PackageManagerService.java revision 54c70a6e1e17e0d5be60eb0d4fd0bd7637b5c1b6
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
22import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
28import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
29import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
30import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
32import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
36import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
37import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
38import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
39import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
40import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
43import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
47import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
48import static android.content.pm.PackageManager.INSTALL_INTERNAL;
49import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
52import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
53import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
54import static android.content.pm.PackageManager.MATCH_ALL;
55import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
56import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
57import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
58import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
59import static android.content.pm.PackageManager.PERMISSION_GRANTED;
60import static android.content.pm.PackageParser.isApkFile;
61import static android.os.Process.PACKAGE_INFO_GID;
62import static android.os.Process.SYSTEM_UID;
63import static android.system.OsConstants.O_CREAT;
64import static android.system.OsConstants.O_RDWR;
65import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
66import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
67import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
68import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
69import static com.android.internal.util.ArrayUtils.appendInt;
70import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
71import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
72import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
73import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
74import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
75
76import android.Manifest;
77import android.app.ActivityManager;
78import android.app.ActivityManagerNative;
79import android.app.AppGlobals;
80import android.app.IActivityManager;
81import android.app.admin.IDevicePolicyManager;
82import android.app.backup.IBackupManager;
83import android.app.usage.UsageStats;
84import android.app.usage.UsageStatsManager;
85import android.content.BroadcastReceiver;
86import android.content.ComponentName;
87import android.content.Context;
88import android.content.IIntentReceiver;
89import android.content.Intent;
90import android.content.IntentFilter;
91import android.content.IntentSender;
92import android.content.IntentSender.SendIntentException;
93import android.content.ServiceConnection;
94import android.content.pm.ActivityInfo;
95import android.content.pm.ApplicationInfo;
96import android.content.pm.FeatureInfo;
97import android.content.pm.IOnPermissionsChangeListener;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.IntentFilterVerificationInfo;
108import android.content.pm.KeySet;
109import android.content.pm.ManifestDigest;
110import android.content.pm.PackageCleanItem;
111import android.content.pm.PackageInfo;
112import android.content.pm.PackageInfoLite;
113import android.content.pm.PackageInstaller;
114import android.content.pm.PackageManager;
115import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
116import android.content.pm.PackageManagerInternal;
117import android.content.pm.PackageParser;
118import android.content.pm.PackageParser.ActivityIntentInfo;
119import android.content.pm.PackageParser.PackageLite;
120import android.content.pm.PackageParser.PackageParserException;
121import android.content.pm.PackageStats;
122import android.content.pm.PackageUserState;
123import android.content.pm.ParceledListSlice;
124import android.content.pm.PermissionGroupInfo;
125import android.content.pm.PermissionInfo;
126import android.content.pm.ProviderInfo;
127import android.content.pm.ResolveInfo;
128import android.content.pm.ServiceInfo;
129import android.content.pm.Signature;
130import android.content.pm.UserInfo;
131import android.content.pm.VerificationParams;
132import android.content.pm.VerifierDeviceIdentity;
133import android.content.pm.VerifierInfo;
134import android.content.res.Resources;
135import android.hardware.display.DisplayManager;
136import android.net.Uri;
137import android.os.Binder;
138import android.os.Build;
139import android.os.Bundle;
140import android.os.Debug;
141import android.os.Environment;
142import android.os.Environment.UserEnvironment;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteCallbackList;
152import android.os.RemoteException;
153import android.os.SELinux;
154import android.os.ServiceManager;
155import android.os.SystemClock;
156import android.os.SystemProperties;
157import android.os.UserHandle;
158import android.os.UserManager;
159import android.os.storage.IMountService;
160import android.os.storage.StorageEventListener;
161import android.os.storage.StorageManager;
162import android.os.storage.VolumeInfo;
163import android.os.storage.VolumeRecord;
164import android.security.KeyStore;
165import android.security.SystemKeyStore;
166import android.system.ErrnoException;
167import android.system.Os;
168import android.system.StructStat;
169import android.text.TextUtils;
170import android.text.format.DateUtils;
171import android.util.ArrayMap;
172import android.util.ArraySet;
173import android.util.AtomicFile;
174import android.util.DisplayMetrics;
175import android.util.EventLog;
176import android.util.ExceptionUtils;
177import android.util.Log;
178import android.util.LogPrinter;
179import android.util.MathUtils;
180import android.util.PrintStreamPrinter;
181import android.util.Slog;
182import android.util.SparseArray;
183import android.util.SparseBooleanArray;
184import android.util.SparseIntArray;
185import android.util.Xml;
186import android.view.Display;
187
188import dalvik.system.DexFile;
189import dalvik.system.VMRuntime;
190
191import libcore.io.IoUtils;
192import libcore.util.EmptyArray;
193
194import com.android.internal.R;
195import com.android.internal.annotations.GuardedBy;
196import com.android.internal.app.IMediaContainerService;
197import com.android.internal.app.ResolverActivity;
198import com.android.internal.content.NativeLibraryHelper;
199import com.android.internal.content.PackageHelper;
200import com.android.internal.os.IParcelFileDescriptorFactory;
201import com.android.internal.os.SomeArgs;
202import com.android.internal.os.Zygote;
203import com.android.internal.util.ArrayUtils;
204import com.android.internal.util.FastPrintWriter;
205import com.android.internal.util.FastXmlSerializer;
206import com.android.internal.util.IndentingPrintWriter;
207import com.android.internal.util.Preconditions;
208import com.android.server.EventLogTags;
209import com.android.server.FgThread;
210import com.android.server.IntentResolver;
211import com.android.server.LocalServices;
212import com.android.server.ServiceThread;
213import com.android.server.SystemConfig;
214import com.android.server.Watchdog;
215import com.android.server.pm.PermissionsState.PermissionState;
216import com.android.server.pm.Settings.DatabaseVersion;
217import com.android.server.storage.DeviceStorageMonitorInternal;
218
219import org.xmlpull.v1.XmlPullParser;
220import org.xmlpull.v1.XmlPullParserException;
221import org.xmlpull.v1.XmlSerializer;
222
223import java.io.BufferedInputStream;
224import java.io.BufferedOutputStream;
225import java.io.BufferedReader;
226import java.io.ByteArrayInputStream;
227import java.io.ByteArrayOutputStream;
228import java.io.File;
229import java.io.FileDescriptor;
230import java.io.FileNotFoundException;
231import java.io.FileOutputStream;
232import java.io.FileReader;
233import java.io.FilenameFilter;
234import java.io.IOException;
235import java.io.InputStream;
236import java.io.PrintWriter;
237import java.nio.charset.StandardCharsets;
238import java.security.NoSuchAlgorithmException;
239import java.security.PublicKey;
240import java.security.cert.CertificateEncodingException;
241import java.security.cert.CertificateException;
242import java.text.SimpleDateFormat;
243import java.util.ArrayList;
244import java.util.Arrays;
245import java.util.Collection;
246import java.util.Collections;
247import java.util.Comparator;
248import java.util.Date;
249import java.util.Iterator;
250import java.util.List;
251import java.util.Map;
252import java.util.Objects;
253import java.util.Set;
254import java.util.concurrent.CountDownLatch;
255import java.util.concurrent.TimeUnit;
256import java.util.concurrent.atomic.AtomicBoolean;
257import java.util.concurrent.atomic.AtomicInteger;
258import java.util.concurrent.atomic.AtomicLong;
259
260/**
261 * Keep track of all those .apks everywhere.
262 *
263 * This is very central to the platform's security; please run the unit
264 * tests whenever making modifications here:
265 *
266runtest -c android.content.pm.PackageManagerTests frameworks-core
267 *
268 * {@hide}
269 */
270public class PackageManagerService extends IPackageManager.Stub {
271    static final String TAG = "PackageManager";
272    static final boolean DEBUG_SETTINGS = false;
273    static final boolean DEBUG_PREFERRED = false;
274    static final boolean DEBUG_UPGRADE = false;
275    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
276    private static final boolean DEBUG_BACKUP = true;
277    private static final boolean DEBUG_INSTALL = false;
278    private static final boolean DEBUG_REMOVE = false;
279    private static final boolean DEBUG_BROADCASTS = false;
280    private static final boolean DEBUG_SHOW_INFO = false;
281    private static final boolean DEBUG_PACKAGE_INFO = false;
282    private static final boolean DEBUG_INTENT_MATCHING = false;
283    private static final boolean DEBUG_PACKAGE_SCANNING = false;
284    private static final boolean DEBUG_VERIFY = false;
285    private static final boolean DEBUG_DEXOPT = false;
286    private static final boolean DEBUG_ABI_SELECTION = false;
287
288    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
289
290    private static final int RADIO_UID = Process.PHONE_UID;
291    private static final int LOG_UID = Process.LOG_UID;
292    private static final int NFC_UID = Process.NFC_UID;
293    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
294    private static final int SHELL_UID = Process.SHELL_UID;
295
296    // Cap the size of permission trees that 3rd party apps can define
297    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
298
299    // Suffix used during package installation when copying/moving
300    // package apks to install directory.
301    private static final String INSTALL_PACKAGE_SUFFIX = "-";
302
303    static final int SCAN_NO_DEX = 1<<1;
304    static final int SCAN_FORCE_DEX = 1<<2;
305    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
306    static final int SCAN_NEW_INSTALL = 1<<4;
307    static final int SCAN_NO_PATHS = 1<<5;
308    static final int SCAN_UPDATE_TIME = 1<<6;
309    static final int SCAN_DEFER_DEX = 1<<7;
310    static final int SCAN_BOOTING = 1<<8;
311    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
312    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
313    static final int SCAN_REQUIRE_KNOWN = 1<<12;
314    static final int SCAN_MOVE = 1<<13;
315    static final int SCAN_INITIAL = 1<<14;
316
317    static final int REMOVE_CHATTY = 1<<16;
318
319    private static final int[] EMPTY_INT_ARRAY = new int[0];
320
321    /**
322     * Timeout (in milliseconds) after which the watchdog should declare that
323     * our handler thread is wedged.  The usual default for such things is one
324     * minute but we sometimes do very lengthy I/O operations on this thread,
325     * such as installing multi-gigabyte applications, so ours needs to be longer.
326     */
327    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
328
329    /**
330     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
331     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
332     * settings entry if available, otherwise we use the hardcoded default.  If it's been
333     * more than this long since the last fstrim, we force one during the boot sequence.
334     *
335     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
336     * one gets run at the next available charging+idle time.  This final mandatory
337     * no-fstrim check kicks in only of the other scheduling criteria is never met.
338     */
339    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
340
341    /**
342     * Whether verification is enabled by default.
343     */
344    private static final boolean DEFAULT_VERIFY_ENABLE = true;
345
346    /**
347     * The default maximum time to wait for the verification agent to return in
348     * milliseconds.
349     */
350    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
351
352    /**
353     * The default response for package verification timeout.
354     *
355     * This can be either PackageManager.VERIFICATION_ALLOW or
356     * PackageManager.VERIFICATION_REJECT.
357     */
358    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
359
360    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
361
362    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
363            DEFAULT_CONTAINER_PACKAGE,
364            "com.android.defcontainer.DefaultContainerService");
365
366    private static final String KILL_APP_REASON_GIDS_CHANGED =
367            "permission grant or revoke changed gids";
368
369    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
370            "permissions revoked";
371
372    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
373
374    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
375
376    /** Permission grant: not grant the permission. */
377    private static final int GRANT_DENIED = 1;
378
379    /** Permission grant: grant the permission as an install permission. */
380    private static final int GRANT_INSTALL = 2;
381
382    /** Permission grant: grant the permission as an install permission for a legacy app. */
383    private static final int GRANT_INSTALL_LEGACY = 3;
384
385    /** Permission grant: grant the permission as a runtime one. */
386    private static final int GRANT_RUNTIME = 4;
387
388    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
389    private static final int GRANT_UPGRADE = 5;
390
391    /** Canonical intent used to identify what counts as a "web browser" app */
392    private static final Intent sBrowserIntent;
393    static {
394        sBrowserIntent = new Intent();
395        sBrowserIntent.setAction(Intent.ACTION_VIEW);
396        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
397        sBrowserIntent.setData(Uri.parse("http:"));
398    }
399
400    final ServiceThread mHandlerThread;
401
402    final PackageHandler mHandler;
403
404    /**
405     * Messages for {@link #mHandler} that need to wait for system ready before
406     * being dispatched.
407     */
408    private ArrayList<Message> mPostSystemReadyMessages;
409
410    final int mSdkVersion = Build.VERSION.SDK_INT;
411
412    final Context mContext;
413    final boolean mFactoryTest;
414    final boolean mOnlyCore;
415    final boolean mLazyDexOpt;
416    final long mDexOptLRUThresholdInMills;
417    final DisplayMetrics mMetrics;
418    final int mDefParseFlags;
419    final String[] mSeparateProcesses;
420    final boolean mIsUpgrade;
421
422    // This is where all application persistent data goes.
423    final File mAppDataDir;
424
425    // This is where all application persistent data goes for secondary users.
426    final File mUserAppDataDir;
427
428    /** The location for ASEC container files on internal storage. */
429    final String mAsecInternalPath;
430
431    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
432    // LOCK HELD.  Can be called with mInstallLock held.
433    @GuardedBy("mInstallLock")
434    final Installer mInstaller;
435
436    /** Directory where installed third-party apps stored */
437    final File mAppInstallDir;
438
439    /**
440     * Directory to which applications installed internally have their
441     * 32 bit native libraries copied.
442     */
443    private File mAppLib32InstallDir;
444
445    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
446    // apps.
447    final File mDrmAppPrivateInstallDir;
448
449    // ----------------------------------------------------------------
450
451    // Lock for state used when installing and doing other long running
452    // operations.  Methods that must be called with this lock held have
453    // the suffix "LI".
454    final Object mInstallLock = new Object();
455
456    // ----------------------------------------------------------------
457
458    // Keys are String (package name), values are Package.  This also serves
459    // as the lock for the global state.  Methods that must be called with
460    // this lock held have the prefix "LP".
461    @GuardedBy("mPackages")
462    final ArrayMap<String, PackageParser.Package> mPackages =
463            new ArrayMap<String, PackageParser.Package>();
464
465    // Tracks available target package names -> overlay package paths.
466    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
467        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
468
469    final Settings mSettings;
470    boolean mRestoredSettings;
471
472    // System configuration read by SystemConfig.
473    final int[] mGlobalGids;
474    final SparseArray<ArraySet<String>> mSystemPermissions;
475    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
476
477    // If mac_permissions.xml was found for seinfo labeling.
478    boolean mFoundPolicyFile;
479
480    // If a recursive restorecon of /data/data/<pkg> is needed.
481    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
482
483    public static final class SharedLibraryEntry {
484        public final String path;
485        public final String apk;
486
487        SharedLibraryEntry(String _path, String _apk) {
488            path = _path;
489            apk = _apk;
490        }
491    }
492
493    // Currently known shared libraries.
494    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
495            new ArrayMap<String, SharedLibraryEntry>();
496
497    // All available activities, for your resolving pleasure.
498    final ActivityIntentResolver mActivities =
499            new ActivityIntentResolver();
500
501    // All available receivers, for your resolving pleasure.
502    final ActivityIntentResolver mReceivers =
503            new ActivityIntentResolver();
504
505    // All available services, for your resolving pleasure.
506    final ServiceIntentResolver mServices = new ServiceIntentResolver();
507
508    // All available providers, for your resolving pleasure.
509    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
510
511    // Mapping from provider base names (first directory in content URI codePath)
512    // to the provider information.
513    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
514            new ArrayMap<String, PackageParser.Provider>();
515
516    // Mapping from instrumentation class names to info about them.
517    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
518            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
519
520    // Mapping from permission names to info about them.
521    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
522            new ArrayMap<String, PackageParser.PermissionGroup>();
523
524    // Packages whose data we have transfered into another package, thus
525    // should no longer exist.
526    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
527
528    // Broadcast actions that are only available to the system.
529    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
530
531    /** List of packages waiting for verification. */
532    final SparseArray<PackageVerificationState> mPendingVerification
533            = new SparseArray<PackageVerificationState>();
534
535    /** Set of packages associated with each app op permission. */
536    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
537
538    final PackageInstallerService mInstallerService;
539
540    private final PackageDexOptimizer mPackageDexOptimizer;
541
542    private AtomicInteger mNextMoveId = new AtomicInteger();
543    private final MoveCallbacks mMoveCallbacks;
544
545    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
546
547    // Cache of users who need badging.
548    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
549
550    /** Token for keys in mPendingVerification. */
551    private int mPendingVerificationToken = 0;
552
553    volatile boolean mSystemReady;
554    volatile boolean mSafeMode;
555    volatile boolean mHasSystemUidErrors;
556
557    ApplicationInfo mAndroidApplication;
558    final ActivityInfo mResolveActivity = new ActivityInfo();
559    final ResolveInfo mResolveInfo = new ResolveInfo();
560    ComponentName mResolveComponentName;
561    PackageParser.Package mPlatformPackage;
562    ComponentName mCustomResolverComponentName;
563
564    boolean mResolverReplaced = false;
565
566    private final ComponentName mIntentFilterVerifierComponent;
567    private int mIntentFilterVerificationToken = 0;
568
569    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
570            = new SparseArray<IntentFilterVerificationState>();
571
572    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
573            new DefaultPermissionGrantPolicy(this);
574
575    private static class IFVerificationParams {
576        PackageParser.Package pkg;
577        boolean replacing;
578        int userId;
579        int verifierUid;
580
581        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
582                int _userId, int _verifierUid) {
583            pkg = _pkg;
584            replacing = _replacing;
585            userId = _userId;
586            replacing = _replacing;
587            verifierUid = _verifierUid;
588        }
589    }
590
591    private interface IntentFilterVerifier<T extends IntentFilter> {
592        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
593                                               T filter, String packageName);
594        void startVerifications(int userId);
595        void receiveVerificationResponse(int verificationId);
596    }
597
598    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
599        private Context mContext;
600        private ComponentName mIntentFilterVerifierComponent;
601        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
602
603        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
604            mContext = context;
605            mIntentFilterVerifierComponent = verifierComponent;
606        }
607
608        private String getDefaultScheme() {
609            return IntentFilter.SCHEME_HTTPS;
610        }
611
612        @Override
613        public void startVerifications(int userId) {
614            // Launch verifications requests
615            int count = mCurrentIntentFilterVerifications.size();
616            for (int n=0; n<count; n++) {
617                int verificationId = mCurrentIntentFilterVerifications.get(n);
618                final IntentFilterVerificationState ivs =
619                        mIntentFilterVerificationStates.get(verificationId);
620
621                String packageName = ivs.getPackageName();
622
623                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
624                final int filterCount = filters.size();
625                ArraySet<String> domainsSet = new ArraySet<>();
626                for (int m=0; m<filterCount; m++) {
627                    PackageParser.ActivityIntentInfo filter = filters.get(m);
628                    domainsSet.addAll(filter.getHostsList());
629                }
630                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
631                synchronized (mPackages) {
632                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
633                            packageName, domainsList) != null) {
634                        scheduleWriteSettingsLocked();
635                    }
636                }
637                sendVerificationRequest(userId, verificationId, ivs);
638            }
639            mCurrentIntentFilterVerifications.clear();
640        }
641
642        private void sendVerificationRequest(int userId, int verificationId,
643                IntentFilterVerificationState ivs) {
644
645            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
646            verificationIntent.putExtra(
647                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
648                    verificationId);
649            verificationIntent.putExtra(
650                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
651                    getDefaultScheme());
652            verificationIntent.putExtra(
653                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
654                    ivs.getHostsString());
655            verificationIntent.putExtra(
656                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
657                    ivs.getPackageName());
658            verificationIntent.setComponent(mIntentFilterVerifierComponent);
659            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
660
661            UserHandle user = new UserHandle(userId);
662            mContext.sendBroadcastAsUser(verificationIntent, user);
663            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
664                    "Sending IntentFilter verification broadcast");
665        }
666
667        public void receiveVerificationResponse(int verificationId) {
668            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
669
670            final boolean verified = ivs.isVerified();
671
672            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
673            final int count = filters.size();
674            if (DEBUG_DOMAIN_VERIFICATION) {
675                Slog.i(TAG, "Received verification response " + verificationId
676                        + " for " + count + " filters, verified=" + verified);
677            }
678            for (int n=0; n<count; n++) {
679                PackageParser.ActivityIntentInfo filter = filters.get(n);
680                filter.setVerified(verified);
681
682                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
683                        + " verified with result:" + verified + " and hosts:"
684                        + ivs.getHostsString());
685            }
686
687            mIntentFilterVerificationStates.remove(verificationId);
688
689            final String packageName = ivs.getPackageName();
690            IntentFilterVerificationInfo ivi = null;
691
692            synchronized (mPackages) {
693                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
694            }
695            if (ivi == null) {
696                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
697                        + verificationId + " packageName:" + packageName);
698                return;
699            }
700            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
701                    "Updating IntentFilterVerificationInfo for verificationId:" + verificationId);
702
703            synchronized (mPackages) {
704                if (verified) {
705                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
706                } else {
707                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
708                }
709                scheduleWriteSettingsLocked();
710
711                final int userId = ivs.getUserId();
712                if (userId != UserHandle.USER_ALL) {
713                    final int userStatus =
714                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
715
716                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
717                    boolean needUpdate = false;
718
719                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
720                    // already been set by the User thru the Disambiguation dialog
721                    switch (userStatus) {
722                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
723                            if (verified) {
724                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
725                            } else {
726                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
727                            }
728                            needUpdate = true;
729                            break;
730
731                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
732                            if (verified) {
733                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
734                                needUpdate = true;
735                            }
736                            break;
737
738                        default:
739                            // Nothing to do
740                    }
741
742                    if (needUpdate) {
743                        mSettings.updateIntentFilterVerificationStatusLPw(
744                                packageName, updatedStatus, userId);
745                        scheduleWritePackageRestrictionsLocked(userId);
746                    }
747                }
748            }
749        }
750
751        @Override
752        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
753                    ActivityIntentInfo filter, String packageName) {
754            if (!hasValidDomains(filter)) {
755                return false;
756            }
757            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
758            if (ivs == null) {
759                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
760                        packageName);
761            }
762            if (DEBUG_DOMAIN_VERIFICATION) {
763                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
764            }
765            ivs.addFilter(filter);
766            return true;
767        }
768
769        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
770                int userId, int verificationId, String packageName) {
771            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
772                    verifierUid, userId, packageName);
773            ivs.setPendingState();
774            synchronized (mPackages) {
775                mIntentFilterVerificationStates.append(verificationId, ivs);
776                mCurrentIntentFilterVerifications.add(verificationId);
777            }
778            return ivs;
779        }
780    }
781
782    private static boolean hasValidDomains(ActivityIntentInfo filter) {
783        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
784                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
785        if (!hasHTTPorHTTPS) {
786            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
787                    "IntentFilter does not contain any HTTP or HTTPS data scheme");
788            return false;
789        }
790        return true;
791    }
792
793    private IntentFilterVerifier mIntentFilterVerifier;
794
795    // Set of pending broadcasts for aggregating enable/disable of components.
796    static class PendingPackageBroadcasts {
797        // for each user id, a map of <package name -> components within that package>
798        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
799
800        public PendingPackageBroadcasts() {
801            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
802        }
803
804        public ArrayList<String> get(int userId, String packageName) {
805            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
806            return packages.get(packageName);
807        }
808
809        public void put(int userId, String packageName, ArrayList<String> components) {
810            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
811            packages.put(packageName, components);
812        }
813
814        public void remove(int userId, String packageName) {
815            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
816            if (packages != null) {
817                packages.remove(packageName);
818            }
819        }
820
821        public void remove(int userId) {
822            mUidMap.remove(userId);
823        }
824
825        public int userIdCount() {
826            return mUidMap.size();
827        }
828
829        public int userIdAt(int n) {
830            return mUidMap.keyAt(n);
831        }
832
833        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
834            return mUidMap.get(userId);
835        }
836
837        public int size() {
838            // total number of pending broadcast entries across all userIds
839            int num = 0;
840            for (int i = 0; i< mUidMap.size(); i++) {
841                num += mUidMap.valueAt(i).size();
842            }
843            return num;
844        }
845
846        public void clear() {
847            mUidMap.clear();
848        }
849
850        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
851            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
852            if (map == null) {
853                map = new ArrayMap<String, ArrayList<String>>();
854                mUidMap.put(userId, map);
855            }
856            return map;
857        }
858    }
859    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
860
861    // Service Connection to remote media container service to copy
862    // package uri's from external media onto secure containers
863    // or internal storage.
864    private IMediaContainerService mContainerService = null;
865
866    static final int SEND_PENDING_BROADCAST = 1;
867    static final int MCS_BOUND = 3;
868    static final int END_COPY = 4;
869    static final int INIT_COPY = 5;
870    static final int MCS_UNBIND = 6;
871    static final int START_CLEANING_PACKAGE = 7;
872    static final int FIND_INSTALL_LOC = 8;
873    static final int POST_INSTALL = 9;
874    static final int MCS_RECONNECT = 10;
875    static final int MCS_GIVE_UP = 11;
876    static final int UPDATED_MEDIA_STATUS = 12;
877    static final int WRITE_SETTINGS = 13;
878    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
879    static final int PACKAGE_VERIFIED = 15;
880    static final int CHECK_PENDING_VERIFICATION = 16;
881    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
882    static final int INTENT_FILTER_VERIFIED = 18;
883
884    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
885
886    // Delay time in millisecs
887    static final int BROADCAST_DELAY = 10 * 1000;
888
889    static UserManagerService sUserManager;
890
891    // Stores a list of users whose package restrictions file needs to be updated
892    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
893
894    final private DefaultContainerConnection mDefContainerConn =
895            new DefaultContainerConnection();
896    class DefaultContainerConnection implements ServiceConnection {
897        public void onServiceConnected(ComponentName name, IBinder service) {
898            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
899            IMediaContainerService imcs =
900                IMediaContainerService.Stub.asInterface(service);
901            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
902        }
903
904        public void onServiceDisconnected(ComponentName name) {
905            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
906        }
907    }
908
909    // Recordkeeping of restore-after-install operations that are currently in flight
910    // between the Package Manager and the Backup Manager
911    class PostInstallData {
912        public InstallArgs args;
913        public PackageInstalledInfo res;
914
915        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
916            args = _a;
917            res = _r;
918        }
919    }
920
921    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
922    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
923
924    // XML tags for backup/restore of various bits of state
925    private static final String TAG_PREFERRED_BACKUP = "pa";
926    private static final String TAG_DEFAULT_APPS = "da";
927    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
928
929    private final String mRequiredVerifierPackage;
930
931    private final PackageUsage mPackageUsage = new PackageUsage();
932
933    private class PackageUsage {
934        private static final int WRITE_INTERVAL
935            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
936
937        private final Object mFileLock = new Object();
938        private final AtomicLong mLastWritten = new AtomicLong(0);
939        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
940
941        private boolean mIsHistoricalPackageUsageAvailable = true;
942
943        boolean isHistoricalPackageUsageAvailable() {
944            return mIsHistoricalPackageUsageAvailable;
945        }
946
947        void write(boolean force) {
948            if (force) {
949                writeInternal();
950                return;
951            }
952            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
953                && !DEBUG_DEXOPT) {
954                return;
955            }
956            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
957                new Thread("PackageUsage_DiskWriter") {
958                    @Override
959                    public void run() {
960                        try {
961                            writeInternal();
962                        } finally {
963                            mBackgroundWriteRunning.set(false);
964                        }
965                    }
966                }.start();
967            }
968        }
969
970        private void writeInternal() {
971            synchronized (mPackages) {
972                synchronized (mFileLock) {
973                    AtomicFile file = getFile();
974                    FileOutputStream f = null;
975                    try {
976                        f = file.startWrite();
977                        BufferedOutputStream out = new BufferedOutputStream(f);
978                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
979                        StringBuilder sb = new StringBuilder();
980                        for (PackageParser.Package pkg : mPackages.values()) {
981                            if (pkg.mLastPackageUsageTimeInMills == 0) {
982                                continue;
983                            }
984                            sb.setLength(0);
985                            sb.append(pkg.packageName);
986                            sb.append(' ');
987                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
988                            sb.append('\n');
989                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
990                        }
991                        out.flush();
992                        file.finishWrite(f);
993                    } catch (IOException e) {
994                        if (f != null) {
995                            file.failWrite(f);
996                        }
997                        Log.e(TAG, "Failed to write package usage times", e);
998                    }
999                }
1000            }
1001            mLastWritten.set(SystemClock.elapsedRealtime());
1002        }
1003
1004        void readLP() {
1005            synchronized (mFileLock) {
1006                AtomicFile file = getFile();
1007                BufferedInputStream in = null;
1008                try {
1009                    in = new BufferedInputStream(file.openRead());
1010                    StringBuffer sb = new StringBuffer();
1011                    while (true) {
1012                        String packageName = readToken(in, sb, ' ');
1013                        if (packageName == null) {
1014                            break;
1015                        }
1016                        String timeInMillisString = readToken(in, sb, '\n');
1017                        if (timeInMillisString == null) {
1018                            throw new IOException("Failed to find last usage time for package "
1019                                                  + packageName);
1020                        }
1021                        PackageParser.Package pkg = mPackages.get(packageName);
1022                        if (pkg == null) {
1023                            continue;
1024                        }
1025                        long timeInMillis;
1026                        try {
1027                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1028                        } catch (NumberFormatException e) {
1029                            throw new IOException("Failed to parse " + timeInMillisString
1030                                                  + " as a long.", e);
1031                        }
1032                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1033                    }
1034                } catch (FileNotFoundException expected) {
1035                    mIsHistoricalPackageUsageAvailable = false;
1036                } catch (IOException e) {
1037                    Log.w(TAG, "Failed to read package usage times", e);
1038                } finally {
1039                    IoUtils.closeQuietly(in);
1040                }
1041            }
1042            mLastWritten.set(SystemClock.elapsedRealtime());
1043        }
1044
1045        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1046                throws IOException {
1047            sb.setLength(0);
1048            while (true) {
1049                int ch = in.read();
1050                if (ch == -1) {
1051                    if (sb.length() == 0) {
1052                        return null;
1053                    }
1054                    throw new IOException("Unexpected EOF");
1055                }
1056                if (ch == endOfToken) {
1057                    return sb.toString();
1058                }
1059                sb.append((char)ch);
1060            }
1061        }
1062
1063        private AtomicFile getFile() {
1064            File dataDir = Environment.getDataDirectory();
1065            File systemDir = new File(dataDir, "system");
1066            File fname = new File(systemDir, "package-usage.list");
1067            return new AtomicFile(fname);
1068        }
1069    }
1070
1071    class PackageHandler extends Handler {
1072        private boolean mBound = false;
1073        final ArrayList<HandlerParams> mPendingInstalls =
1074            new ArrayList<HandlerParams>();
1075
1076        private boolean connectToService() {
1077            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1078                    " DefaultContainerService");
1079            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1080            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1081            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1082                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1083                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1084                mBound = true;
1085                return true;
1086            }
1087            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1088            return false;
1089        }
1090
1091        private void disconnectService() {
1092            mContainerService = null;
1093            mBound = false;
1094            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1095            mContext.unbindService(mDefContainerConn);
1096            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1097        }
1098
1099        PackageHandler(Looper looper) {
1100            super(looper);
1101        }
1102
1103        public void handleMessage(Message msg) {
1104            try {
1105                doHandleMessage(msg);
1106            } finally {
1107                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1108            }
1109        }
1110
1111        void doHandleMessage(Message msg) {
1112            switch (msg.what) {
1113                case INIT_COPY: {
1114                    HandlerParams params = (HandlerParams) msg.obj;
1115                    int idx = mPendingInstalls.size();
1116                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1117                    // If a bind was already initiated we dont really
1118                    // need to do anything. The pending install
1119                    // will be processed later on.
1120                    if (!mBound) {
1121                        // If this is the only one pending we might
1122                        // have to bind to the service again.
1123                        if (!connectToService()) {
1124                            Slog.e(TAG, "Failed to bind to media container service");
1125                            params.serviceError();
1126                            return;
1127                        } else {
1128                            // Once we bind to the service, the first
1129                            // pending request will be processed.
1130                            mPendingInstalls.add(idx, params);
1131                        }
1132                    } else {
1133                        mPendingInstalls.add(idx, params);
1134                        // Already bound to the service. Just make
1135                        // sure we trigger off processing the first request.
1136                        if (idx == 0) {
1137                            mHandler.sendEmptyMessage(MCS_BOUND);
1138                        }
1139                    }
1140                    break;
1141                }
1142                case MCS_BOUND: {
1143                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1144                    if (msg.obj != null) {
1145                        mContainerService = (IMediaContainerService) msg.obj;
1146                    }
1147                    if (mContainerService == null) {
1148                        if (!mBound) {
1149                            // Something seriously wrong since we are not bound and we are not
1150                            // waiting for connection. Bail out.
1151                            Slog.e(TAG, "Cannot bind to media container service");
1152                            for (HandlerParams params : mPendingInstalls) {
1153                                // Indicate service bind error
1154                                params.serviceError();
1155                            }
1156                            mPendingInstalls.clear();
1157                        } else {
1158                            Slog.w(TAG, "Waiting to connect to media container service");
1159                        }
1160                    } else if (mPendingInstalls.size() > 0) {
1161                        HandlerParams params = mPendingInstalls.get(0);
1162                        if (params != null) {
1163                            if (params.startCopy()) {
1164                                // We are done...  look for more work or to
1165                                // go idle.
1166                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1167                                        "Checking for more work or unbind...");
1168                                // Delete pending install
1169                                if (mPendingInstalls.size() > 0) {
1170                                    mPendingInstalls.remove(0);
1171                                }
1172                                if (mPendingInstalls.size() == 0) {
1173                                    if (mBound) {
1174                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1175                                                "Posting delayed MCS_UNBIND");
1176                                        removeMessages(MCS_UNBIND);
1177                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1178                                        // Unbind after a little delay, to avoid
1179                                        // continual thrashing.
1180                                        sendMessageDelayed(ubmsg, 10000);
1181                                    }
1182                                } else {
1183                                    // There are more pending requests in queue.
1184                                    // Just post MCS_BOUND message to trigger processing
1185                                    // of next pending install.
1186                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1187                                            "Posting MCS_BOUND for next work");
1188                                    mHandler.sendEmptyMessage(MCS_BOUND);
1189                                }
1190                            }
1191                        }
1192                    } else {
1193                        // Should never happen ideally.
1194                        Slog.w(TAG, "Empty queue");
1195                    }
1196                    break;
1197                }
1198                case MCS_RECONNECT: {
1199                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1200                    if (mPendingInstalls.size() > 0) {
1201                        if (mBound) {
1202                            disconnectService();
1203                        }
1204                        if (!connectToService()) {
1205                            Slog.e(TAG, "Failed to bind to media container service");
1206                            for (HandlerParams params : mPendingInstalls) {
1207                                // Indicate service bind error
1208                                params.serviceError();
1209                            }
1210                            mPendingInstalls.clear();
1211                        }
1212                    }
1213                    break;
1214                }
1215                case MCS_UNBIND: {
1216                    // If there is no actual work left, then time to unbind.
1217                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1218
1219                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1220                        if (mBound) {
1221                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1222
1223                            disconnectService();
1224                        }
1225                    } else if (mPendingInstalls.size() > 0) {
1226                        // There are more pending requests in queue.
1227                        // Just post MCS_BOUND message to trigger processing
1228                        // of next pending install.
1229                        mHandler.sendEmptyMessage(MCS_BOUND);
1230                    }
1231
1232                    break;
1233                }
1234                case MCS_GIVE_UP: {
1235                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1236                    mPendingInstalls.remove(0);
1237                    break;
1238                }
1239                case SEND_PENDING_BROADCAST: {
1240                    String packages[];
1241                    ArrayList<String> components[];
1242                    int size = 0;
1243                    int uids[];
1244                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1245                    synchronized (mPackages) {
1246                        if (mPendingBroadcasts == null) {
1247                            return;
1248                        }
1249                        size = mPendingBroadcasts.size();
1250                        if (size <= 0) {
1251                            // Nothing to be done. Just return
1252                            return;
1253                        }
1254                        packages = new String[size];
1255                        components = new ArrayList[size];
1256                        uids = new int[size];
1257                        int i = 0;  // filling out the above arrays
1258
1259                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1260                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1261                            Iterator<Map.Entry<String, ArrayList<String>>> it
1262                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1263                                            .entrySet().iterator();
1264                            while (it.hasNext() && i < size) {
1265                                Map.Entry<String, ArrayList<String>> ent = it.next();
1266                                packages[i] = ent.getKey();
1267                                components[i] = ent.getValue();
1268                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1269                                uids[i] = (ps != null)
1270                                        ? UserHandle.getUid(packageUserId, ps.appId)
1271                                        : -1;
1272                                i++;
1273                            }
1274                        }
1275                        size = i;
1276                        mPendingBroadcasts.clear();
1277                    }
1278                    // Send broadcasts
1279                    for (int i = 0; i < size; i++) {
1280                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1281                    }
1282                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1283                    break;
1284                }
1285                case START_CLEANING_PACKAGE: {
1286                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1287                    final String packageName = (String)msg.obj;
1288                    final int userId = msg.arg1;
1289                    final boolean andCode = msg.arg2 != 0;
1290                    synchronized (mPackages) {
1291                        if (userId == UserHandle.USER_ALL) {
1292                            int[] users = sUserManager.getUserIds();
1293                            for (int user : users) {
1294                                mSettings.addPackageToCleanLPw(
1295                                        new PackageCleanItem(user, packageName, andCode));
1296                            }
1297                        } else {
1298                            mSettings.addPackageToCleanLPw(
1299                                    new PackageCleanItem(userId, packageName, andCode));
1300                        }
1301                    }
1302                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1303                    startCleaningPackages();
1304                } break;
1305                case POST_INSTALL: {
1306                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1307                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1308                    mRunningInstalls.delete(msg.arg1);
1309                    boolean deleteOld = false;
1310
1311                    if (data != null) {
1312                        InstallArgs args = data.args;
1313                        PackageInstalledInfo res = data.res;
1314
1315                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1316                            final String packageName = res.pkg.applicationInfo.packageName;
1317                            res.removedInfo.sendBroadcast(false, true, false);
1318                            Bundle extras = new Bundle(1);
1319                            extras.putInt(Intent.EXTRA_UID, res.uid);
1320
1321                            // Now that we successfully installed the package, grant runtime
1322                            // permissions if requested before broadcasting the install.
1323                            if ((args.installFlags
1324                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1325                                grantRequestedRuntimePermissions(res.pkg,
1326                                        args.user.getIdentifier());
1327                            }
1328
1329                            // Determine the set of users who are adding this
1330                            // package for the first time vs. those who are seeing
1331                            // an update.
1332                            int[] firstUsers;
1333                            int[] updateUsers = new int[0];
1334                            if (res.origUsers == null || res.origUsers.length == 0) {
1335                                firstUsers = res.newUsers;
1336                            } else {
1337                                firstUsers = new int[0];
1338                                for (int i=0; i<res.newUsers.length; i++) {
1339                                    int user = res.newUsers[i];
1340                                    boolean isNew = true;
1341                                    for (int j=0; j<res.origUsers.length; j++) {
1342                                        if (res.origUsers[j] == user) {
1343                                            isNew = false;
1344                                            break;
1345                                        }
1346                                    }
1347                                    if (isNew) {
1348                                        int[] newFirst = new int[firstUsers.length+1];
1349                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1350                                                firstUsers.length);
1351                                        newFirst[firstUsers.length] = user;
1352                                        firstUsers = newFirst;
1353                                    } else {
1354                                        int[] newUpdate = new int[updateUsers.length+1];
1355                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1356                                                updateUsers.length);
1357                                        newUpdate[updateUsers.length] = user;
1358                                        updateUsers = newUpdate;
1359                                    }
1360                                }
1361                            }
1362                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1363                                    packageName, extras, null, null, firstUsers);
1364                            final boolean update = res.removedInfo.removedPackage != null;
1365                            if (update) {
1366                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1367                            }
1368                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1369                                    packageName, extras, null, null, updateUsers);
1370                            if (update) {
1371                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1372                                        packageName, extras, null, null, updateUsers);
1373                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1374                                        null, null, packageName, null, updateUsers);
1375
1376                                // treat asec-hosted packages like removable media on upgrade
1377                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1378                                    if (DEBUG_INSTALL) {
1379                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1380                                                + " is ASEC-hosted -> AVAILABLE");
1381                                    }
1382                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1383                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1384                                    pkgList.add(packageName);
1385                                    sendResourcesChangedBroadcast(true, true,
1386                                            pkgList,uidArray, null);
1387                                }
1388                            }
1389                            if (res.removedInfo.args != null) {
1390                                // Remove the replaced package's older resources safely now
1391                                deleteOld = true;
1392                            }
1393
1394                            // If this app is a browser and it's newly-installed for some
1395                            // users, clear any default-browser state in those users
1396                            if (firstUsers.length > 0) {
1397                                // the app's nature doesn't depend on the user, so we can just
1398                                // check its browser nature in any user and generalize.
1399                                if (packageIsBrowser(packageName, firstUsers[0])) {
1400                                    synchronized (mPackages) {
1401                                        for (int userId : firstUsers) {
1402                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1403                                        }
1404                                    }
1405                                }
1406                            }
1407                            // Log current value of "unknown sources" setting
1408                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1409                                getUnknownSourcesSettings());
1410                        }
1411                        // Force a gc to clear up things
1412                        Runtime.getRuntime().gc();
1413                        // We delete after a gc for applications  on sdcard.
1414                        if (deleteOld) {
1415                            synchronized (mInstallLock) {
1416                                res.removedInfo.args.doPostDeleteLI(true);
1417                            }
1418                        }
1419                        if (args.observer != null) {
1420                            try {
1421                                Bundle extras = extrasForInstallResult(res);
1422                                args.observer.onPackageInstalled(res.name, res.returnCode,
1423                                        res.returnMsg, extras);
1424                            } catch (RemoteException e) {
1425                                Slog.i(TAG, "Observer no longer exists.");
1426                            }
1427                        }
1428                    } else {
1429                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1430                    }
1431                } break;
1432                case UPDATED_MEDIA_STATUS: {
1433                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1434                    boolean reportStatus = msg.arg1 == 1;
1435                    boolean doGc = msg.arg2 == 1;
1436                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1437                    if (doGc) {
1438                        // Force a gc to clear up stale containers.
1439                        Runtime.getRuntime().gc();
1440                    }
1441                    if (msg.obj != null) {
1442                        @SuppressWarnings("unchecked")
1443                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1444                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1445                        // Unload containers
1446                        unloadAllContainers(args);
1447                    }
1448                    if (reportStatus) {
1449                        try {
1450                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1451                            PackageHelper.getMountService().finishMediaUpdate();
1452                        } catch (RemoteException e) {
1453                            Log.e(TAG, "MountService not running?");
1454                        }
1455                    }
1456                } break;
1457                case WRITE_SETTINGS: {
1458                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1459                    synchronized (mPackages) {
1460                        removeMessages(WRITE_SETTINGS);
1461                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1462                        mSettings.writeLPr();
1463                        mDirtyUsers.clear();
1464                    }
1465                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1466                } break;
1467                case WRITE_PACKAGE_RESTRICTIONS: {
1468                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1469                    synchronized (mPackages) {
1470                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1471                        for (int userId : mDirtyUsers) {
1472                            mSettings.writePackageRestrictionsLPr(userId);
1473                        }
1474                        mDirtyUsers.clear();
1475                    }
1476                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1477                } break;
1478                case CHECK_PENDING_VERIFICATION: {
1479                    final int verificationId = msg.arg1;
1480                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1481
1482                    if ((state != null) && !state.timeoutExtended()) {
1483                        final InstallArgs args = state.getInstallArgs();
1484                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1485
1486                        Slog.i(TAG, "Verification timed out for " + originUri);
1487                        mPendingVerification.remove(verificationId);
1488
1489                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1490
1491                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1492                            Slog.i(TAG, "Continuing with installation of " + originUri);
1493                            state.setVerifierResponse(Binder.getCallingUid(),
1494                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1495                            broadcastPackageVerified(verificationId, originUri,
1496                                    PackageManager.VERIFICATION_ALLOW,
1497                                    state.getInstallArgs().getUser());
1498                            try {
1499                                ret = args.copyApk(mContainerService, true);
1500                            } catch (RemoteException e) {
1501                                Slog.e(TAG, "Could not contact the ContainerService");
1502                            }
1503                        } else {
1504                            broadcastPackageVerified(verificationId, originUri,
1505                                    PackageManager.VERIFICATION_REJECT,
1506                                    state.getInstallArgs().getUser());
1507                        }
1508
1509                        processPendingInstall(args, ret);
1510                        mHandler.sendEmptyMessage(MCS_UNBIND);
1511                    }
1512                    break;
1513                }
1514                case PACKAGE_VERIFIED: {
1515                    final int verificationId = msg.arg1;
1516
1517                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1518                    if (state == null) {
1519                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1520                        break;
1521                    }
1522
1523                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1524
1525                    state.setVerifierResponse(response.callerUid, response.code);
1526
1527                    if (state.isVerificationComplete()) {
1528                        mPendingVerification.remove(verificationId);
1529
1530                        final InstallArgs args = state.getInstallArgs();
1531                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1532
1533                        int ret;
1534                        if (state.isInstallAllowed()) {
1535                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1536                            broadcastPackageVerified(verificationId, originUri,
1537                                    response.code, state.getInstallArgs().getUser());
1538                            try {
1539                                ret = args.copyApk(mContainerService, true);
1540                            } catch (RemoteException e) {
1541                                Slog.e(TAG, "Could not contact the ContainerService");
1542                            }
1543                        } else {
1544                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1545                        }
1546
1547                        processPendingInstall(args, ret);
1548
1549                        mHandler.sendEmptyMessage(MCS_UNBIND);
1550                    }
1551
1552                    break;
1553                }
1554                case START_INTENT_FILTER_VERIFICATIONS: {
1555                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1556                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1557                            params.replacing, params.pkg);
1558                    break;
1559                }
1560                case INTENT_FILTER_VERIFIED: {
1561                    final int verificationId = msg.arg1;
1562
1563                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1564                            verificationId);
1565                    if (state == null) {
1566                        Slog.w(TAG, "Invalid IntentFilter verification token "
1567                                + verificationId + " received");
1568                        break;
1569                    }
1570
1571                    final int userId = state.getUserId();
1572
1573                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1574                            "Processing IntentFilter verification with token:"
1575                            + verificationId + " and userId:" + userId);
1576
1577                    final IntentFilterVerificationResponse response =
1578                            (IntentFilterVerificationResponse) msg.obj;
1579
1580                    state.setVerifierResponse(response.callerUid, response.code);
1581
1582                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1583                            "IntentFilter verification with token:" + verificationId
1584                            + " and userId:" + userId
1585                            + " is settings verifier response with response code:"
1586                            + response.code);
1587
1588                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1589                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1590                                + response.getFailedDomainsString());
1591                    }
1592
1593                    if (state.isVerificationComplete()) {
1594                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1595                    } else {
1596                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1597                                "IntentFilter verification with token:" + verificationId
1598                                + " was not said to be complete");
1599                    }
1600
1601                    break;
1602                }
1603            }
1604        }
1605    }
1606
1607    private StorageEventListener mStorageListener = new StorageEventListener() {
1608        @Override
1609        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1610            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1611                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1612                    final String volumeUuid = vol.getFsUuid();
1613
1614                    // Clean up any users or apps that were removed or recreated
1615                    // while this volume was missing
1616                    reconcileUsers(volumeUuid);
1617                    reconcileApps(volumeUuid);
1618
1619                    // Clean up any install sessions that expired or were
1620                    // cancelled while this volume was missing
1621                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1622
1623                    loadPrivatePackages(vol);
1624
1625                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1626                    unloadPrivatePackages(vol);
1627                }
1628            }
1629
1630            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1631                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1632                    updateExternalMediaStatus(true, false);
1633                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1634                    updateExternalMediaStatus(false, false);
1635                }
1636            }
1637        }
1638
1639        @Override
1640        public void onVolumeForgotten(String fsUuid) {
1641            // Remove any apps installed on the forgotten volume
1642            synchronized (mPackages) {
1643                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1644                for (PackageSetting ps : packages) {
1645                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1646                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1647                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1648                }
1649
1650                mSettings.writeLPr();
1651            }
1652        }
1653    };
1654
1655    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1656        if (userId >= UserHandle.USER_OWNER) {
1657            grantRequestedRuntimePermissionsForUser(pkg, userId);
1658        } else if (userId == UserHandle.USER_ALL) {
1659            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1660                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1661            }
1662        }
1663
1664        // We could have touched GID membership, so flush out packages.list
1665        synchronized (mPackages) {
1666            mSettings.writePackageListLPr();
1667        }
1668    }
1669
1670    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1671        SettingBase sb = (SettingBase) pkg.mExtras;
1672        if (sb == null) {
1673            return;
1674        }
1675
1676        PermissionsState permissionsState = sb.getPermissionsState();
1677
1678        for (String permission : pkg.requestedPermissions) {
1679            BasePermission bp = mSettings.mPermissions.get(permission);
1680            if (bp != null && bp.isRuntime()) {
1681                permissionsState.grantRuntimePermission(bp, userId);
1682            }
1683        }
1684    }
1685
1686    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1687        Bundle extras = null;
1688        switch (res.returnCode) {
1689            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1690                extras = new Bundle();
1691                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1692                        res.origPermission);
1693                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1694                        res.origPackage);
1695                break;
1696            }
1697            case PackageManager.INSTALL_SUCCEEDED: {
1698                extras = new Bundle();
1699                extras.putBoolean(Intent.EXTRA_REPLACING,
1700                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1701                break;
1702            }
1703        }
1704        return extras;
1705    }
1706
1707    void scheduleWriteSettingsLocked() {
1708        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1709            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1710        }
1711    }
1712
1713    void scheduleWritePackageRestrictionsLocked(int userId) {
1714        if (!sUserManager.exists(userId)) return;
1715        mDirtyUsers.add(userId);
1716        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1717            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1718        }
1719    }
1720
1721    public static PackageManagerService main(Context context, Installer installer,
1722            boolean factoryTest, boolean onlyCore) {
1723        PackageManagerService m = new PackageManagerService(context, installer,
1724                factoryTest, onlyCore);
1725        ServiceManager.addService("package", m);
1726        return m;
1727    }
1728
1729    static String[] splitString(String str, char sep) {
1730        int count = 1;
1731        int i = 0;
1732        while ((i=str.indexOf(sep, i)) >= 0) {
1733            count++;
1734            i++;
1735        }
1736
1737        String[] res = new String[count];
1738        i=0;
1739        count = 0;
1740        int lastI=0;
1741        while ((i=str.indexOf(sep, i)) >= 0) {
1742            res[count] = str.substring(lastI, i);
1743            count++;
1744            i++;
1745            lastI = i;
1746        }
1747        res[count] = str.substring(lastI, str.length());
1748        return res;
1749    }
1750
1751    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1752        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1753                Context.DISPLAY_SERVICE);
1754        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1755    }
1756
1757    public PackageManagerService(Context context, Installer installer,
1758            boolean factoryTest, boolean onlyCore) {
1759        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1760                SystemClock.uptimeMillis());
1761
1762        if (mSdkVersion <= 0) {
1763            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1764        }
1765
1766        mContext = context;
1767        mFactoryTest = factoryTest;
1768        mOnlyCore = onlyCore;
1769        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1770        mMetrics = new DisplayMetrics();
1771        mSettings = new Settings(mPackages);
1772        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1773                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1774        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1775                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1776        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1777                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1778        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1779                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1780        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1781                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1782        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1783                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1784
1785        // TODO: add a property to control this?
1786        long dexOptLRUThresholdInMinutes;
1787        if (mLazyDexOpt) {
1788            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1789        } else {
1790            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1791        }
1792        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1793
1794        String separateProcesses = SystemProperties.get("debug.separate_processes");
1795        if (separateProcesses != null && separateProcesses.length() > 0) {
1796            if ("*".equals(separateProcesses)) {
1797                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1798                mSeparateProcesses = null;
1799                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1800            } else {
1801                mDefParseFlags = 0;
1802                mSeparateProcesses = separateProcesses.split(",");
1803                Slog.w(TAG, "Running with debug.separate_processes: "
1804                        + separateProcesses);
1805            }
1806        } else {
1807            mDefParseFlags = 0;
1808            mSeparateProcesses = null;
1809        }
1810
1811        mInstaller = installer;
1812        mPackageDexOptimizer = new PackageDexOptimizer(this);
1813        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1814
1815        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1816                FgThread.get().getLooper());
1817
1818        getDefaultDisplayMetrics(context, mMetrics);
1819
1820        SystemConfig systemConfig = SystemConfig.getInstance();
1821        mGlobalGids = systemConfig.getGlobalGids();
1822        mSystemPermissions = systemConfig.getSystemPermissions();
1823        mAvailableFeatures = systemConfig.getAvailableFeatures();
1824
1825        synchronized (mInstallLock) {
1826        // writer
1827        synchronized (mPackages) {
1828            mHandlerThread = new ServiceThread(TAG,
1829                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1830            mHandlerThread.start();
1831            mHandler = new PackageHandler(mHandlerThread.getLooper());
1832            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1833
1834            File dataDir = Environment.getDataDirectory();
1835            mAppDataDir = new File(dataDir, "data");
1836            mAppInstallDir = new File(dataDir, "app");
1837            mAppLib32InstallDir = new File(dataDir, "app-lib");
1838            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1839            mUserAppDataDir = new File(dataDir, "user");
1840            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1841
1842            sUserManager = new UserManagerService(context, this,
1843                    mInstallLock, mPackages);
1844
1845            // Propagate permission configuration in to package manager.
1846            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1847                    = systemConfig.getPermissions();
1848            for (int i=0; i<permConfig.size(); i++) {
1849                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1850                BasePermission bp = mSettings.mPermissions.get(perm.name);
1851                if (bp == null) {
1852                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1853                    mSettings.mPermissions.put(perm.name, bp);
1854                }
1855                if (perm.gids != null) {
1856                    bp.setGids(perm.gids, perm.perUser);
1857                }
1858            }
1859
1860            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1861            for (int i=0; i<libConfig.size(); i++) {
1862                mSharedLibraries.put(libConfig.keyAt(i),
1863                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1864            }
1865
1866            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1867
1868            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1869                    mSdkVersion, mOnlyCore);
1870
1871            String customResolverActivity = Resources.getSystem().getString(
1872                    R.string.config_customResolverActivity);
1873            if (TextUtils.isEmpty(customResolverActivity)) {
1874                customResolverActivity = null;
1875            } else {
1876                mCustomResolverComponentName = ComponentName.unflattenFromString(
1877                        customResolverActivity);
1878            }
1879
1880            long startTime = SystemClock.uptimeMillis();
1881
1882            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1883                    startTime);
1884
1885            // Set flag to monitor and not change apk file paths when
1886            // scanning install directories.
1887            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1888
1889            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1890
1891            /**
1892             * Add everything in the in the boot class path to the
1893             * list of process files because dexopt will have been run
1894             * if necessary during zygote startup.
1895             */
1896            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1897            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1898
1899            if (bootClassPath != null) {
1900                String[] bootClassPathElements = splitString(bootClassPath, ':');
1901                for (String element : bootClassPathElements) {
1902                    alreadyDexOpted.add(element);
1903                }
1904            } else {
1905                Slog.w(TAG, "No BOOTCLASSPATH found!");
1906            }
1907
1908            if (systemServerClassPath != null) {
1909                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1910                for (String element : systemServerClassPathElements) {
1911                    alreadyDexOpted.add(element);
1912                }
1913            } else {
1914                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1915            }
1916
1917            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1918            final String[] dexCodeInstructionSets =
1919                    getDexCodeInstructionSets(
1920                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1921
1922            /**
1923             * Ensure all external libraries have had dexopt run on them.
1924             */
1925            if (mSharedLibraries.size() > 0) {
1926                // NOTE: For now, we're compiling these system "shared libraries"
1927                // (and framework jars) into all available architectures. It's possible
1928                // to compile them only when we come across an app that uses them (there's
1929                // already logic for that in scanPackageLI) but that adds some complexity.
1930                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1931                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1932                        final String lib = libEntry.path;
1933                        if (lib == null) {
1934                            continue;
1935                        }
1936
1937                        try {
1938                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1939                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1940                                alreadyDexOpted.add(lib);
1941                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1942                            }
1943                        } catch (FileNotFoundException e) {
1944                            Slog.w(TAG, "Library not found: " + lib);
1945                        } catch (IOException e) {
1946                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1947                                    + e.getMessage());
1948                        }
1949                    }
1950                }
1951            }
1952
1953            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1954
1955            // Gross hack for now: we know this file doesn't contain any
1956            // code, so don't dexopt it to avoid the resulting log spew.
1957            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1958
1959            // Gross hack for now: we know this file is only part of
1960            // the boot class path for art, so don't dexopt it to
1961            // avoid the resulting log spew.
1962            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1963
1964            /**
1965             * There are a number of commands implemented in Java, which
1966             * we currently need to do the dexopt on so that they can be
1967             * run from a non-root shell.
1968             */
1969            String[] frameworkFiles = frameworkDir.list();
1970            if (frameworkFiles != null) {
1971                // TODO: We could compile these only for the most preferred ABI. We should
1972                // first double check that the dex files for these commands are not referenced
1973                // by other system apps.
1974                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1975                    for (int i=0; i<frameworkFiles.length; i++) {
1976                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1977                        String path = libPath.getPath();
1978                        // Skip the file if we already did it.
1979                        if (alreadyDexOpted.contains(path)) {
1980                            continue;
1981                        }
1982                        // Skip the file if it is not a type we want to dexopt.
1983                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1984                            continue;
1985                        }
1986                        try {
1987                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1988                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1989                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1990                            }
1991                        } catch (FileNotFoundException e) {
1992                            Slog.w(TAG, "Jar not found: " + path);
1993                        } catch (IOException e) {
1994                            Slog.w(TAG, "Exception reading jar: " + path, e);
1995                        }
1996                    }
1997                }
1998            }
1999
2000            // Collect vendor overlay packages.
2001            // (Do this before scanning any apps.)
2002            // For security and version matching reason, only consider
2003            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2004            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2005            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2006                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2007
2008            // Find base frameworks (resource packages without code).
2009            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2010                    | PackageParser.PARSE_IS_SYSTEM_DIR
2011                    | PackageParser.PARSE_IS_PRIVILEGED,
2012                    scanFlags | SCAN_NO_DEX, 0);
2013
2014            // Collected privileged system packages.
2015            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2016            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2017                    | PackageParser.PARSE_IS_SYSTEM_DIR
2018                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2019
2020            // Collect ordinary system packages.
2021            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2022            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2023                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2024
2025            // Collect all vendor packages.
2026            File vendorAppDir = new File("/vendor/app");
2027            try {
2028                vendorAppDir = vendorAppDir.getCanonicalFile();
2029            } catch (IOException e) {
2030                // failed to look up canonical path, continue with original one
2031            }
2032            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2033                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2034
2035            // Collect all OEM packages.
2036            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2037            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2038                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2039
2040            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2041            mInstaller.moveFiles();
2042
2043            // Prune any system packages that no longer exist.
2044            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2045            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2046            if (!mOnlyCore) {
2047                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2048                while (psit.hasNext()) {
2049                    PackageSetting ps = psit.next();
2050
2051                    /*
2052                     * If this is not a system app, it can't be a
2053                     * disable system app.
2054                     */
2055                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2056                        continue;
2057                    }
2058
2059                    /*
2060                     * If the package is scanned, it's not erased.
2061                     */
2062                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2063                    if (scannedPkg != null) {
2064                        /*
2065                         * If the system app is both scanned and in the
2066                         * disabled packages list, then it must have been
2067                         * added via OTA. Remove it from the currently
2068                         * scanned package so the previously user-installed
2069                         * application can be scanned.
2070                         */
2071                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2072                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2073                                    + ps.name + "; removing system app.  Last known codePath="
2074                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2075                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2076                                    + scannedPkg.mVersionCode);
2077                            removePackageLI(ps, true);
2078                            expectingBetter.put(ps.name, ps.codePath);
2079                        }
2080
2081                        continue;
2082                    }
2083
2084                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2085                        psit.remove();
2086                        logCriticalInfo(Log.WARN, "System package " + ps.name
2087                                + " no longer exists; wiping its data");
2088                        removeDataDirsLI(null, ps.name);
2089                    } else {
2090                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2091                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2092                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2093                        }
2094                    }
2095                }
2096            }
2097
2098            //look for any incomplete package installations
2099            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2100            //clean up list
2101            for(int i = 0; i < deletePkgsList.size(); i++) {
2102                //clean up here
2103                cleanupInstallFailedPackage(deletePkgsList.get(i));
2104            }
2105            //delete tmp files
2106            deleteTempPackageFiles();
2107
2108            // Remove any shared userIDs that have no associated packages
2109            mSettings.pruneSharedUsersLPw();
2110
2111            if (!mOnlyCore) {
2112                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2113                        SystemClock.uptimeMillis());
2114                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2115
2116                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2117                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2118
2119                /**
2120                 * Remove disable package settings for any updated system
2121                 * apps that were removed via an OTA. If they're not a
2122                 * previously-updated app, remove them completely.
2123                 * Otherwise, just revoke their system-level permissions.
2124                 */
2125                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2126                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2127                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2128
2129                    String msg;
2130                    if (deletedPkg == null) {
2131                        msg = "Updated system package " + deletedAppName
2132                                + " no longer exists; wiping its data";
2133                        removeDataDirsLI(null, deletedAppName);
2134                    } else {
2135                        msg = "Updated system app + " + deletedAppName
2136                                + " no longer present; removing system privileges for "
2137                                + deletedAppName;
2138
2139                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2140
2141                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2142                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2143                    }
2144                    logCriticalInfo(Log.WARN, msg);
2145                }
2146
2147                /**
2148                 * Make sure all system apps that we expected to appear on
2149                 * the userdata partition actually showed up. If they never
2150                 * appeared, crawl back and revive the system version.
2151                 */
2152                for (int i = 0; i < expectingBetter.size(); i++) {
2153                    final String packageName = expectingBetter.keyAt(i);
2154                    if (!mPackages.containsKey(packageName)) {
2155                        final File scanFile = expectingBetter.valueAt(i);
2156
2157                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2158                                + " but never showed up; reverting to system");
2159
2160                        final int reparseFlags;
2161                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2162                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2163                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2164                                    | PackageParser.PARSE_IS_PRIVILEGED;
2165                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2166                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2167                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2168                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2169                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2170                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2171                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2172                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2173                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2174                        } else {
2175                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2176                            continue;
2177                        }
2178
2179                        mSettings.enableSystemPackageLPw(packageName);
2180
2181                        try {
2182                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2183                        } catch (PackageManagerException e) {
2184                            Slog.e(TAG, "Failed to parse original system package: "
2185                                    + e.getMessage());
2186                        }
2187                    }
2188                }
2189            }
2190
2191            // Now that we know all of the shared libraries, update all clients to have
2192            // the correct library paths.
2193            updateAllSharedLibrariesLPw();
2194
2195            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2196                // NOTE: We ignore potential failures here during a system scan (like
2197                // the rest of the commands above) because there's precious little we
2198                // can do about it. A settings error is reported, though.
2199                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2200                        false /* force dexopt */, false /* defer dexopt */);
2201            }
2202
2203            // Now that we know all the packages we are keeping,
2204            // read and update their last usage times.
2205            mPackageUsage.readLP();
2206
2207            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2208                    SystemClock.uptimeMillis());
2209            Slog.i(TAG, "Time to scan packages: "
2210                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2211                    + " seconds");
2212
2213            // If the platform SDK has changed since the last time we booted,
2214            // we need to re-grant app permission to catch any new ones that
2215            // appear.  This is really a hack, and means that apps can in some
2216            // cases get permissions that the user didn't initially explicitly
2217            // allow...  it would be nice to have some better way to handle
2218            // this situation.
2219            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2220                    != mSdkVersion;
2221            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2222                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2223                    + "; regranting permissions for internal storage");
2224            mSettings.mInternalSdkPlatform = mSdkVersion;
2225
2226            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2227                    | (regrantPermissions
2228                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2229                            : 0));
2230
2231            // If this is the first boot, and it is a normal boot, then
2232            // we need to initialize the default preferred apps.
2233            if (!mRestoredSettings && !onlyCore) {
2234                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2235                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2236            }
2237
2238            // If this is first boot after an OTA, and a normal boot, then
2239            // we need to clear code cache directories.
2240            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2241            if (mIsUpgrade && !onlyCore) {
2242                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2243                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2244                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2245                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2246                }
2247                mSettings.mFingerprint = Build.FINGERPRINT;
2248            }
2249
2250            primeDomainVerificationsLPw();
2251            checkDefaultBrowser();
2252
2253            // All the changes are done during package scanning.
2254            mSettings.updateInternalDatabaseVersion();
2255
2256            // can downgrade to reader
2257            mSettings.writeLPr();
2258
2259            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2260                    SystemClock.uptimeMillis());
2261
2262            mRequiredVerifierPackage = getRequiredVerifierLPr();
2263
2264            mInstallerService = new PackageInstallerService(context, this);
2265
2266            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2267            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2268                    mIntentFilterVerifierComponent);
2269
2270        } // synchronized (mPackages)
2271        } // synchronized (mInstallLock)
2272
2273        // Now after opening every single application zip, make sure they
2274        // are all flushed.  Not really needed, but keeps things nice and
2275        // tidy.
2276        Runtime.getRuntime().gc();
2277
2278        // Expose private service for system components to use.
2279        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2280    }
2281
2282    @Override
2283    public boolean isFirstBoot() {
2284        return !mRestoredSettings;
2285    }
2286
2287    @Override
2288    public boolean isOnlyCoreApps() {
2289        return mOnlyCore;
2290    }
2291
2292    @Override
2293    public boolean isUpgrade() {
2294        return mIsUpgrade;
2295    }
2296
2297    private String getRequiredVerifierLPr() {
2298        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2299        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2300                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2301
2302        String requiredVerifier = null;
2303
2304        final int N = receivers.size();
2305        for (int i = 0; i < N; i++) {
2306            final ResolveInfo info = receivers.get(i);
2307
2308            if (info.activityInfo == null) {
2309                continue;
2310            }
2311
2312            final String packageName = info.activityInfo.packageName;
2313
2314            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2315                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2316                continue;
2317            }
2318
2319            if (requiredVerifier != null) {
2320                throw new RuntimeException("There can be only one required verifier");
2321            }
2322
2323            requiredVerifier = packageName;
2324        }
2325
2326        return requiredVerifier;
2327    }
2328
2329    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2330        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2331        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2332                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2333
2334        ComponentName verifierComponentName = null;
2335
2336        int priority = -1000;
2337        final int N = receivers.size();
2338        for (int i = 0; i < N; i++) {
2339            final ResolveInfo info = receivers.get(i);
2340
2341            if (info.activityInfo == null) {
2342                continue;
2343            }
2344
2345            final String packageName = info.activityInfo.packageName;
2346
2347            final PackageSetting ps = mSettings.mPackages.get(packageName);
2348            if (ps == null) {
2349                continue;
2350            }
2351
2352            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2353                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2354                continue;
2355            }
2356
2357            // Select the IntentFilterVerifier with the highest priority
2358            if (priority < info.priority) {
2359                priority = info.priority;
2360                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2361                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2362                        + verifierComponentName + " with priority: " + info.priority);
2363            }
2364        }
2365
2366        return verifierComponentName;
2367    }
2368
2369    private void primeDomainVerificationsLPw() {
2370        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2371        boolean updated = false;
2372        ArraySet<String> allHostsSet = new ArraySet<>();
2373        for (PackageParser.Package pkg : mPackages.values()) {
2374            final String packageName = pkg.packageName;
2375            if (!hasDomainURLs(pkg)) {
2376                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2377                            "package with no domain URLs: " + packageName);
2378                continue;
2379            }
2380            if (!pkg.isSystemApp()) {
2381                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2382                        "No priming domain verifications for a non system package : " +
2383                                packageName);
2384                continue;
2385            }
2386            for (PackageParser.Activity a : pkg.activities) {
2387                for (ActivityIntentInfo filter : a.intents) {
2388                    if (hasValidDomains(filter)) {
2389                        allHostsSet.addAll(filter.getHostsList());
2390                    }
2391                }
2392            }
2393            if (allHostsSet.size() == 0) {
2394                allHostsSet.add("*");
2395            }
2396            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2397            IntentFilterVerificationInfo ivi =
2398                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2399            if (ivi != null) {
2400                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2401                        "Priming domain verifications for package: " + packageName +
2402                        " with hosts:" + ivi.getDomainsString());
2403                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2404                updated = true;
2405            }
2406            else {
2407                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2408                        "No priming domain verifications for package: " + packageName);
2409            }
2410            allHostsSet.clear();
2411        }
2412        if (updated) {
2413            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2414                    "Will need to write primed domain verifications");
2415        }
2416        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2417    }
2418
2419    private void applyFactoryDefaultBrowserLPw(int userId) {
2420        // The default browser app's package name is stored in a string resource,
2421        // with a product-specific overlay used for vendor customization.
2422        String browserPkg = mContext.getResources().getString(
2423                com.android.internal.R.string.default_browser);
2424        if (browserPkg != null) {
2425            // non-empty string => required to be a known package
2426            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2427            if (ps == null) {
2428                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2429                browserPkg = null;
2430            } else {
2431                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2432            }
2433        }
2434
2435        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2436        // default.  If there's more than one, just leave everything alone.
2437        if (browserPkg == null) {
2438            calculateDefaultBrowserLPw(userId);
2439        }
2440    }
2441
2442    private void calculateDefaultBrowserLPw(int userId) {
2443        List<String> allBrowsers = resolveAllBrowserApps(userId);
2444        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2445        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2446    }
2447
2448    private List<String> resolveAllBrowserApps(int userId) {
2449        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2450        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2451                PackageManager.MATCH_ALL, userId);
2452
2453        final int count = list.size();
2454        List<String> result = new ArrayList<String>(count);
2455        for (int i=0; i<count; i++) {
2456            ResolveInfo info = list.get(i);
2457            if (info.activityInfo == null
2458                    || !info.handleAllWebDataURI
2459                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2460                    || result.contains(info.activityInfo.packageName)) {
2461                continue;
2462            }
2463            result.add(info.activityInfo.packageName);
2464        }
2465
2466        return result;
2467    }
2468
2469    private boolean packageIsBrowser(String packageName, int userId) {
2470        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2471                PackageManager.MATCH_ALL, userId);
2472        final int N = list.size();
2473        for (int i = 0; i < N; i++) {
2474            ResolveInfo info = list.get(i);
2475            if (packageName.equals(info.activityInfo.packageName)) {
2476                return true;
2477            }
2478        }
2479        return false;
2480    }
2481
2482    private void checkDefaultBrowser() {
2483        final int myUserId = UserHandle.myUserId();
2484        final String packageName = getDefaultBrowserPackageName(myUserId);
2485        if (packageName != null) {
2486            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2487            if (info == null) {
2488                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2489                synchronized (mPackages) {
2490                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2491                }
2492            }
2493        }
2494    }
2495
2496    @Override
2497    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2498            throws RemoteException {
2499        try {
2500            return super.onTransact(code, data, reply, flags);
2501        } catch (RuntimeException e) {
2502            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2503                Slog.wtf(TAG, "Package Manager Crash", e);
2504            }
2505            throw e;
2506        }
2507    }
2508
2509    void cleanupInstallFailedPackage(PackageSetting ps) {
2510        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2511
2512        removeDataDirsLI(ps.volumeUuid, ps.name);
2513        if (ps.codePath != null) {
2514            if (ps.codePath.isDirectory()) {
2515                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2516            } else {
2517                ps.codePath.delete();
2518            }
2519        }
2520        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2521            if (ps.resourcePath.isDirectory()) {
2522                FileUtils.deleteContents(ps.resourcePath);
2523            }
2524            ps.resourcePath.delete();
2525        }
2526        mSettings.removePackageLPw(ps.name);
2527    }
2528
2529    static int[] appendInts(int[] cur, int[] add) {
2530        if (add == null) return cur;
2531        if (cur == null) return add;
2532        final int N = add.length;
2533        for (int i=0; i<N; i++) {
2534            cur = appendInt(cur, add[i]);
2535        }
2536        return cur;
2537    }
2538
2539    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2540        if (!sUserManager.exists(userId)) return null;
2541        final PackageSetting ps = (PackageSetting) p.mExtras;
2542        if (ps == null) {
2543            return null;
2544        }
2545
2546        final PermissionsState permissionsState = ps.getPermissionsState();
2547
2548        final int[] gids = permissionsState.computeGids(userId);
2549        final Set<String> permissions = permissionsState.getPermissions(userId);
2550        final PackageUserState state = ps.readUserState(userId);
2551
2552        return PackageParser.generatePackageInfo(p, gids, flags,
2553                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2554    }
2555
2556    @Override
2557    public boolean isPackageFrozen(String packageName) {
2558        synchronized (mPackages) {
2559            final PackageSetting ps = mSettings.mPackages.get(packageName);
2560            if (ps != null) {
2561                return ps.frozen;
2562            }
2563        }
2564        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2565        return true;
2566    }
2567
2568    @Override
2569    public boolean isPackageAvailable(String packageName, int userId) {
2570        if (!sUserManager.exists(userId)) return false;
2571        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2572        synchronized (mPackages) {
2573            PackageParser.Package p = mPackages.get(packageName);
2574            if (p != null) {
2575                final PackageSetting ps = (PackageSetting) p.mExtras;
2576                if (ps != null) {
2577                    final PackageUserState state = ps.readUserState(userId);
2578                    if (state != null) {
2579                        return PackageParser.isAvailable(state);
2580                    }
2581                }
2582            }
2583        }
2584        return false;
2585    }
2586
2587    @Override
2588    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2589        if (!sUserManager.exists(userId)) return null;
2590        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2591        // reader
2592        synchronized (mPackages) {
2593            PackageParser.Package p = mPackages.get(packageName);
2594            if (DEBUG_PACKAGE_INFO)
2595                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2596            if (p != null) {
2597                return generatePackageInfo(p, flags, userId);
2598            }
2599            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2600                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2601            }
2602        }
2603        return null;
2604    }
2605
2606    @Override
2607    public String[] currentToCanonicalPackageNames(String[] names) {
2608        String[] out = new String[names.length];
2609        // reader
2610        synchronized (mPackages) {
2611            for (int i=names.length-1; i>=0; i--) {
2612                PackageSetting ps = mSettings.mPackages.get(names[i]);
2613                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2614            }
2615        }
2616        return out;
2617    }
2618
2619    @Override
2620    public String[] canonicalToCurrentPackageNames(String[] names) {
2621        String[] out = new String[names.length];
2622        // reader
2623        synchronized (mPackages) {
2624            for (int i=names.length-1; i>=0; i--) {
2625                String cur = mSettings.mRenamedPackages.get(names[i]);
2626                out[i] = cur != null ? cur : names[i];
2627            }
2628        }
2629        return out;
2630    }
2631
2632    @Override
2633    public int getPackageUid(String packageName, int userId) {
2634        if (!sUserManager.exists(userId)) return -1;
2635        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2636
2637        // reader
2638        synchronized (mPackages) {
2639            PackageParser.Package p = mPackages.get(packageName);
2640            if(p != null) {
2641                return UserHandle.getUid(userId, p.applicationInfo.uid);
2642            }
2643            PackageSetting ps = mSettings.mPackages.get(packageName);
2644            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2645                return -1;
2646            }
2647            p = ps.pkg;
2648            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2649        }
2650    }
2651
2652    @Override
2653    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2654        if (!sUserManager.exists(userId)) {
2655            return null;
2656        }
2657
2658        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2659                "getPackageGids");
2660
2661        // reader
2662        synchronized (mPackages) {
2663            PackageParser.Package p = mPackages.get(packageName);
2664            if (DEBUG_PACKAGE_INFO) {
2665                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2666            }
2667            if (p != null) {
2668                PackageSetting ps = (PackageSetting) p.mExtras;
2669                return ps.getPermissionsState().computeGids(userId);
2670            }
2671        }
2672
2673        return null;
2674    }
2675
2676    @Override
2677    public int getMountExternalMode(int uid) {
2678        if (Process.isIsolated(uid)) {
2679            return Zygote.MOUNT_EXTERNAL_NONE;
2680        } else {
2681            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2682                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2683            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2684                return Zygote.MOUNT_EXTERNAL_WRITE;
2685            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2686                return Zygote.MOUNT_EXTERNAL_READ;
2687            } else {
2688                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2689            }
2690        }
2691    }
2692
2693    static PermissionInfo generatePermissionInfo(
2694            BasePermission bp, int flags) {
2695        if (bp.perm != null) {
2696            return PackageParser.generatePermissionInfo(bp.perm, flags);
2697        }
2698        PermissionInfo pi = new PermissionInfo();
2699        pi.name = bp.name;
2700        pi.packageName = bp.sourcePackage;
2701        pi.nonLocalizedLabel = bp.name;
2702        pi.protectionLevel = bp.protectionLevel;
2703        return pi;
2704    }
2705
2706    @Override
2707    public PermissionInfo getPermissionInfo(String name, int flags) {
2708        // reader
2709        synchronized (mPackages) {
2710            final BasePermission p = mSettings.mPermissions.get(name);
2711            if (p != null) {
2712                return generatePermissionInfo(p, flags);
2713            }
2714            return null;
2715        }
2716    }
2717
2718    @Override
2719    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2720        // reader
2721        synchronized (mPackages) {
2722            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2723            for (BasePermission p : mSettings.mPermissions.values()) {
2724                if (group == null) {
2725                    if (p.perm == null || p.perm.info.group == null) {
2726                        out.add(generatePermissionInfo(p, flags));
2727                    }
2728                } else {
2729                    if (p.perm != null && group.equals(p.perm.info.group)) {
2730                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2731                    }
2732                }
2733            }
2734
2735            if (out.size() > 0) {
2736                return out;
2737            }
2738            return mPermissionGroups.containsKey(group) ? out : null;
2739        }
2740    }
2741
2742    @Override
2743    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2744        // reader
2745        synchronized (mPackages) {
2746            return PackageParser.generatePermissionGroupInfo(
2747                    mPermissionGroups.get(name), flags);
2748        }
2749    }
2750
2751    @Override
2752    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2753        // reader
2754        synchronized (mPackages) {
2755            final int N = mPermissionGroups.size();
2756            ArrayList<PermissionGroupInfo> out
2757                    = new ArrayList<PermissionGroupInfo>(N);
2758            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2759                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2760            }
2761            return out;
2762        }
2763    }
2764
2765    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2766            int userId) {
2767        if (!sUserManager.exists(userId)) return null;
2768        PackageSetting ps = mSettings.mPackages.get(packageName);
2769        if (ps != null) {
2770            if (ps.pkg == null) {
2771                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2772                        flags, userId);
2773                if (pInfo != null) {
2774                    return pInfo.applicationInfo;
2775                }
2776                return null;
2777            }
2778            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2779                    ps.readUserState(userId), userId);
2780        }
2781        return null;
2782    }
2783
2784    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2785            int userId) {
2786        if (!sUserManager.exists(userId)) return null;
2787        PackageSetting ps = mSettings.mPackages.get(packageName);
2788        if (ps != null) {
2789            PackageParser.Package pkg = ps.pkg;
2790            if (pkg == null) {
2791                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2792                    return null;
2793                }
2794                // Only data remains, so we aren't worried about code paths
2795                pkg = new PackageParser.Package(packageName);
2796                pkg.applicationInfo.packageName = packageName;
2797                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2798                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2799                pkg.applicationInfo.dataDir = Environment
2800                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2801                        .getAbsolutePath();
2802                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2803                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2804            }
2805            return generatePackageInfo(pkg, flags, userId);
2806        }
2807        return null;
2808    }
2809
2810    @Override
2811    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2812        if (!sUserManager.exists(userId)) return null;
2813        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2814        // writer
2815        synchronized (mPackages) {
2816            PackageParser.Package p = mPackages.get(packageName);
2817            if (DEBUG_PACKAGE_INFO) Log.v(
2818                    TAG, "getApplicationInfo " + packageName
2819                    + ": " + p);
2820            if (p != null) {
2821                PackageSetting ps = mSettings.mPackages.get(packageName);
2822                if (ps == null) return null;
2823                // Note: isEnabledLP() does not apply here - always return info
2824                return PackageParser.generateApplicationInfo(
2825                        p, flags, ps.readUserState(userId), userId);
2826            }
2827            if ("android".equals(packageName)||"system".equals(packageName)) {
2828                return mAndroidApplication;
2829            }
2830            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2831                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2832            }
2833        }
2834        return null;
2835    }
2836
2837    @Override
2838    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2839            final IPackageDataObserver observer) {
2840        mContext.enforceCallingOrSelfPermission(
2841                android.Manifest.permission.CLEAR_APP_CACHE, null);
2842        // Queue up an async operation since clearing cache may take a little while.
2843        mHandler.post(new Runnable() {
2844            public void run() {
2845                mHandler.removeCallbacks(this);
2846                int retCode = -1;
2847                synchronized (mInstallLock) {
2848                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2849                    if (retCode < 0) {
2850                        Slog.w(TAG, "Couldn't clear application caches");
2851                    }
2852                }
2853                if (observer != null) {
2854                    try {
2855                        observer.onRemoveCompleted(null, (retCode >= 0));
2856                    } catch (RemoteException e) {
2857                        Slog.w(TAG, "RemoveException when invoking call back");
2858                    }
2859                }
2860            }
2861        });
2862    }
2863
2864    @Override
2865    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2866            final IntentSender pi) {
2867        mContext.enforceCallingOrSelfPermission(
2868                android.Manifest.permission.CLEAR_APP_CACHE, null);
2869        // Queue up an async operation since clearing cache may take a little while.
2870        mHandler.post(new Runnable() {
2871            public void run() {
2872                mHandler.removeCallbacks(this);
2873                int retCode = -1;
2874                synchronized (mInstallLock) {
2875                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2876                    if (retCode < 0) {
2877                        Slog.w(TAG, "Couldn't clear application caches");
2878                    }
2879                }
2880                if(pi != null) {
2881                    try {
2882                        // Callback via pending intent
2883                        int code = (retCode >= 0) ? 1 : 0;
2884                        pi.sendIntent(null, code, null,
2885                                null, null);
2886                    } catch (SendIntentException e1) {
2887                        Slog.i(TAG, "Failed to send pending intent");
2888                    }
2889                }
2890            }
2891        });
2892    }
2893
2894    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2895        synchronized (mInstallLock) {
2896            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2897                throw new IOException("Failed to free enough space");
2898            }
2899        }
2900    }
2901
2902    @Override
2903    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2904        if (!sUserManager.exists(userId)) return null;
2905        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2906        synchronized (mPackages) {
2907            PackageParser.Activity a = mActivities.mActivities.get(component);
2908
2909            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2910            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2911                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2912                if (ps == null) return null;
2913                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2914                        userId);
2915            }
2916            if (mResolveComponentName.equals(component)) {
2917                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2918                        new PackageUserState(), userId);
2919            }
2920        }
2921        return null;
2922    }
2923
2924    @Override
2925    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2926            String resolvedType) {
2927        synchronized (mPackages) {
2928            PackageParser.Activity a = mActivities.mActivities.get(component);
2929            if (a == null) {
2930                return false;
2931            }
2932            for (int i=0; i<a.intents.size(); i++) {
2933                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2934                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2935                    return true;
2936                }
2937            }
2938            return false;
2939        }
2940    }
2941
2942    @Override
2943    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2944        if (!sUserManager.exists(userId)) return null;
2945        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2946        synchronized (mPackages) {
2947            PackageParser.Activity a = mReceivers.mActivities.get(component);
2948            if (DEBUG_PACKAGE_INFO) Log.v(
2949                TAG, "getReceiverInfo " + component + ": " + a);
2950            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2951                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2952                if (ps == null) return null;
2953                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2954                        userId);
2955            }
2956        }
2957        return null;
2958    }
2959
2960    @Override
2961    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2962        if (!sUserManager.exists(userId)) return null;
2963        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2964        synchronized (mPackages) {
2965            PackageParser.Service s = mServices.mServices.get(component);
2966            if (DEBUG_PACKAGE_INFO) Log.v(
2967                TAG, "getServiceInfo " + component + ": " + s);
2968            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2969                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2970                if (ps == null) return null;
2971                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2972                        userId);
2973            }
2974        }
2975        return null;
2976    }
2977
2978    @Override
2979    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2980        if (!sUserManager.exists(userId)) return null;
2981        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2982        synchronized (mPackages) {
2983            PackageParser.Provider p = mProviders.mProviders.get(component);
2984            if (DEBUG_PACKAGE_INFO) Log.v(
2985                TAG, "getProviderInfo " + component + ": " + p);
2986            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2987                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2988                if (ps == null) return null;
2989                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2990                        userId);
2991            }
2992        }
2993        return null;
2994    }
2995
2996    @Override
2997    public String[] getSystemSharedLibraryNames() {
2998        Set<String> libSet;
2999        synchronized (mPackages) {
3000            libSet = mSharedLibraries.keySet();
3001            int size = libSet.size();
3002            if (size > 0) {
3003                String[] libs = new String[size];
3004                libSet.toArray(libs);
3005                return libs;
3006            }
3007        }
3008        return null;
3009    }
3010
3011    /**
3012     * @hide
3013     */
3014    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3015        synchronized (mPackages) {
3016            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3017            if (lib != null && lib.apk != null) {
3018                return mPackages.get(lib.apk);
3019            }
3020        }
3021        return null;
3022    }
3023
3024    @Override
3025    public FeatureInfo[] getSystemAvailableFeatures() {
3026        Collection<FeatureInfo> featSet;
3027        synchronized (mPackages) {
3028            featSet = mAvailableFeatures.values();
3029            int size = featSet.size();
3030            if (size > 0) {
3031                FeatureInfo[] features = new FeatureInfo[size+1];
3032                featSet.toArray(features);
3033                FeatureInfo fi = new FeatureInfo();
3034                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3035                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3036                features[size] = fi;
3037                return features;
3038            }
3039        }
3040        return null;
3041    }
3042
3043    @Override
3044    public boolean hasSystemFeature(String name) {
3045        synchronized (mPackages) {
3046            return mAvailableFeatures.containsKey(name);
3047        }
3048    }
3049
3050    private void checkValidCaller(int uid, int userId) {
3051        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3052            return;
3053
3054        throw new SecurityException("Caller uid=" + uid
3055                + " is not privileged to communicate with user=" + userId);
3056    }
3057
3058    @Override
3059    public int checkPermission(String permName, String pkgName, int userId) {
3060        if (!sUserManager.exists(userId)) {
3061            return PackageManager.PERMISSION_DENIED;
3062        }
3063
3064        synchronized (mPackages) {
3065            final PackageParser.Package p = mPackages.get(pkgName);
3066            if (p != null && p.mExtras != null) {
3067                final PackageSetting ps = (PackageSetting) p.mExtras;
3068                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3069                    return PackageManager.PERMISSION_GRANTED;
3070                }
3071            }
3072        }
3073
3074        return PackageManager.PERMISSION_DENIED;
3075    }
3076
3077    @Override
3078    public int checkUidPermission(String permName, int uid) {
3079        final int userId = UserHandle.getUserId(uid);
3080
3081        if (!sUserManager.exists(userId)) {
3082            return PackageManager.PERMISSION_DENIED;
3083        }
3084
3085        synchronized (mPackages) {
3086            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3087            if (obj != null) {
3088                final SettingBase ps = (SettingBase) obj;
3089                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3090                    return PackageManager.PERMISSION_GRANTED;
3091                }
3092            } else {
3093                ArraySet<String> perms = mSystemPermissions.get(uid);
3094                if (perms != null && perms.contains(permName)) {
3095                    return PackageManager.PERMISSION_GRANTED;
3096                }
3097            }
3098        }
3099
3100        return PackageManager.PERMISSION_DENIED;
3101    }
3102
3103    /**
3104     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3105     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3106     * @param checkShell TODO(yamasani):
3107     * @param message the message to log on security exception
3108     */
3109    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3110            boolean checkShell, String message) {
3111        if (userId < 0) {
3112            throw new IllegalArgumentException("Invalid userId " + userId);
3113        }
3114        if (checkShell) {
3115            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3116        }
3117        if (userId == UserHandle.getUserId(callingUid)) return;
3118        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3119            if (requireFullPermission) {
3120                mContext.enforceCallingOrSelfPermission(
3121                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3122            } else {
3123                try {
3124                    mContext.enforceCallingOrSelfPermission(
3125                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3126                } catch (SecurityException se) {
3127                    mContext.enforceCallingOrSelfPermission(
3128                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3129                }
3130            }
3131        }
3132    }
3133
3134    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3135        if (callingUid == Process.SHELL_UID) {
3136            if (userHandle >= 0
3137                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3138                throw new SecurityException("Shell does not have permission to access user "
3139                        + userHandle);
3140            } else if (userHandle < 0) {
3141                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3142                        + Debug.getCallers(3));
3143            }
3144        }
3145    }
3146
3147    private BasePermission findPermissionTreeLP(String permName) {
3148        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3149            if (permName.startsWith(bp.name) &&
3150                    permName.length() > bp.name.length() &&
3151                    permName.charAt(bp.name.length()) == '.') {
3152                return bp;
3153            }
3154        }
3155        return null;
3156    }
3157
3158    private BasePermission checkPermissionTreeLP(String permName) {
3159        if (permName != null) {
3160            BasePermission bp = findPermissionTreeLP(permName);
3161            if (bp != null) {
3162                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3163                    return bp;
3164                }
3165                throw new SecurityException("Calling uid "
3166                        + Binder.getCallingUid()
3167                        + " is not allowed to add to permission tree "
3168                        + bp.name + " owned by uid " + bp.uid);
3169            }
3170        }
3171        throw new SecurityException("No permission tree found for " + permName);
3172    }
3173
3174    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3175        if (s1 == null) {
3176            return s2 == null;
3177        }
3178        if (s2 == null) {
3179            return false;
3180        }
3181        if (s1.getClass() != s2.getClass()) {
3182            return false;
3183        }
3184        return s1.equals(s2);
3185    }
3186
3187    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3188        if (pi1.icon != pi2.icon) return false;
3189        if (pi1.logo != pi2.logo) return false;
3190        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3191        if (!compareStrings(pi1.name, pi2.name)) return false;
3192        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3193        // We'll take care of setting this one.
3194        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3195        // These are not currently stored in settings.
3196        //if (!compareStrings(pi1.group, pi2.group)) return false;
3197        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3198        //if (pi1.labelRes != pi2.labelRes) return false;
3199        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3200        return true;
3201    }
3202
3203    int permissionInfoFootprint(PermissionInfo info) {
3204        int size = info.name.length();
3205        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3206        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3207        return size;
3208    }
3209
3210    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3211        int size = 0;
3212        for (BasePermission perm : mSettings.mPermissions.values()) {
3213            if (perm.uid == tree.uid) {
3214                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3215            }
3216        }
3217        return size;
3218    }
3219
3220    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3221        // We calculate the max size of permissions defined by this uid and throw
3222        // if that plus the size of 'info' would exceed our stated maximum.
3223        if (tree.uid != Process.SYSTEM_UID) {
3224            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3225            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3226                throw new SecurityException("Permission tree size cap exceeded");
3227            }
3228        }
3229    }
3230
3231    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3232        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3233            throw new SecurityException("Label must be specified in permission");
3234        }
3235        BasePermission tree = checkPermissionTreeLP(info.name);
3236        BasePermission bp = mSettings.mPermissions.get(info.name);
3237        boolean added = bp == null;
3238        boolean changed = true;
3239        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3240        if (added) {
3241            enforcePermissionCapLocked(info, tree);
3242            bp = new BasePermission(info.name, tree.sourcePackage,
3243                    BasePermission.TYPE_DYNAMIC);
3244        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3245            throw new SecurityException(
3246                    "Not allowed to modify non-dynamic permission "
3247                    + info.name);
3248        } else {
3249            if (bp.protectionLevel == fixedLevel
3250                    && bp.perm.owner.equals(tree.perm.owner)
3251                    && bp.uid == tree.uid
3252                    && comparePermissionInfos(bp.perm.info, info)) {
3253                changed = false;
3254            }
3255        }
3256        bp.protectionLevel = fixedLevel;
3257        info = new PermissionInfo(info);
3258        info.protectionLevel = fixedLevel;
3259        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3260        bp.perm.info.packageName = tree.perm.info.packageName;
3261        bp.uid = tree.uid;
3262        if (added) {
3263            mSettings.mPermissions.put(info.name, bp);
3264        }
3265        if (changed) {
3266            if (!async) {
3267                mSettings.writeLPr();
3268            } else {
3269                scheduleWriteSettingsLocked();
3270            }
3271        }
3272        return added;
3273    }
3274
3275    @Override
3276    public boolean addPermission(PermissionInfo info) {
3277        synchronized (mPackages) {
3278            return addPermissionLocked(info, false);
3279        }
3280    }
3281
3282    @Override
3283    public boolean addPermissionAsync(PermissionInfo info) {
3284        synchronized (mPackages) {
3285            return addPermissionLocked(info, true);
3286        }
3287    }
3288
3289    @Override
3290    public void removePermission(String name) {
3291        synchronized (mPackages) {
3292            checkPermissionTreeLP(name);
3293            BasePermission bp = mSettings.mPermissions.get(name);
3294            if (bp != null) {
3295                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3296                    throw new SecurityException(
3297                            "Not allowed to modify non-dynamic permission "
3298                            + name);
3299                }
3300                mSettings.mPermissions.remove(name);
3301                mSettings.writeLPr();
3302            }
3303        }
3304    }
3305
3306    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3307            BasePermission bp) {
3308        int index = pkg.requestedPermissions.indexOf(bp.name);
3309        if (index == -1) {
3310            throw new SecurityException("Package " + pkg.packageName
3311                    + " has not requested permission " + bp.name);
3312        }
3313        if (!bp.isRuntime()) {
3314            throw new SecurityException("Permission " + bp.name
3315                    + " is not a changeable permission type");
3316        }
3317    }
3318
3319    @Override
3320    public void grantRuntimePermission(String packageName, String name, final int userId) {
3321        if (!sUserManager.exists(userId)) {
3322            Log.e(TAG, "No such user:" + userId);
3323            return;
3324        }
3325
3326        mContext.enforceCallingOrSelfPermission(
3327                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3328                "grantRuntimePermission");
3329
3330        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3331                "grantRuntimePermission");
3332
3333        final int uid;
3334        final SettingBase sb;
3335
3336        synchronized (mPackages) {
3337            final PackageParser.Package pkg = mPackages.get(packageName);
3338            if (pkg == null) {
3339                throw new IllegalArgumentException("Unknown package: " + packageName);
3340            }
3341
3342            final BasePermission bp = mSettings.mPermissions.get(name);
3343            if (bp == null) {
3344                throw new IllegalArgumentException("Unknown permission: " + name);
3345            }
3346
3347            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3348
3349            uid = pkg.applicationInfo.uid;
3350            sb = (SettingBase) pkg.mExtras;
3351            if (sb == null) {
3352                throw new IllegalArgumentException("Unknown package: " + packageName);
3353            }
3354
3355            final PermissionsState permissionsState = sb.getPermissionsState();
3356
3357            final int flags = permissionsState.getPermissionFlags(name, userId);
3358            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3359                throw new SecurityException("Cannot grant system fixed permission: "
3360                        + name + " for package: " + packageName);
3361            }
3362
3363            final int result = permissionsState.grantRuntimePermission(bp, userId);
3364            switch (result) {
3365                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3366                    return;
3367                }
3368
3369                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3370                    mHandler.post(new Runnable() {
3371                        @Override
3372                        public void run() {
3373                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3374                        }
3375                    });
3376                } break;
3377            }
3378
3379            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3380
3381            // Not critical if that is lost - app has to request again.
3382            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3383        }
3384
3385        if (READ_EXTERNAL_STORAGE.equals(name)
3386                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3387            final long token = Binder.clearCallingIdentity();
3388            try {
3389                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3390                storage.remountUid(uid);
3391            } finally {
3392                Binder.restoreCallingIdentity(token);
3393            }
3394        }
3395    }
3396
3397    @Override
3398    public void revokeRuntimePermission(String packageName, String name, int userId) {
3399        if (!sUserManager.exists(userId)) {
3400            Log.e(TAG, "No such user:" + userId);
3401            return;
3402        }
3403
3404        mContext.enforceCallingOrSelfPermission(
3405                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3406                "revokeRuntimePermission");
3407
3408        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3409                "revokeRuntimePermission");
3410
3411        final SettingBase sb;
3412
3413        synchronized (mPackages) {
3414            final PackageParser.Package pkg = mPackages.get(packageName);
3415            if (pkg == null) {
3416                throw new IllegalArgumentException("Unknown package: " + packageName);
3417            }
3418
3419            final BasePermission bp = mSettings.mPermissions.get(name);
3420            if (bp == null) {
3421                throw new IllegalArgumentException("Unknown permission: " + name);
3422            }
3423
3424            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3425
3426            sb = (SettingBase) pkg.mExtras;
3427            if (sb == null) {
3428                throw new IllegalArgumentException("Unknown package: " + packageName);
3429            }
3430
3431            final PermissionsState permissionsState = sb.getPermissionsState();
3432
3433            final int flags = permissionsState.getPermissionFlags(name, userId);
3434            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3435                throw new SecurityException("Cannot revoke system fixed permission: "
3436                        + name + " for package: " + packageName);
3437            }
3438
3439            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3440                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3441                return;
3442            }
3443
3444            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3445
3446            // Critical, after this call app should never have the permission.
3447            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3448        }
3449
3450        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3451    }
3452
3453    @Override
3454    public void resetRuntimePermissions() {
3455        mContext.enforceCallingOrSelfPermission(
3456                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3457                "revokeRuntimePermission");
3458
3459        int callingUid = Binder.getCallingUid();
3460        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3461            mContext.enforceCallingOrSelfPermission(
3462                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3463                    "resetRuntimePermissions");
3464        }
3465
3466        final int[] userIds;
3467
3468        synchronized (mPackages) {
3469            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3470            final int userCount = UserManagerService.getInstance().getUserIds().length;
3471            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3472        }
3473
3474        for (int userId : userIds) {
3475            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3476        }
3477    }
3478
3479    @Override
3480    public int getPermissionFlags(String name, String packageName, int userId) {
3481        if (!sUserManager.exists(userId)) {
3482            return 0;
3483        }
3484
3485        mContext.enforceCallingOrSelfPermission(
3486                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3487                "getPermissionFlags");
3488
3489        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3490                "getPermissionFlags");
3491
3492        synchronized (mPackages) {
3493            final PackageParser.Package pkg = mPackages.get(packageName);
3494            if (pkg == null) {
3495                throw new IllegalArgumentException("Unknown package: " + packageName);
3496            }
3497
3498            final BasePermission bp = mSettings.mPermissions.get(name);
3499            if (bp == null) {
3500                throw new IllegalArgumentException("Unknown permission: " + name);
3501            }
3502
3503            SettingBase sb = (SettingBase) pkg.mExtras;
3504            if (sb == null) {
3505                throw new IllegalArgumentException("Unknown package: " + packageName);
3506            }
3507
3508            PermissionsState permissionsState = sb.getPermissionsState();
3509            return permissionsState.getPermissionFlags(name, userId);
3510        }
3511    }
3512
3513    @Override
3514    public void updatePermissionFlags(String name, String packageName, int flagMask,
3515            int flagValues, int userId) {
3516        if (!sUserManager.exists(userId)) {
3517            return;
3518        }
3519
3520        mContext.enforceCallingOrSelfPermission(
3521                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3522                "updatePermissionFlags");
3523
3524        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3525                "updatePermissionFlags");
3526
3527        // Only the system can change system fixed flags.
3528        if (getCallingUid() != Process.SYSTEM_UID) {
3529            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3530            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3531        }
3532
3533        synchronized (mPackages) {
3534            final PackageParser.Package pkg = mPackages.get(packageName);
3535            if (pkg == null) {
3536                throw new IllegalArgumentException("Unknown package: " + packageName);
3537            }
3538
3539            final BasePermission bp = mSettings.mPermissions.get(name);
3540            if (bp == null) {
3541                throw new IllegalArgumentException("Unknown permission: " + name);
3542            }
3543
3544            SettingBase sb = (SettingBase) pkg.mExtras;
3545            if (sb == null) {
3546                throw new IllegalArgumentException("Unknown package: " + packageName);
3547            }
3548
3549            PermissionsState permissionsState = sb.getPermissionsState();
3550
3551            // Only the package manager can change flags for system component permissions.
3552            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3553            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3554                return;
3555            }
3556
3557            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3558
3559            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3560                // Install and runtime permissions are stored in different places,
3561                // so figure out what permission changed and persist the change.
3562                if (permissionsState.getInstallPermissionState(name) != null) {
3563                    scheduleWriteSettingsLocked();
3564                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3565                        || hadState) {
3566                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3567                }
3568            }
3569        }
3570    }
3571
3572    /**
3573     * Update the permission flags for all packages and runtime permissions of a user in order
3574     * to allow device or profile owner to remove POLICY_FIXED.
3575     */
3576    @Override
3577    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3578        if (!sUserManager.exists(userId)) {
3579            return;
3580        }
3581
3582        mContext.enforceCallingOrSelfPermission(
3583                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3584                "updatePermissionFlagsForAllApps");
3585
3586        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3587                "updatePermissionFlagsForAllApps");
3588
3589        // Only the system can change system fixed flags.
3590        if (getCallingUid() != Process.SYSTEM_UID) {
3591            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3592            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3593        }
3594
3595        synchronized (mPackages) {
3596            boolean changed = false;
3597            final int packageCount = mPackages.size();
3598            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3599                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3600                SettingBase sb = (SettingBase) pkg.mExtras;
3601                if (sb == null) {
3602                    continue;
3603                }
3604                PermissionsState permissionsState = sb.getPermissionsState();
3605                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3606                        userId, flagMask, flagValues);
3607            }
3608            if (changed) {
3609                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3610            }
3611        }
3612    }
3613
3614    @Override
3615    public boolean shouldShowRequestPermissionRationale(String permissionName,
3616            String packageName, int userId) {
3617        if (UserHandle.getCallingUserId() != userId) {
3618            mContext.enforceCallingPermission(
3619                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3620                    "canShowRequestPermissionRationale for user " + userId);
3621        }
3622
3623        final int uid = getPackageUid(packageName, userId);
3624        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3625            return false;
3626        }
3627
3628        if (checkPermission(permissionName, packageName, userId)
3629                == PackageManager.PERMISSION_GRANTED) {
3630            return false;
3631        }
3632
3633        final int flags;
3634
3635        final long identity = Binder.clearCallingIdentity();
3636        try {
3637            flags = getPermissionFlags(permissionName,
3638                    packageName, userId);
3639        } finally {
3640            Binder.restoreCallingIdentity(identity);
3641        }
3642
3643        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3644                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3645                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3646
3647        if ((flags & fixedFlags) != 0) {
3648            return false;
3649        }
3650
3651        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3652    }
3653
3654    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3655        BasePermission bp = mSettings.mPermissions.get(permission);
3656        if (bp == null) {
3657            throw new SecurityException("Missing " + permission + " permission");
3658        }
3659
3660        SettingBase sb = (SettingBase) pkg.mExtras;
3661        PermissionsState permissionsState = sb.getPermissionsState();
3662
3663        if (permissionsState.grantInstallPermission(bp) !=
3664                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3665            scheduleWriteSettingsLocked();
3666        }
3667    }
3668
3669    @Override
3670    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3671        mContext.enforceCallingOrSelfPermission(
3672                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3673                "addOnPermissionsChangeListener");
3674
3675        synchronized (mPackages) {
3676            mOnPermissionChangeListeners.addListenerLocked(listener);
3677        }
3678    }
3679
3680    @Override
3681    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3682        synchronized (mPackages) {
3683            mOnPermissionChangeListeners.removeListenerLocked(listener);
3684        }
3685    }
3686
3687    @Override
3688    public boolean isProtectedBroadcast(String actionName) {
3689        synchronized (mPackages) {
3690            return mProtectedBroadcasts.contains(actionName);
3691        }
3692    }
3693
3694    @Override
3695    public int checkSignatures(String pkg1, String pkg2) {
3696        synchronized (mPackages) {
3697            final PackageParser.Package p1 = mPackages.get(pkg1);
3698            final PackageParser.Package p2 = mPackages.get(pkg2);
3699            if (p1 == null || p1.mExtras == null
3700                    || p2 == null || p2.mExtras == null) {
3701                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3702            }
3703            return compareSignatures(p1.mSignatures, p2.mSignatures);
3704        }
3705    }
3706
3707    @Override
3708    public int checkUidSignatures(int uid1, int uid2) {
3709        // Map to base uids.
3710        uid1 = UserHandle.getAppId(uid1);
3711        uid2 = UserHandle.getAppId(uid2);
3712        // reader
3713        synchronized (mPackages) {
3714            Signature[] s1;
3715            Signature[] s2;
3716            Object obj = mSettings.getUserIdLPr(uid1);
3717            if (obj != null) {
3718                if (obj instanceof SharedUserSetting) {
3719                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3720                } else if (obj instanceof PackageSetting) {
3721                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3722                } else {
3723                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3724                }
3725            } else {
3726                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3727            }
3728            obj = mSettings.getUserIdLPr(uid2);
3729            if (obj != null) {
3730                if (obj instanceof SharedUserSetting) {
3731                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3732                } else if (obj instanceof PackageSetting) {
3733                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3734                } else {
3735                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3736                }
3737            } else {
3738                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3739            }
3740            return compareSignatures(s1, s2);
3741        }
3742    }
3743
3744    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3745        final long identity = Binder.clearCallingIdentity();
3746        try {
3747            if (sb instanceof SharedUserSetting) {
3748                SharedUserSetting sus = (SharedUserSetting) sb;
3749                final int packageCount = sus.packages.size();
3750                for (int i = 0; i < packageCount; i++) {
3751                    PackageSetting susPs = sus.packages.valueAt(i);
3752                    if (userId == UserHandle.USER_ALL) {
3753                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3754                    } else {
3755                        final int uid = UserHandle.getUid(userId, susPs.appId);
3756                        killUid(uid, reason);
3757                    }
3758                }
3759            } else if (sb instanceof PackageSetting) {
3760                PackageSetting ps = (PackageSetting) sb;
3761                if (userId == UserHandle.USER_ALL) {
3762                    killApplication(ps.pkg.packageName, ps.appId, reason);
3763                } else {
3764                    final int uid = UserHandle.getUid(userId, ps.appId);
3765                    killUid(uid, reason);
3766                }
3767            }
3768        } finally {
3769            Binder.restoreCallingIdentity(identity);
3770        }
3771    }
3772
3773    private static void killUid(int uid, String reason) {
3774        IActivityManager am = ActivityManagerNative.getDefault();
3775        if (am != null) {
3776            try {
3777                am.killUid(uid, reason);
3778            } catch (RemoteException e) {
3779                /* ignore - same process */
3780            }
3781        }
3782    }
3783
3784    /**
3785     * Compares two sets of signatures. Returns:
3786     * <br />
3787     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3788     * <br />
3789     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3790     * <br />
3791     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3792     * <br />
3793     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3794     * <br />
3795     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3796     */
3797    static int compareSignatures(Signature[] s1, Signature[] s2) {
3798        if (s1 == null) {
3799            return s2 == null
3800                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3801                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3802        }
3803
3804        if (s2 == null) {
3805            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3806        }
3807
3808        if (s1.length != s2.length) {
3809            return PackageManager.SIGNATURE_NO_MATCH;
3810        }
3811
3812        // Since both signature sets are of size 1, we can compare without HashSets.
3813        if (s1.length == 1) {
3814            return s1[0].equals(s2[0]) ?
3815                    PackageManager.SIGNATURE_MATCH :
3816                    PackageManager.SIGNATURE_NO_MATCH;
3817        }
3818
3819        ArraySet<Signature> set1 = new ArraySet<Signature>();
3820        for (Signature sig : s1) {
3821            set1.add(sig);
3822        }
3823        ArraySet<Signature> set2 = new ArraySet<Signature>();
3824        for (Signature sig : s2) {
3825            set2.add(sig);
3826        }
3827        // Make sure s2 contains all signatures in s1.
3828        if (set1.equals(set2)) {
3829            return PackageManager.SIGNATURE_MATCH;
3830        }
3831        return PackageManager.SIGNATURE_NO_MATCH;
3832    }
3833
3834    /**
3835     * If the database version for this type of package (internal storage or
3836     * external storage) is less than the version where package signatures
3837     * were updated, return true.
3838     */
3839    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3840        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3841                DatabaseVersion.SIGNATURE_END_ENTITY))
3842                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3843                        DatabaseVersion.SIGNATURE_END_ENTITY));
3844    }
3845
3846    /**
3847     * Used for backward compatibility to make sure any packages with
3848     * certificate chains get upgraded to the new style. {@code existingSigs}
3849     * will be in the old format (since they were stored on disk from before the
3850     * system upgrade) and {@code scannedSigs} will be in the newer format.
3851     */
3852    private int compareSignaturesCompat(PackageSignatures existingSigs,
3853            PackageParser.Package scannedPkg) {
3854        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3855            return PackageManager.SIGNATURE_NO_MATCH;
3856        }
3857
3858        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3859        for (Signature sig : existingSigs.mSignatures) {
3860            existingSet.add(sig);
3861        }
3862        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3863        for (Signature sig : scannedPkg.mSignatures) {
3864            try {
3865                Signature[] chainSignatures = sig.getChainSignatures();
3866                for (Signature chainSig : chainSignatures) {
3867                    scannedCompatSet.add(chainSig);
3868                }
3869            } catch (CertificateEncodingException e) {
3870                scannedCompatSet.add(sig);
3871            }
3872        }
3873        /*
3874         * Make sure the expanded scanned set contains all signatures in the
3875         * existing one.
3876         */
3877        if (scannedCompatSet.equals(existingSet)) {
3878            // Migrate the old signatures to the new scheme.
3879            existingSigs.assignSignatures(scannedPkg.mSignatures);
3880            // The new KeySets will be re-added later in the scanning process.
3881            synchronized (mPackages) {
3882                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3883            }
3884            return PackageManager.SIGNATURE_MATCH;
3885        }
3886        return PackageManager.SIGNATURE_NO_MATCH;
3887    }
3888
3889    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3890        if (isExternal(scannedPkg)) {
3891            return mSettings.isExternalDatabaseVersionOlderThan(
3892                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3893        } else {
3894            return mSettings.isInternalDatabaseVersionOlderThan(
3895                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3896        }
3897    }
3898
3899    private int compareSignaturesRecover(PackageSignatures existingSigs,
3900            PackageParser.Package scannedPkg) {
3901        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3902            return PackageManager.SIGNATURE_NO_MATCH;
3903        }
3904
3905        String msg = null;
3906        try {
3907            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3908                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3909                        + scannedPkg.packageName);
3910                return PackageManager.SIGNATURE_MATCH;
3911            }
3912        } catch (CertificateException e) {
3913            msg = e.getMessage();
3914        }
3915
3916        logCriticalInfo(Log.INFO,
3917                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3918        return PackageManager.SIGNATURE_NO_MATCH;
3919    }
3920
3921    @Override
3922    public String[] getPackagesForUid(int uid) {
3923        uid = UserHandle.getAppId(uid);
3924        // reader
3925        synchronized (mPackages) {
3926            Object obj = mSettings.getUserIdLPr(uid);
3927            if (obj instanceof SharedUserSetting) {
3928                final SharedUserSetting sus = (SharedUserSetting) obj;
3929                final int N = sus.packages.size();
3930                final String[] res = new String[N];
3931                final Iterator<PackageSetting> it = sus.packages.iterator();
3932                int i = 0;
3933                while (it.hasNext()) {
3934                    res[i++] = it.next().name;
3935                }
3936                return res;
3937            } else if (obj instanceof PackageSetting) {
3938                final PackageSetting ps = (PackageSetting) obj;
3939                return new String[] { ps.name };
3940            }
3941        }
3942        return null;
3943    }
3944
3945    @Override
3946    public String getNameForUid(int uid) {
3947        // reader
3948        synchronized (mPackages) {
3949            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3950            if (obj instanceof SharedUserSetting) {
3951                final SharedUserSetting sus = (SharedUserSetting) obj;
3952                return sus.name + ":" + sus.userId;
3953            } else if (obj instanceof PackageSetting) {
3954                final PackageSetting ps = (PackageSetting) obj;
3955                return ps.name;
3956            }
3957        }
3958        return null;
3959    }
3960
3961    @Override
3962    public int getUidForSharedUser(String sharedUserName) {
3963        if(sharedUserName == null) {
3964            return -1;
3965        }
3966        // reader
3967        synchronized (mPackages) {
3968            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3969            if (suid == null) {
3970                return -1;
3971            }
3972            return suid.userId;
3973        }
3974    }
3975
3976    @Override
3977    public int getFlagsForUid(int uid) {
3978        synchronized (mPackages) {
3979            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3980            if (obj instanceof SharedUserSetting) {
3981                final SharedUserSetting sus = (SharedUserSetting) obj;
3982                return sus.pkgFlags;
3983            } else if (obj instanceof PackageSetting) {
3984                final PackageSetting ps = (PackageSetting) obj;
3985                return ps.pkgFlags;
3986            }
3987        }
3988        return 0;
3989    }
3990
3991    @Override
3992    public int getPrivateFlagsForUid(int uid) {
3993        synchronized (mPackages) {
3994            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3995            if (obj instanceof SharedUserSetting) {
3996                final SharedUserSetting sus = (SharedUserSetting) obj;
3997                return sus.pkgPrivateFlags;
3998            } else if (obj instanceof PackageSetting) {
3999                final PackageSetting ps = (PackageSetting) obj;
4000                return ps.pkgPrivateFlags;
4001            }
4002        }
4003        return 0;
4004    }
4005
4006    @Override
4007    public boolean isUidPrivileged(int uid) {
4008        uid = UserHandle.getAppId(uid);
4009        // reader
4010        synchronized (mPackages) {
4011            Object obj = mSettings.getUserIdLPr(uid);
4012            if (obj instanceof SharedUserSetting) {
4013                final SharedUserSetting sus = (SharedUserSetting) obj;
4014                final Iterator<PackageSetting> it = sus.packages.iterator();
4015                while (it.hasNext()) {
4016                    if (it.next().isPrivileged()) {
4017                        return true;
4018                    }
4019                }
4020            } else if (obj instanceof PackageSetting) {
4021                final PackageSetting ps = (PackageSetting) obj;
4022                return ps.isPrivileged();
4023            }
4024        }
4025        return false;
4026    }
4027
4028    @Override
4029    public String[] getAppOpPermissionPackages(String permissionName) {
4030        synchronized (mPackages) {
4031            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4032            if (pkgs == null) {
4033                return null;
4034            }
4035            return pkgs.toArray(new String[pkgs.size()]);
4036        }
4037    }
4038
4039    @Override
4040    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4041            int flags, int userId) {
4042        if (!sUserManager.exists(userId)) return null;
4043        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4044        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4045        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4046    }
4047
4048    @Override
4049    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4050            IntentFilter filter, int match, ComponentName activity) {
4051        final int userId = UserHandle.getCallingUserId();
4052        if (DEBUG_PREFERRED) {
4053            Log.v(TAG, "setLastChosenActivity intent=" + intent
4054                + " resolvedType=" + resolvedType
4055                + " flags=" + flags
4056                + " filter=" + filter
4057                + " match=" + match
4058                + " activity=" + activity);
4059            filter.dump(new PrintStreamPrinter(System.out), "    ");
4060        }
4061        intent.setComponent(null);
4062        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4063        // Find any earlier preferred or last chosen entries and nuke them
4064        findPreferredActivity(intent, resolvedType,
4065                flags, query, 0, false, true, false, userId);
4066        // Add the new activity as the last chosen for this filter
4067        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4068                "Setting last chosen");
4069    }
4070
4071    @Override
4072    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4073        final int userId = UserHandle.getCallingUserId();
4074        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4075        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4076        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4077                false, false, false, userId);
4078    }
4079
4080    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4081            int flags, List<ResolveInfo> query, int userId) {
4082        if (query != null) {
4083            final int N = query.size();
4084            if (N == 1) {
4085                return query.get(0);
4086            } else if (N > 1) {
4087                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4088                // If there is more than one activity with the same priority,
4089                // then let the user decide between them.
4090                ResolveInfo r0 = query.get(0);
4091                ResolveInfo r1 = query.get(1);
4092                if (DEBUG_INTENT_MATCHING || debug) {
4093                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4094                            + r1.activityInfo.name + "=" + r1.priority);
4095                }
4096                // If the first activity has a higher priority, or a different
4097                // default, then it is always desireable to pick it.
4098                if (r0.priority != r1.priority
4099                        || r0.preferredOrder != r1.preferredOrder
4100                        || r0.isDefault != r1.isDefault) {
4101                    return query.get(0);
4102                }
4103                // If we have saved a preference for a preferred activity for
4104                // this Intent, use that.
4105                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4106                        flags, query, r0.priority, true, false, debug, userId);
4107                if (ri != null) {
4108                    return ri;
4109                }
4110                if (userId != 0) {
4111                    ri = new ResolveInfo(mResolveInfo);
4112                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4113                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4114                            ri.activityInfo.applicationInfo);
4115                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4116                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4117                    return ri;
4118                }
4119                return mResolveInfo;
4120            }
4121        }
4122        return null;
4123    }
4124
4125    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4126            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4127        final int N = query.size();
4128        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4129                .get(userId);
4130        // Get the list of persistent preferred activities that handle the intent
4131        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4132        List<PersistentPreferredActivity> pprefs = ppir != null
4133                ? ppir.queryIntent(intent, resolvedType,
4134                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4135                : null;
4136        if (pprefs != null && pprefs.size() > 0) {
4137            final int M = pprefs.size();
4138            for (int i=0; i<M; i++) {
4139                final PersistentPreferredActivity ppa = pprefs.get(i);
4140                if (DEBUG_PREFERRED || debug) {
4141                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4142                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4143                            + "\n  component=" + ppa.mComponent);
4144                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4145                }
4146                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4147                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4148                if (DEBUG_PREFERRED || debug) {
4149                    Slog.v(TAG, "Found persistent preferred activity:");
4150                    if (ai != null) {
4151                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4152                    } else {
4153                        Slog.v(TAG, "  null");
4154                    }
4155                }
4156                if (ai == null) {
4157                    // This previously registered persistent preferred activity
4158                    // component is no longer known. Ignore it and do NOT remove it.
4159                    continue;
4160                }
4161                for (int j=0; j<N; j++) {
4162                    final ResolveInfo ri = query.get(j);
4163                    if (!ri.activityInfo.applicationInfo.packageName
4164                            .equals(ai.applicationInfo.packageName)) {
4165                        continue;
4166                    }
4167                    if (!ri.activityInfo.name.equals(ai.name)) {
4168                        continue;
4169                    }
4170                    //  Found a persistent preference that can handle the intent.
4171                    if (DEBUG_PREFERRED || debug) {
4172                        Slog.v(TAG, "Returning persistent preferred activity: " +
4173                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4174                    }
4175                    return ri;
4176                }
4177            }
4178        }
4179        return null;
4180    }
4181
4182    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4183            List<ResolveInfo> query, int priority, boolean always,
4184            boolean removeMatches, boolean debug, int userId) {
4185        if (!sUserManager.exists(userId)) return null;
4186        // writer
4187        synchronized (mPackages) {
4188            if (intent.getSelector() != null) {
4189                intent = intent.getSelector();
4190            }
4191            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4192
4193            // Try to find a matching persistent preferred activity.
4194            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4195                    debug, userId);
4196
4197            // If a persistent preferred activity matched, use it.
4198            if (pri != null) {
4199                return pri;
4200            }
4201
4202            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4203            // Get the list of preferred activities that handle the intent
4204            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4205            List<PreferredActivity> prefs = pir != null
4206                    ? pir.queryIntent(intent, resolvedType,
4207                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4208                    : null;
4209            if (prefs != null && prefs.size() > 0) {
4210                boolean changed = false;
4211                try {
4212                    // First figure out how good the original match set is.
4213                    // We will only allow preferred activities that came
4214                    // from the same match quality.
4215                    int match = 0;
4216
4217                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4218
4219                    final int N = query.size();
4220                    for (int j=0; j<N; j++) {
4221                        final ResolveInfo ri = query.get(j);
4222                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4223                                + ": 0x" + Integer.toHexString(match));
4224                        if (ri.match > match) {
4225                            match = ri.match;
4226                        }
4227                    }
4228
4229                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4230                            + Integer.toHexString(match));
4231
4232                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4233                    final int M = prefs.size();
4234                    for (int i=0; i<M; i++) {
4235                        final PreferredActivity pa = prefs.get(i);
4236                        if (DEBUG_PREFERRED || debug) {
4237                            Slog.v(TAG, "Checking PreferredActivity ds="
4238                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4239                                    + "\n  component=" + pa.mPref.mComponent);
4240                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4241                        }
4242                        if (pa.mPref.mMatch != match) {
4243                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4244                                    + Integer.toHexString(pa.mPref.mMatch));
4245                            continue;
4246                        }
4247                        // If it's not an "always" type preferred activity and that's what we're
4248                        // looking for, skip it.
4249                        if (always && !pa.mPref.mAlways) {
4250                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4251                            continue;
4252                        }
4253                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4254                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4255                        if (DEBUG_PREFERRED || debug) {
4256                            Slog.v(TAG, "Found preferred activity:");
4257                            if (ai != null) {
4258                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4259                            } else {
4260                                Slog.v(TAG, "  null");
4261                            }
4262                        }
4263                        if (ai == null) {
4264                            // This previously registered preferred activity
4265                            // component is no longer known.  Most likely an update
4266                            // to the app was installed and in the new version this
4267                            // component no longer exists.  Clean it up by removing
4268                            // it from the preferred activities list, and skip it.
4269                            Slog.w(TAG, "Removing dangling preferred activity: "
4270                                    + pa.mPref.mComponent);
4271                            pir.removeFilter(pa);
4272                            changed = true;
4273                            continue;
4274                        }
4275                        for (int j=0; j<N; j++) {
4276                            final ResolveInfo ri = query.get(j);
4277                            if (!ri.activityInfo.applicationInfo.packageName
4278                                    .equals(ai.applicationInfo.packageName)) {
4279                                continue;
4280                            }
4281                            if (!ri.activityInfo.name.equals(ai.name)) {
4282                                continue;
4283                            }
4284
4285                            if (removeMatches) {
4286                                pir.removeFilter(pa);
4287                                changed = true;
4288                                if (DEBUG_PREFERRED) {
4289                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4290                                }
4291                                break;
4292                            }
4293
4294                            // Okay we found a previously set preferred or last chosen app.
4295                            // If the result set is different from when this
4296                            // was created, we need to clear it and re-ask the
4297                            // user their preference, if we're looking for an "always" type entry.
4298                            if (always && !pa.mPref.sameSet(query)) {
4299                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4300                                        + intent + " type " + resolvedType);
4301                                if (DEBUG_PREFERRED) {
4302                                    Slog.v(TAG, "Removing preferred activity since set changed "
4303                                            + pa.mPref.mComponent);
4304                                }
4305                                pir.removeFilter(pa);
4306                                // Re-add the filter as a "last chosen" entry (!always)
4307                                PreferredActivity lastChosen = new PreferredActivity(
4308                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4309                                pir.addFilter(lastChosen);
4310                                changed = true;
4311                                return null;
4312                            }
4313
4314                            // Yay! Either the set matched or we're looking for the last chosen
4315                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4316                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4317                            return ri;
4318                        }
4319                    }
4320                } finally {
4321                    if (changed) {
4322                        if (DEBUG_PREFERRED) {
4323                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4324                        }
4325                        scheduleWritePackageRestrictionsLocked(userId);
4326                    }
4327                }
4328            }
4329        }
4330        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4331        return null;
4332    }
4333
4334    /*
4335     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4336     */
4337    @Override
4338    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4339            int targetUserId) {
4340        mContext.enforceCallingOrSelfPermission(
4341                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4342        List<CrossProfileIntentFilter> matches =
4343                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4344        if (matches != null) {
4345            int size = matches.size();
4346            for (int i = 0; i < size; i++) {
4347                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4348            }
4349        }
4350        if (hasWebURI(intent)) {
4351            // cross-profile app linking works only towards the parent.
4352            final UserInfo parent = getProfileParent(sourceUserId);
4353            synchronized(mPackages) {
4354                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4355                        parent.id) != null;
4356            }
4357        }
4358        return false;
4359    }
4360
4361    private UserInfo getProfileParent(int userId) {
4362        final long identity = Binder.clearCallingIdentity();
4363        try {
4364            return sUserManager.getProfileParent(userId);
4365        } finally {
4366            Binder.restoreCallingIdentity(identity);
4367        }
4368    }
4369
4370    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4371            String resolvedType, int userId) {
4372        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4373        if (resolver != null) {
4374            return resolver.queryIntent(intent, resolvedType, false, userId);
4375        }
4376        return null;
4377    }
4378
4379    @Override
4380    public List<ResolveInfo> queryIntentActivities(Intent intent,
4381            String resolvedType, int flags, int userId) {
4382        if (!sUserManager.exists(userId)) return Collections.emptyList();
4383        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4384        ComponentName comp = intent.getComponent();
4385        if (comp == null) {
4386            if (intent.getSelector() != null) {
4387                intent = intent.getSelector();
4388                comp = intent.getComponent();
4389            }
4390        }
4391
4392        if (comp != null) {
4393            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4394            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4395            if (ai != null) {
4396                final ResolveInfo ri = new ResolveInfo();
4397                ri.activityInfo = ai;
4398                list.add(ri);
4399            }
4400            return list;
4401        }
4402
4403        // reader
4404        synchronized (mPackages) {
4405            final String pkgName = intent.getPackage();
4406            if (pkgName == null) {
4407                List<CrossProfileIntentFilter> matchingFilters =
4408                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4409                // Check for results that need to skip the current profile.
4410                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4411                        resolvedType, flags, userId);
4412                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4413                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4414                    result.add(xpResolveInfo);
4415                    return filterIfNotPrimaryUser(result, userId);
4416                }
4417
4418                // Check for results in the current profile.
4419                List<ResolveInfo> result = mActivities.queryIntent(
4420                        intent, resolvedType, flags, userId);
4421
4422                // Check for cross profile results.
4423                xpResolveInfo = queryCrossProfileIntents(
4424                        matchingFilters, intent, resolvedType, flags, userId);
4425                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4426                    result.add(xpResolveInfo);
4427                    Collections.sort(result, mResolvePrioritySorter);
4428                }
4429                result = filterIfNotPrimaryUser(result, userId);
4430                if (hasWebURI(intent)) {
4431                    CrossProfileDomainInfo xpDomainInfo = null;
4432                    final UserInfo parent = getProfileParent(userId);
4433                    if (parent != null) {
4434                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4435                                flags, userId, parent.id);
4436                    }
4437                    if (xpDomainInfo != null) {
4438                        if (xpResolveInfo != null) {
4439                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4440                            // in the result.
4441                            result.remove(xpResolveInfo);
4442                        }
4443                        if (result.size() == 0) {
4444                            result.add(xpDomainInfo.resolveInfo);
4445                            return result;
4446                        }
4447                    } else if (result.size() <= 1) {
4448                        return result;
4449                    }
4450                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4451                            xpDomainInfo);
4452                    Collections.sort(result, mResolvePrioritySorter);
4453                }
4454                return result;
4455            }
4456            final PackageParser.Package pkg = mPackages.get(pkgName);
4457            if (pkg != null) {
4458                return filterIfNotPrimaryUser(
4459                        mActivities.queryIntentForPackage(
4460                                intent, resolvedType, flags, pkg.activities, userId),
4461                        userId);
4462            }
4463            return new ArrayList<ResolveInfo>();
4464        }
4465    }
4466
4467    private static class CrossProfileDomainInfo {
4468        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4469        ResolveInfo resolveInfo;
4470        /* Best domain verification status of the activities found in the other profile */
4471        int bestDomainVerificationStatus;
4472    }
4473
4474    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4475            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4476        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4477                sourceUserId)) {
4478            return null;
4479        }
4480        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4481                resolvedType, flags, parentUserId);
4482
4483        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4484            return null;
4485        }
4486        CrossProfileDomainInfo result = null;
4487        int size = resultTargetUser.size();
4488        for (int i = 0; i < size; i++) {
4489            ResolveInfo riTargetUser = resultTargetUser.get(i);
4490            // Intent filter verification is only for filters that specify a host. So don't return
4491            // those that handle all web uris.
4492            if (riTargetUser.handleAllWebDataURI) {
4493                continue;
4494            }
4495            String packageName = riTargetUser.activityInfo.packageName;
4496            PackageSetting ps = mSettings.mPackages.get(packageName);
4497            if (ps == null) {
4498                continue;
4499            }
4500            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4501            if (result == null) {
4502                result = new CrossProfileDomainInfo();
4503                result.resolveInfo =
4504                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4505                result.bestDomainVerificationStatus = status;
4506            } else {
4507                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4508                        result.bestDomainVerificationStatus);
4509            }
4510        }
4511        return result;
4512    }
4513
4514    /**
4515     * Verification statuses are ordered from the worse to the best, except for
4516     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4517     */
4518    private int bestDomainVerificationStatus(int status1, int status2) {
4519        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4520            return status2;
4521        }
4522        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4523            return status1;
4524        }
4525        return (int) MathUtils.max(status1, status2);
4526    }
4527
4528    private boolean isUserEnabled(int userId) {
4529        long callingId = Binder.clearCallingIdentity();
4530        try {
4531            UserInfo userInfo = sUserManager.getUserInfo(userId);
4532            return userInfo != null && userInfo.isEnabled();
4533        } finally {
4534            Binder.restoreCallingIdentity(callingId);
4535        }
4536    }
4537
4538    /**
4539     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4540     *
4541     * @return filtered list
4542     */
4543    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4544        if (userId == UserHandle.USER_OWNER) {
4545            return resolveInfos;
4546        }
4547        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4548            ResolveInfo info = resolveInfos.get(i);
4549            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4550                resolveInfos.remove(i);
4551            }
4552        }
4553        return resolveInfos;
4554    }
4555
4556    private static boolean hasWebURI(Intent intent) {
4557        if (intent.getData() == null) {
4558            return false;
4559        }
4560        final String scheme = intent.getScheme();
4561        if (TextUtils.isEmpty(scheme)) {
4562            return false;
4563        }
4564        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4565    }
4566
4567    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4568            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4569        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4570            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4571                    candidates.size());
4572        }
4573
4574        final int userId = UserHandle.getCallingUserId();
4575        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4576        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4577        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4578        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4579        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4580
4581        synchronized (mPackages) {
4582            final int count = candidates.size();
4583            // First, try to use linked apps. Partition the candidates into four lists:
4584            // one for the final results, one for the "do not use ever", one for "undefined status"
4585            // and finally one for "browser app type".
4586            for (int n=0; n<count; n++) {
4587                ResolveInfo info = candidates.get(n);
4588                String packageName = info.activityInfo.packageName;
4589                PackageSetting ps = mSettings.mPackages.get(packageName);
4590                if (ps != null) {
4591                    // Add to the special match all list (Browser use case)
4592                    if (info.handleAllWebDataURI) {
4593                        matchAllList.add(info);
4594                        continue;
4595                    }
4596                    // Try to get the status from User settings first
4597                    int status = getDomainVerificationStatusLPr(ps, userId);
4598                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4599                        if (DEBUG_DOMAIN_VERIFICATION) {
4600                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4601                        }
4602                        alwaysList.add(info);
4603                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4604                        if (DEBUG_DOMAIN_VERIFICATION) {
4605                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4606                        }
4607                        neverList.add(info);
4608                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4609                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4610                        if (DEBUG_DOMAIN_VERIFICATION) {
4611                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4612                        }
4613                        undefinedList.add(info);
4614                    }
4615                }
4616            }
4617            // First try to add the "always" resolution for the current user if there is any
4618            if (alwaysList.size() > 0) {
4619                result.addAll(alwaysList);
4620            // if there is an "always" for the parent user, add it.
4621            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4622                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4623                result.add(xpDomainInfo.resolveInfo);
4624            } else {
4625                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4626                result.addAll(undefinedList);
4627                if (xpDomainInfo != null && (
4628                        xpDomainInfo.bestDomainVerificationStatus
4629                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4630                        || xpDomainInfo.bestDomainVerificationStatus
4631                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4632                    result.add(xpDomainInfo.resolveInfo);
4633                }
4634                // Also add Browsers (all of them or only the default one)
4635                if ((flags & MATCH_ALL) != 0) {
4636                    result.addAll(matchAllList);
4637                } else {
4638                    // Try to add the Default Browser if we can
4639                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4640                            UserHandle.myUserId());
4641                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4642                        boolean defaultBrowserFound = false;
4643                        final int browserCount = matchAllList.size();
4644                        for (int n=0; n<browserCount; n++) {
4645                            ResolveInfo browser = matchAllList.get(n);
4646                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4647                                result.add(browser);
4648                                defaultBrowserFound = true;
4649                                break;
4650                            }
4651                        }
4652                        if (!defaultBrowserFound) {
4653                            result.addAll(matchAllList);
4654                        }
4655                    } else {
4656                        result.addAll(matchAllList);
4657                    }
4658                }
4659
4660                // If there is nothing selected, add all candidates and remove the ones that the user
4661                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4662                if (result.size() == 0) {
4663                    result.addAll(candidates);
4664                    result.removeAll(neverList);
4665                }
4666            }
4667        }
4668        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4669            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4670                    result.size());
4671            for (ResolveInfo info : result) {
4672                Slog.v(TAG, "  + " + info.activityInfo);
4673            }
4674        }
4675        return result;
4676    }
4677
4678    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4679        int status = ps.getDomainVerificationStatusForUser(userId);
4680        // if none available, get the master status
4681        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4682            if (ps.getIntentFilterVerificationInfo() != null) {
4683                status = ps.getIntentFilterVerificationInfo().getStatus();
4684            }
4685        }
4686        return status;
4687    }
4688
4689    private ResolveInfo querySkipCurrentProfileIntents(
4690            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4691            int flags, int sourceUserId) {
4692        if (matchingFilters != null) {
4693            int size = matchingFilters.size();
4694            for (int i = 0; i < size; i ++) {
4695                CrossProfileIntentFilter filter = matchingFilters.get(i);
4696                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4697                    // Checking if there are activities in the target user that can handle the
4698                    // intent.
4699                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4700                            flags, sourceUserId);
4701                    if (resolveInfo != null) {
4702                        return resolveInfo;
4703                    }
4704                }
4705            }
4706        }
4707        return null;
4708    }
4709
4710    // Return matching ResolveInfo if any for skip current profile intent filters.
4711    private ResolveInfo queryCrossProfileIntents(
4712            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4713            int flags, int sourceUserId) {
4714        if (matchingFilters != null) {
4715            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4716            // match the same intent. For performance reasons, it is better not to
4717            // run queryIntent twice for the same userId
4718            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4719            int size = matchingFilters.size();
4720            for (int i = 0; i < size; i++) {
4721                CrossProfileIntentFilter filter = matchingFilters.get(i);
4722                int targetUserId = filter.getTargetUserId();
4723                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4724                        && !alreadyTriedUserIds.get(targetUserId)) {
4725                    // Checking if there are activities in the target user that can handle the
4726                    // intent.
4727                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4728                            flags, sourceUserId);
4729                    if (resolveInfo != null) return resolveInfo;
4730                    alreadyTriedUserIds.put(targetUserId, true);
4731                }
4732            }
4733        }
4734        return null;
4735    }
4736
4737    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4738            String resolvedType, int flags, int sourceUserId) {
4739        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4740                resolvedType, flags, filter.getTargetUserId());
4741        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4742            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4743        }
4744        return null;
4745    }
4746
4747    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4748            int sourceUserId, int targetUserId) {
4749        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4750        String className;
4751        if (targetUserId == UserHandle.USER_OWNER) {
4752            className = FORWARD_INTENT_TO_USER_OWNER;
4753        } else {
4754            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4755        }
4756        ComponentName forwardingActivityComponentName = new ComponentName(
4757                mAndroidApplication.packageName, className);
4758        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4759                sourceUserId);
4760        if (targetUserId == UserHandle.USER_OWNER) {
4761            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4762            forwardingResolveInfo.noResourceId = true;
4763        }
4764        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4765        forwardingResolveInfo.priority = 0;
4766        forwardingResolveInfo.preferredOrder = 0;
4767        forwardingResolveInfo.match = 0;
4768        forwardingResolveInfo.isDefault = true;
4769        forwardingResolveInfo.filter = filter;
4770        forwardingResolveInfo.targetUserId = targetUserId;
4771        return forwardingResolveInfo;
4772    }
4773
4774    @Override
4775    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4776            Intent[] specifics, String[] specificTypes, Intent intent,
4777            String resolvedType, int flags, int userId) {
4778        if (!sUserManager.exists(userId)) return Collections.emptyList();
4779        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4780                false, "query intent activity options");
4781        final String resultsAction = intent.getAction();
4782
4783        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4784                | PackageManager.GET_RESOLVED_FILTER, userId);
4785
4786        if (DEBUG_INTENT_MATCHING) {
4787            Log.v(TAG, "Query " + intent + ": " + results);
4788        }
4789
4790        int specificsPos = 0;
4791        int N;
4792
4793        // todo: note that the algorithm used here is O(N^2).  This
4794        // isn't a problem in our current environment, but if we start running
4795        // into situations where we have more than 5 or 10 matches then this
4796        // should probably be changed to something smarter...
4797
4798        // First we go through and resolve each of the specific items
4799        // that were supplied, taking care of removing any corresponding
4800        // duplicate items in the generic resolve list.
4801        if (specifics != null) {
4802            for (int i=0; i<specifics.length; i++) {
4803                final Intent sintent = specifics[i];
4804                if (sintent == null) {
4805                    continue;
4806                }
4807
4808                if (DEBUG_INTENT_MATCHING) {
4809                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4810                }
4811
4812                String action = sintent.getAction();
4813                if (resultsAction != null && resultsAction.equals(action)) {
4814                    // If this action was explicitly requested, then don't
4815                    // remove things that have it.
4816                    action = null;
4817                }
4818
4819                ResolveInfo ri = null;
4820                ActivityInfo ai = null;
4821
4822                ComponentName comp = sintent.getComponent();
4823                if (comp == null) {
4824                    ri = resolveIntent(
4825                        sintent,
4826                        specificTypes != null ? specificTypes[i] : null,
4827                            flags, userId);
4828                    if (ri == null) {
4829                        continue;
4830                    }
4831                    if (ri == mResolveInfo) {
4832                        // ACK!  Must do something better with this.
4833                    }
4834                    ai = ri.activityInfo;
4835                    comp = new ComponentName(ai.applicationInfo.packageName,
4836                            ai.name);
4837                } else {
4838                    ai = getActivityInfo(comp, flags, userId);
4839                    if (ai == null) {
4840                        continue;
4841                    }
4842                }
4843
4844                // Look for any generic query activities that are duplicates
4845                // of this specific one, and remove them from the results.
4846                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4847                N = results.size();
4848                int j;
4849                for (j=specificsPos; j<N; j++) {
4850                    ResolveInfo sri = results.get(j);
4851                    if ((sri.activityInfo.name.equals(comp.getClassName())
4852                            && sri.activityInfo.applicationInfo.packageName.equals(
4853                                    comp.getPackageName()))
4854                        || (action != null && sri.filter.matchAction(action))) {
4855                        results.remove(j);
4856                        if (DEBUG_INTENT_MATCHING) Log.v(
4857                            TAG, "Removing duplicate item from " + j
4858                            + " due to specific " + specificsPos);
4859                        if (ri == null) {
4860                            ri = sri;
4861                        }
4862                        j--;
4863                        N--;
4864                    }
4865                }
4866
4867                // Add this specific item to its proper place.
4868                if (ri == null) {
4869                    ri = new ResolveInfo();
4870                    ri.activityInfo = ai;
4871                }
4872                results.add(specificsPos, ri);
4873                ri.specificIndex = i;
4874                specificsPos++;
4875            }
4876        }
4877
4878        // Now we go through the remaining generic results and remove any
4879        // duplicate actions that are found here.
4880        N = results.size();
4881        for (int i=specificsPos; i<N-1; i++) {
4882            final ResolveInfo rii = results.get(i);
4883            if (rii.filter == null) {
4884                continue;
4885            }
4886
4887            // Iterate over all of the actions of this result's intent
4888            // filter...  typically this should be just one.
4889            final Iterator<String> it = rii.filter.actionsIterator();
4890            if (it == null) {
4891                continue;
4892            }
4893            while (it.hasNext()) {
4894                final String action = it.next();
4895                if (resultsAction != null && resultsAction.equals(action)) {
4896                    // If this action was explicitly requested, then don't
4897                    // remove things that have it.
4898                    continue;
4899                }
4900                for (int j=i+1; j<N; j++) {
4901                    final ResolveInfo rij = results.get(j);
4902                    if (rij.filter != null && rij.filter.hasAction(action)) {
4903                        results.remove(j);
4904                        if (DEBUG_INTENT_MATCHING) Log.v(
4905                            TAG, "Removing duplicate item from " + j
4906                            + " due to action " + action + " at " + i);
4907                        j--;
4908                        N--;
4909                    }
4910                }
4911            }
4912
4913            // If the caller didn't request filter information, drop it now
4914            // so we don't have to marshall/unmarshall it.
4915            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4916                rii.filter = null;
4917            }
4918        }
4919
4920        // Filter out the caller activity if so requested.
4921        if (caller != null) {
4922            N = results.size();
4923            for (int i=0; i<N; i++) {
4924                ActivityInfo ainfo = results.get(i).activityInfo;
4925                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4926                        && caller.getClassName().equals(ainfo.name)) {
4927                    results.remove(i);
4928                    break;
4929                }
4930            }
4931        }
4932
4933        // If the caller didn't request filter information,
4934        // drop them now so we don't have to
4935        // marshall/unmarshall it.
4936        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4937            N = results.size();
4938            for (int i=0; i<N; i++) {
4939                results.get(i).filter = null;
4940            }
4941        }
4942
4943        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4944        return results;
4945    }
4946
4947    @Override
4948    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4949            int userId) {
4950        if (!sUserManager.exists(userId)) return Collections.emptyList();
4951        ComponentName comp = intent.getComponent();
4952        if (comp == null) {
4953            if (intent.getSelector() != null) {
4954                intent = intent.getSelector();
4955                comp = intent.getComponent();
4956            }
4957        }
4958        if (comp != null) {
4959            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4960            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4961            if (ai != null) {
4962                ResolveInfo ri = new ResolveInfo();
4963                ri.activityInfo = ai;
4964                list.add(ri);
4965            }
4966            return list;
4967        }
4968
4969        // reader
4970        synchronized (mPackages) {
4971            String pkgName = intent.getPackage();
4972            if (pkgName == null) {
4973                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4974            }
4975            final PackageParser.Package pkg = mPackages.get(pkgName);
4976            if (pkg != null) {
4977                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4978                        userId);
4979            }
4980            return null;
4981        }
4982    }
4983
4984    @Override
4985    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4986        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4987        if (!sUserManager.exists(userId)) return null;
4988        if (query != null) {
4989            if (query.size() >= 1) {
4990                // If there is more than one service with the same priority,
4991                // just arbitrarily pick the first one.
4992                return query.get(0);
4993            }
4994        }
4995        return null;
4996    }
4997
4998    @Override
4999    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5000            int userId) {
5001        if (!sUserManager.exists(userId)) return Collections.emptyList();
5002        ComponentName comp = intent.getComponent();
5003        if (comp == null) {
5004            if (intent.getSelector() != null) {
5005                intent = intent.getSelector();
5006                comp = intent.getComponent();
5007            }
5008        }
5009        if (comp != null) {
5010            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5011            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5012            if (si != null) {
5013                final ResolveInfo ri = new ResolveInfo();
5014                ri.serviceInfo = si;
5015                list.add(ri);
5016            }
5017            return list;
5018        }
5019
5020        // reader
5021        synchronized (mPackages) {
5022            String pkgName = intent.getPackage();
5023            if (pkgName == null) {
5024                return mServices.queryIntent(intent, resolvedType, flags, userId);
5025            }
5026            final PackageParser.Package pkg = mPackages.get(pkgName);
5027            if (pkg != null) {
5028                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5029                        userId);
5030            }
5031            return null;
5032        }
5033    }
5034
5035    @Override
5036    public List<ResolveInfo> queryIntentContentProviders(
5037            Intent intent, String resolvedType, int flags, int userId) {
5038        if (!sUserManager.exists(userId)) return Collections.emptyList();
5039        ComponentName comp = intent.getComponent();
5040        if (comp == null) {
5041            if (intent.getSelector() != null) {
5042                intent = intent.getSelector();
5043                comp = intent.getComponent();
5044            }
5045        }
5046        if (comp != null) {
5047            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5048            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5049            if (pi != null) {
5050                final ResolveInfo ri = new ResolveInfo();
5051                ri.providerInfo = pi;
5052                list.add(ri);
5053            }
5054            return list;
5055        }
5056
5057        // reader
5058        synchronized (mPackages) {
5059            String pkgName = intent.getPackage();
5060            if (pkgName == null) {
5061                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5062            }
5063            final PackageParser.Package pkg = mPackages.get(pkgName);
5064            if (pkg != null) {
5065                return mProviders.queryIntentForPackage(
5066                        intent, resolvedType, flags, pkg.providers, userId);
5067            }
5068            return null;
5069        }
5070    }
5071
5072    @Override
5073    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5074        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5075
5076        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5077
5078        // writer
5079        synchronized (mPackages) {
5080            ArrayList<PackageInfo> list;
5081            if (listUninstalled) {
5082                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5083                for (PackageSetting ps : mSettings.mPackages.values()) {
5084                    PackageInfo pi;
5085                    if (ps.pkg != null) {
5086                        pi = generatePackageInfo(ps.pkg, flags, userId);
5087                    } else {
5088                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5089                    }
5090                    if (pi != null) {
5091                        list.add(pi);
5092                    }
5093                }
5094            } else {
5095                list = new ArrayList<PackageInfo>(mPackages.size());
5096                for (PackageParser.Package p : mPackages.values()) {
5097                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5098                    if (pi != null) {
5099                        list.add(pi);
5100                    }
5101                }
5102            }
5103
5104            return new ParceledListSlice<PackageInfo>(list);
5105        }
5106    }
5107
5108    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5109            String[] permissions, boolean[] tmp, int flags, int userId) {
5110        int numMatch = 0;
5111        final PermissionsState permissionsState = ps.getPermissionsState();
5112        for (int i=0; i<permissions.length; i++) {
5113            final String permission = permissions[i];
5114            if (permissionsState.hasPermission(permission, userId)) {
5115                tmp[i] = true;
5116                numMatch++;
5117            } else {
5118                tmp[i] = false;
5119            }
5120        }
5121        if (numMatch == 0) {
5122            return;
5123        }
5124        PackageInfo pi;
5125        if (ps.pkg != null) {
5126            pi = generatePackageInfo(ps.pkg, flags, userId);
5127        } else {
5128            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5129        }
5130        // The above might return null in cases of uninstalled apps or install-state
5131        // skew across users/profiles.
5132        if (pi != null) {
5133            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5134                if (numMatch == permissions.length) {
5135                    pi.requestedPermissions = permissions;
5136                } else {
5137                    pi.requestedPermissions = new String[numMatch];
5138                    numMatch = 0;
5139                    for (int i=0; i<permissions.length; i++) {
5140                        if (tmp[i]) {
5141                            pi.requestedPermissions[numMatch] = permissions[i];
5142                            numMatch++;
5143                        }
5144                    }
5145                }
5146            }
5147            list.add(pi);
5148        }
5149    }
5150
5151    @Override
5152    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5153            String[] permissions, int flags, int userId) {
5154        if (!sUserManager.exists(userId)) return null;
5155        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5156
5157        // writer
5158        synchronized (mPackages) {
5159            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5160            boolean[] tmpBools = new boolean[permissions.length];
5161            if (listUninstalled) {
5162                for (PackageSetting ps : mSettings.mPackages.values()) {
5163                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5164                }
5165            } else {
5166                for (PackageParser.Package pkg : mPackages.values()) {
5167                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5168                    if (ps != null) {
5169                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5170                                userId);
5171                    }
5172                }
5173            }
5174
5175            return new ParceledListSlice<PackageInfo>(list);
5176        }
5177    }
5178
5179    @Override
5180    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5181        if (!sUserManager.exists(userId)) return null;
5182        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5183
5184        // writer
5185        synchronized (mPackages) {
5186            ArrayList<ApplicationInfo> list;
5187            if (listUninstalled) {
5188                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5189                for (PackageSetting ps : mSettings.mPackages.values()) {
5190                    ApplicationInfo ai;
5191                    if (ps.pkg != null) {
5192                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5193                                ps.readUserState(userId), userId);
5194                    } else {
5195                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5196                    }
5197                    if (ai != null) {
5198                        list.add(ai);
5199                    }
5200                }
5201            } else {
5202                list = new ArrayList<ApplicationInfo>(mPackages.size());
5203                for (PackageParser.Package p : mPackages.values()) {
5204                    if (p.mExtras != null) {
5205                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5206                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5207                        if (ai != null) {
5208                            list.add(ai);
5209                        }
5210                    }
5211                }
5212            }
5213
5214            return new ParceledListSlice<ApplicationInfo>(list);
5215        }
5216    }
5217
5218    public List<ApplicationInfo> getPersistentApplications(int flags) {
5219        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5220
5221        // reader
5222        synchronized (mPackages) {
5223            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5224            final int userId = UserHandle.getCallingUserId();
5225            while (i.hasNext()) {
5226                final PackageParser.Package p = i.next();
5227                if (p.applicationInfo != null
5228                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5229                        && (!mSafeMode || isSystemApp(p))) {
5230                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5231                    if (ps != null) {
5232                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5233                                ps.readUserState(userId), userId);
5234                        if (ai != null) {
5235                            finalList.add(ai);
5236                        }
5237                    }
5238                }
5239            }
5240        }
5241
5242        return finalList;
5243    }
5244
5245    @Override
5246    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5247        if (!sUserManager.exists(userId)) return null;
5248        // reader
5249        synchronized (mPackages) {
5250            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5251            PackageSetting ps = provider != null
5252                    ? mSettings.mPackages.get(provider.owner.packageName)
5253                    : null;
5254            return ps != null
5255                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5256                    && (!mSafeMode || (provider.info.applicationInfo.flags
5257                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5258                    ? PackageParser.generateProviderInfo(provider, flags,
5259                            ps.readUserState(userId), userId)
5260                    : null;
5261        }
5262    }
5263
5264    /**
5265     * @deprecated
5266     */
5267    @Deprecated
5268    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5269        // reader
5270        synchronized (mPackages) {
5271            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5272                    .entrySet().iterator();
5273            final int userId = UserHandle.getCallingUserId();
5274            while (i.hasNext()) {
5275                Map.Entry<String, PackageParser.Provider> entry = i.next();
5276                PackageParser.Provider p = entry.getValue();
5277                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5278
5279                if (ps != null && p.syncable
5280                        && (!mSafeMode || (p.info.applicationInfo.flags
5281                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5282                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5283                            ps.readUserState(userId), userId);
5284                    if (info != null) {
5285                        outNames.add(entry.getKey());
5286                        outInfo.add(info);
5287                    }
5288                }
5289            }
5290        }
5291    }
5292
5293    @Override
5294    public List<ProviderInfo> queryContentProviders(String processName,
5295            int uid, int flags) {
5296        ArrayList<ProviderInfo> finalList = null;
5297        // reader
5298        synchronized (mPackages) {
5299            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5300            final int userId = processName != null ?
5301                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5302            while (i.hasNext()) {
5303                final PackageParser.Provider p = i.next();
5304                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5305                if (ps != null && p.info.authority != null
5306                        && (processName == null
5307                                || (p.info.processName.equals(processName)
5308                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5309                        && mSettings.isEnabledLPr(p.info, flags, userId)
5310                        && (!mSafeMode
5311                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5312                    if (finalList == null) {
5313                        finalList = new ArrayList<ProviderInfo>(3);
5314                    }
5315                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5316                            ps.readUserState(userId), userId);
5317                    if (info != null) {
5318                        finalList.add(info);
5319                    }
5320                }
5321            }
5322        }
5323
5324        if (finalList != null) {
5325            Collections.sort(finalList, mProviderInitOrderSorter);
5326        }
5327
5328        return finalList;
5329    }
5330
5331    @Override
5332    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5333            int flags) {
5334        // reader
5335        synchronized (mPackages) {
5336            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5337            return PackageParser.generateInstrumentationInfo(i, flags);
5338        }
5339    }
5340
5341    @Override
5342    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5343            int flags) {
5344        ArrayList<InstrumentationInfo> finalList =
5345            new ArrayList<InstrumentationInfo>();
5346
5347        // reader
5348        synchronized (mPackages) {
5349            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5350            while (i.hasNext()) {
5351                final PackageParser.Instrumentation p = i.next();
5352                if (targetPackage == null
5353                        || targetPackage.equals(p.info.targetPackage)) {
5354                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5355                            flags);
5356                    if (ii != null) {
5357                        finalList.add(ii);
5358                    }
5359                }
5360            }
5361        }
5362
5363        return finalList;
5364    }
5365
5366    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5367        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5368        if (overlays == null) {
5369            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5370            return;
5371        }
5372        for (PackageParser.Package opkg : overlays.values()) {
5373            // Not much to do if idmap fails: we already logged the error
5374            // and we certainly don't want to abort installation of pkg simply
5375            // because an overlay didn't fit properly. For these reasons,
5376            // ignore the return value of createIdmapForPackagePairLI.
5377            createIdmapForPackagePairLI(pkg, opkg);
5378        }
5379    }
5380
5381    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5382            PackageParser.Package opkg) {
5383        if (!opkg.mTrustedOverlay) {
5384            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5385                    opkg.baseCodePath + ": overlay not trusted");
5386            return false;
5387        }
5388        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5389        if (overlaySet == null) {
5390            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5391                    opkg.baseCodePath + " but target package has no known overlays");
5392            return false;
5393        }
5394        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5395        // TODO: generate idmap for split APKs
5396        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5397            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5398                    + opkg.baseCodePath);
5399            return false;
5400        }
5401        PackageParser.Package[] overlayArray =
5402            overlaySet.values().toArray(new PackageParser.Package[0]);
5403        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5404            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5405                return p1.mOverlayPriority - p2.mOverlayPriority;
5406            }
5407        };
5408        Arrays.sort(overlayArray, cmp);
5409
5410        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5411        int i = 0;
5412        for (PackageParser.Package p : overlayArray) {
5413            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5414        }
5415        return true;
5416    }
5417
5418    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5419        final File[] files = dir.listFiles();
5420        if (ArrayUtils.isEmpty(files)) {
5421            Log.d(TAG, "No files in app dir " + dir);
5422            return;
5423        }
5424
5425        if (DEBUG_PACKAGE_SCANNING) {
5426            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5427                    + " flags=0x" + Integer.toHexString(parseFlags));
5428        }
5429
5430        for (File file : files) {
5431            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5432                    && !PackageInstallerService.isStageName(file.getName());
5433            if (!isPackage) {
5434                // Ignore entries which are not packages
5435                continue;
5436            }
5437            try {
5438                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5439                        scanFlags, currentTime, null);
5440            } catch (PackageManagerException e) {
5441                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5442
5443                // Delete invalid userdata apps
5444                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5445                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5446                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5447                    if (file.isDirectory()) {
5448                        mInstaller.rmPackageDir(file.getAbsolutePath());
5449                    } else {
5450                        file.delete();
5451                    }
5452                }
5453            }
5454        }
5455    }
5456
5457    private static File getSettingsProblemFile() {
5458        File dataDir = Environment.getDataDirectory();
5459        File systemDir = new File(dataDir, "system");
5460        File fname = new File(systemDir, "uiderrors.txt");
5461        return fname;
5462    }
5463
5464    static void reportSettingsProblem(int priority, String msg) {
5465        logCriticalInfo(priority, msg);
5466    }
5467
5468    static void logCriticalInfo(int priority, String msg) {
5469        Slog.println(priority, TAG, msg);
5470        EventLogTags.writePmCriticalInfo(msg);
5471        try {
5472            File fname = getSettingsProblemFile();
5473            FileOutputStream out = new FileOutputStream(fname, true);
5474            PrintWriter pw = new FastPrintWriter(out);
5475            SimpleDateFormat formatter = new SimpleDateFormat();
5476            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5477            pw.println(dateString + ": " + msg);
5478            pw.close();
5479            FileUtils.setPermissions(
5480                    fname.toString(),
5481                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5482                    -1, -1);
5483        } catch (java.io.IOException e) {
5484        }
5485    }
5486
5487    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5488            PackageParser.Package pkg, File srcFile, int parseFlags)
5489            throws PackageManagerException {
5490        if (ps != null
5491                && ps.codePath.equals(srcFile)
5492                && ps.timeStamp == srcFile.lastModified()
5493                && !isCompatSignatureUpdateNeeded(pkg)
5494                && !isRecoverSignatureUpdateNeeded(pkg)) {
5495            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5496            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5497            ArraySet<PublicKey> signingKs;
5498            synchronized (mPackages) {
5499                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5500            }
5501            if (ps.signatures.mSignatures != null
5502                    && ps.signatures.mSignatures.length != 0
5503                    && signingKs != null) {
5504                // Optimization: reuse the existing cached certificates
5505                // if the package appears to be unchanged.
5506                pkg.mSignatures = ps.signatures.mSignatures;
5507                pkg.mSigningKeys = signingKs;
5508                return;
5509            }
5510
5511            Slog.w(TAG, "PackageSetting for " + ps.name
5512                    + " is missing signatures.  Collecting certs again to recover them.");
5513        } else {
5514            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5515        }
5516
5517        try {
5518            pp.collectCertificates(pkg, parseFlags);
5519            pp.collectManifestDigest(pkg);
5520        } catch (PackageParserException e) {
5521            throw PackageManagerException.from(e);
5522        }
5523    }
5524
5525    /*
5526     *  Scan a package and return the newly parsed package.
5527     *  Returns null in case of errors and the error code is stored in mLastScanError
5528     */
5529    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5530            long currentTime, UserHandle user) throws PackageManagerException {
5531        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5532        parseFlags |= mDefParseFlags;
5533        PackageParser pp = new PackageParser();
5534        pp.setSeparateProcesses(mSeparateProcesses);
5535        pp.setOnlyCoreApps(mOnlyCore);
5536        pp.setDisplayMetrics(mMetrics);
5537
5538        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5539            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5540        }
5541
5542        final PackageParser.Package pkg;
5543        try {
5544            pkg = pp.parsePackage(scanFile, parseFlags);
5545        } catch (PackageParserException e) {
5546            throw PackageManagerException.from(e);
5547        }
5548
5549        PackageSetting ps = null;
5550        PackageSetting updatedPkg;
5551        // reader
5552        synchronized (mPackages) {
5553            // Look to see if we already know about this package.
5554            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5555            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5556                // This package has been renamed to its original name.  Let's
5557                // use that.
5558                ps = mSettings.peekPackageLPr(oldName);
5559            }
5560            // If there was no original package, see one for the real package name.
5561            if (ps == null) {
5562                ps = mSettings.peekPackageLPr(pkg.packageName);
5563            }
5564            // Check to see if this package could be hiding/updating a system
5565            // package.  Must look for it either under the original or real
5566            // package name depending on our state.
5567            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5568            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5569        }
5570        boolean updatedPkgBetter = false;
5571        // First check if this is a system package that may involve an update
5572        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5573            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5574            // it needs to drop FLAG_PRIVILEGED.
5575            if (locationIsPrivileged(scanFile)) {
5576                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5577            } else {
5578                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5579            }
5580
5581            if (ps != null && !ps.codePath.equals(scanFile)) {
5582                // The path has changed from what was last scanned...  check the
5583                // version of the new path against what we have stored to determine
5584                // what to do.
5585                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5586                if (pkg.mVersionCode <= ps.versionCode) {
5587                    // The system package has been updated and the code path does not match
5588                    // Ignore entry. Skip it.
5589                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5590                            + " ignored: updated version " + ps.versionCode
5591                            + " better than this " + pkg.mVersionCode);
5592                    if (!updatedPkg.codePath.equals(scanFile)) {
5593                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5594                                + ps.name + " changing from " + updatedPkg.codePathString
5595                                + " to " + scanFile);
5596                        updatedPkg.codePath = scanFile;
5597                        updatedPkg.codePathString = scanFile.toString();
5598                        updatedPkg.resourcePath = scanFile;
5599                        updatedPkg.resourcePathString = scanFile.toString();
5600                    }
5601                    updatedPkg.pkg = pkg;
5602                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5603                } else {
5604                    // The current app on the system partition is better than
5605                    // what we have updated to on the data partition; switch
5606                    // back to the system partition version.
5607                    // At this point, its safely assumed that package installation for
5608                    // apps in system partition will go through. If not there won't be a working
5609                    // version of the app
5610                    // writer
5611                    synchronized (mPackages) {
5612                        // Just remove the loaded entries from package lists.
5613                        mPackages.remove(ps.name);
5614                    }
5615
5616                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5617                            + " reverting from " + ps.codePathString
5618                            + ": new version " + pkg.mVersionCode
5619                            + " better than installed " + ps.versionCode);
5620
5621                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5622                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5623                    synchronized (mInstallLock) {
5624                        args.cleanUpResourcesLI();
5625                    }
5626                    synchronized (mPackages) {
5627                        mSettings.enableSystemPackageLPw(ps.name);
5628                    }
5629                    updatedPkgBetter = true;
5630                }
5631            }
5632        }
5633
5634        if (updatedPkg != null) {
5635            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5636            // initially
5637            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5638
5639            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5640            // flag set initially
5641            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5642                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5643            }
5644        }
5645
5646        // Verify certificates against what was last scanned
5647        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5648
5649        /*
5650         * A new system app appeared, but we already had a non-system one of the
5651         * same name installed earlier.
5652         */
5653        boolean shouldHideSystemApp = false;
5654        if (updatedPkg == null && ps != null
5655                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5656            /*
5657             * Check to make sure the signatures match first. If they don't,
5658             * wipe the installed application and its data.
5659             */
5660            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5661                    != PackageManager.SIGNATURE_MATCH) {
5662                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5663                        + " signatures don't match existing userdata copy; removing");
5664                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5665                ps = null;
5666            } else {
5667                /*
5668                 * If the newly-added system app is an older version than the
5669                 * already installed version, hide it. It will be scanned later
5670                 * and re-added like an update.
5671                 */
5672                if (pkg.mVersionCode <= ps.versionCode) {
5673                    shouldHideSystemApp = true;
5674                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5675                            + " but new version " + pkg.mVersionCode + " better than installed "
5676                            + ps.versionCode + "; hiding system");
5677                } else {
5678                    /*
5679                     * The newly found system app is a newer version that the
5680                     * one previously installed. Simply remove the
5681                     * already-installed application and replace it with our own
5682                     * while keeping the application data.
5683                     */
5684                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5685                            + " reverting from " + ps.codePathString + ": new version "
5686                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5687                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5688                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5689                    synchronized (mInstallLock) {
5690                        args.cleanUpResourcesLI();
5691                    }
5692                }
5693            }
5694        }
5695
5696        // The apk is forward locked (not public) if its code and resources
5697        // are kept in different files. (except for app in either system or
5698        // vendor path).
5699        // TODO grab this value from PackageSettings
5700        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5701            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5702                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5703            }
5704        }
5705
5706        // TODO: extend to support forward-locked splits
5707        String resourcePath = null;
5708        String baseResourcePath = null;
5709        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5710            if (ps != null && ps.resourcePathString != null) {
5711                resourcePath = ps.resourcePathString;
5712                baseResourcePath = ps.resourcePathString;
5713            } else {
5714                // Should not happen at all. Just log an error.
5715                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5716            }
5717        } else {
5718            resourcePath = pkg.codePath;
5719            baseResourcePath = pkg.baseCodePath;
5720        }
5721
5722        // Set application objects path explicitly.
5723        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5724        pkg.applicationInfo.setCodePath(pkg.codePath);
5725        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5726        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5727        pkg.applicationInfo.setResourcePath(resourcePath);
5728        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5729        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5730
5731        // Note that we invoke the following method only if we are about to unpack an application
5732        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5733                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5734
5735        /*
5736         * If the system app should be overridden by a previously installed
5737         * data, hide the system app now and let the /data/app scan pick it up
5738         * again.
5739         */
5740        if (shouldHideSystemApp) {
5741            synchronized (mPackages) {
5742                /*
5743                 * We have to grant systems permissions before we hide, because
5744                 * grantPermissions will assume the package update is trying to
5745                 * expand its permissions.
5746                 */
5747                grantPermissionsLPw(pkg, true, pkg.packageName);
5748                mSettings.disableSystemPackageLPw(pkg.packageName);
5749            }
5750        }
5751
5752        return scannedPkg;
5753    }
5754
5755    private static String fixProcessName(String defProcessName,
5756            String processName, int uid) {
5757        if (processName == null) {
5758            return defProcessName;
5759        }
5760        return processName;
5761    }
5762
5763    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5764            throws PackageManagerException {
5765        if (pkgSetting.signatures.mSignatures != null) {
5766            // Already existing package. Make sure signatures match
5767            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5768                    == PackageManager.SIGNATURE_MATCH;
5769            if (!match) {
5770                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5771                        == PackageManager.SIGNATURE_MATCH;
5772            }
5773            if (!match) {
5774                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5775                        == PackageManager.SIGNATURE_MATCH;
5776            }
5777            if (!match) {
5778                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5779                        + pkg.packageName + " signatures do not match the "
5780                        + "previously installed version; ignoring!");
5781            }
5782        }
5783
5784        // Check for shared user signatures
5785        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5786            // Already existing package. Make sure signatures match
5787            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5788                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5789            if (!match) {
5790                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5791                        == PackageManager.SIGNATURE_MATCH;
5792            }
5793            if (!match) {
5794                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5795                        == PackageManager.SIGNATURE_MATCH;
5796            }
5797            if (!match) {
5798                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5799                        "Package " + pkg.packageName
5800                        + " has no signatures that match those in shared user "
5801                        + pkgSetting.sharedUser.name + "; ignoring!");
5802            }
5803        }
5804    }
5805
5806    /**
5807     * Enforces that only the system UID or root's UID can call a method exposed
5808     * via Binder.
5809     *
5810     * @param message used as message if SecurityException is thrown
5811     * @throws SecurityException if the caller is not system or root
5812     */
5813    private static final void enforceSystemOrRoot(String message) {
5814        final int uid = Binder.getCallingUid();
5815        if (uid != Process.SYSTEM_UID && uid != 0) {
5816            throw new SecurityException(message);
5817        }
5818    }
5819
5820    @Override
5821    public void performBootDexOpt() {
5822        enforceSystemOrRoot("Only the system can request dexopt be performed");
5823
5824        // Before everything else, see whether we need to fstrim.
5825        try {
5826            IMountService ms = PackageHelper.getMountService();
5827            if (ms != null) {
5828                final boolean isUpgrade = isUpgrade();
5829                boolean doTrim = isUpgrade;
5830                if (doTrim) {
5831                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5832                } else {
5833                    final long interval = android.provider.Settings.Global.getLong(
5834                            mContext.getContentResolver(),
5835                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5836                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5837                    if (interval > 0) {
5838                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5839                        if (timeSinceLast > interval) {
5840                            doTrim = true;
5841                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5842                                    + "; running immediately");
5843                        }
5844                    }
5845                }
5846                if (doTrim) {
5847                    if (!isFirstBoot()) {
5848                        try {
5849                            ActivityManagerNative.getDefault().showBootMessage(
5850                                    mContext.getResources().getString(
5851                                            R.string.android_upgrading_fstrim), true);
5852                        } catch (RemoteException e) {
5853                        }
5854                    }
5855                    ms.runMaintenance();
5856                }
5857            } else {
5858                Slog.e(TAG, "Mount service unavailable!");
5859            }
5860        } catch (RemoteException e) {
5861            // Can't happen; MountService is local
5862        }
5863
5864        final ArraySet<PackageParser.Package> pkgs;
5865        synchronized (mPackages) {
5866            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5867        }
5868
5869        if (pkgs != null) {
5870            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5871            // in case the device runs out of space.
5872            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5873            // Give priority to core apps.
5874            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5875                PackageParser.Package pkg = it.next();
5876                if (pkg.coreApp) {
5877                    if (DEBUG_DEXOPT) {
5878                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5879                    }
5880                    sortedPkgs.add(pkg);
5881                    it.remove();
5882                }
5883            }
5884            // Give priority to system apps that listen for pre boot complete.
5885            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5886            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5887            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5888                PackageParser.Package pkg = it.next();
5889                if (pkgNames.contains(pkg.packageName)) {
5890                    if (DEBUG_DEXOPT) {
5891                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5892                    }
5893                    sortedPkgs.add(pkg);
5894                    it.remove();
5895                }
5896            }
5897            // Give priority to system apps.
5898            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5899                PackageParser.Package pkg = it.next();
5900                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5901                    if (DEBUG_DEXOPT) {
5902                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5903                    }
5904                    sortedPkgs.add(pkg);
5905                    it.remove();
5906                }
5907            }
5908            // Give priority to updated system apps.
5909            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5910                PackageParser.Package pkg = it.next();
5911                if (pkg.isUpdatedSystemApp()) {
5912                    if (DEBUG_DEXOPT) {
5913                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5914                    }
5915                    sortedPkgs.add(pkg);
5916                    it.remove();
5917                }
5918            }
5919            // Give priority to apps that listen for boot complete.
5920            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5921            pkgNames = getPackageNamesForIntent(intent);
5922            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5923                PackageParser.Package pkg = it.next();
5924                if (pkgNames.contains(pkg.packageName)) {
5925                    if (DEBUG_DEXOPT) {
5926                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5927                    }
5928                    sortedPkgs.add(pkg);
5929                    it.remove();
5930                }
5931            }
5932            // Filter out packages that aren't recently used.
5933            filterRecentlyUsedApps(pkgs);
5934            // Add all remaining apps.
5935            for (PackageParser.Package pkg : pkgs) {
5936                if (DEBUG_DEXOPT) {
5937                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5938                }
5939                sortedPkgs.add(pkg);
5940            }
5941
5942            // If we want to be lazy, filter everything that wasn't recently used.
5943            if (mLazyDexOpt) {
5944                filterRecentlyUsedApps(sortedPkgs);
5945            }
5946
5947            int i = 0;
5948            int total = sortedPkgs.size();
5949            File dataDir = Environment.getDataDirectory();
5950            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5951            if (lowThreshold == 0) {
5952                throw new IllegalStateException("Invalid low memory threshold");
5953            }
5954            for (PackageParser.Package pkg : sortedPkgs) {
5955                long usableSpace = dataDir.getUsableSpace();
5956                if (usableSpace < lowThreshold) {
5957                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5958                    break;
5959                }
5960                performBootDexOpt(pkg, ++i, total);
5961            }
5962        }
5963    }
5964
5965    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5966        // Filter out packages that aren't recently used.
5967        //
5968        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5969        // should do a full dexopt.
5970        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5971            int total = pkgs.size();
5972            int skipped = 0;
5973            long now = System.currentTimeMillis();
5974            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5975                PackageParser.Package pkg = i.next();
5976                long then = pkg.mLastPackageUsageTimeInMills;
5977                if (then + mDexOptLRUThresholdInMills < now) {
5978                    if (DEBUG_DEXOPT) {
5979                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5980                              ((then == 0) ? "never" : new Date(then)));
5981                    }
5982                    i.remove();
5983                    skipped++;
5984                }
5985            }
5986            if (DEBUG_DEXOPT) {
5987                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5988            }
5989        }
5990    }
5991
5992    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5993        List<ResolveInfo> ris = null;
5994        try {
5995            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5996                    intent, null, 0, UserHandle.USER_OWNER);
5997        } catch (RemoteException e) {
5998        }
5999        ArraySet<String> pkgNames = new ArraySet<String>();
6000        if (ris != null) {
6001            for (ResolveInfo ri : ris) {
6002                pkgNames.add(ri.activityInfo.packageName);
6003            }
6004        }
6005        return pkgNames;
6006    }
6007
6008    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6009        if (DEBUG_DEXOPT) {
6010            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6011        }
6012        if (!isFirstBoot()) {
6013            try {
6014                ActivityManagerNative.getDefault().showBootMessage(
6015                        mContext.getResources().getString(R.string.android_upgrading_apk,
6016                                curr, total), true);
6017            } catch (RemoteException e) {
6018            }
6019        }
6020        PackageParser.Package p = pkg;
6021        synchronized (mInstallLock) {
6022            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6023                    false /* force dex */, false /* defer */, true /* include dependencies */);
6024        }
6025    }
6026
6027    @Override
6028    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6029        return performDexOpt(packageName, instructionSet, false);
6030    }
6031
6032    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6033        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6034        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6035        if (!dexopt && !updateUsage) {
6036            // We aren't going to dexopt or update usage, so bail early.
6037            return false;
6038        }
6039        PackageParser.Package p;
6040        final String targetInstructionSet;
6041        synchronized (mPackages) {
6042            p = mPackages.get(packageName);
6043            if (p == null) {
6044                return false;
6045            }
6046            if (updateUsage) {
6047                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6048            }
6049            mPackageUsage.write(false);
6050            if (!dexopt) {
6051                // We aren't going to dexopt, so bail early.
6052                return false;
6053            }
6054
6055            targetInstructionSet = instructionSet != null ? instructionSet :
6056                    getPrimaryInstructionSet(p.applicationInfo);
6057            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6058                return false;
6059            }
6060        }
6061
6062        synchronized (mInstallLock) {
6063            final String[] instructionSets = new String[] { targetInstructionSet };
6064            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6065                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6066            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6067        }
6068    }
6069
6070    public ArraySet<String> getPackagesThatNeedDexOpt() {
6071        ArraySet<String> pkgs = null;
6072        synchronized (mPackages) {
6073            for (PackageParser.Package p : mPackages.values()) {
6074                if (DEBUG_DEXOPT) {
6075                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6076                }
6077                if (!p.mDexOptPerformed.isEmpty()) {
6078                    continue;
6079                }
6080                if (pkgs == null) {
6081                    pkgs = new ArraySet<String>();
6082                }
6083                pkgs.add(p.packageName);
6084            }
6085        }
6086        return pkgs;
6087    }
6088
6089    public void shutdown() {
6090        mPackageUsage.write(true);
6091    }
6092
6093    @Override
6094    public void forceDexOpt(String packageName) {
6095        enforceSystemOrRoot("forceDexOpt");
6096
6097        PackageParser.Package pkg;
6098        synchronized (mPackages) {
6099            pkg = mPackages.get(packageName);
6100            if (pkg == null) {
6101                throw new IllegalArgumentException("Missing package: " + packageName);
6102            }
6103        }
6104
6105        synchronized (mInstallLock) {
6106            final String[] instructionSets = new String[] {
6107                    getPrimaryInstructionSet(pkg.applicationInfo) };
6108            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6109                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6110            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6111                throw new IllegalStateException("Failed to dexopt: " + res);
6112            }
6113        }
6114    }
6115
6116    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6117        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6118            Slog.w(TAG, "Unable to update from " + oldPkg.name
6119                    + " to " + newPkg.packageName
6120                    + ": old package not in system partition");
6121            return false;
6122        } else if (mPackages.get(oldPkg.name) != null) {
6123            Slog.w(TAG, "Unable to update from " + oldPkg.name
6124                    + " to " + newPkg.packageName
6125                    + ": old package still exists");
6126            return false;
6127        }
6128        return true;
6129    }
6130
6131    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6132        int[] users = sUserManager.getUserIds();
6133        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6134        if (res < 0) {
6135            return res;
6136        }
6137        for (int user : users) {
6138            if (user != 0) {
6139                res = mInstaller.createUserData(volumeUuid, packageName,
6140                        UserHandle.getUid(user, uid), user, seinfo);
6141                if (res < 0) {
6142                    return res;
6143                }
6144            }
6145        }
6146        return res;
6147    }
6148
6149    private int removeDataDirsLI(String volumeUuid, String packageName) {
6150        int[] users = sUserManager.getUserIds();
6151        int res = 0;
6152        for (int user : users) {
6153            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6154            if (resInner < 0) {
6155                res = resInner;
6156            }
6157        }
6158
6159        return res;
6160    }
6161
6162    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6163        int[] users = sUserManager.getUserIds();
6164        int res = 0;
6165        for (int user : users) {
6166            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6167            if (resInner < 0) {
6168                res = resInner;
6169            }
6170        }
6171        return res;
6172    }
6173
6174    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6175            PackageParser.Package changingLib) {
6176        if (file.path != null) {
6177            usesLibraryFiles.add(file.path);
6178            return;
6179        }
6180        PackageParser.Package p = mPackages.get(file.apk);
6181        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6182            // If we are doing this while in the middle of updating a library apk,
6183            // then we need to make sure to use that new apk for determining the
6184            // dependencies here.  (We haven't yet finished committing the new apk
6185            // to the package manager state.)
6186            if (p == null || p.packageName.equals(changingLib.packageName)) {
6187                p = changingLib;
6188            }
6189        }
6190        if (p != null) {
6191            usesLibraryFiles.addAll(p.getAllCodePaths());
6192        }
6193    }
6194
6195    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6196            PackageParser.Package changingLib) throws PackageManagerException {
6197        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6198            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6199            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6200            for (int i=0; i<N; i++) {
6201                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6202                if (file == null) {
6203                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6204                            "Package " + pkg.packageName + " requires unavailable shared library "
6205                            + pkg.usesLibraries.get(i) + "; failing!");
6206                }
6207                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6208            }
6209            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6210            for (int i=0; i<N; i++) {
6211                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6212                if (file == null) {
6213                    Slog.w(TAG, "Package " + pkg.packageName
6214                            + " desires unavailable shared library "
6215                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6216                } else {
6217                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6218                }
6219            }
6220            N = usesLibraryFiles.size();
6221            if (N > 0) {
6222                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6223            } else {
6224                pkg.usesLibraryFiles = null;
6225            }
6226        }
6227    }
6228
6229    private static boolean hasString(List<String> list, List<String> which) {
6230        if (list == null) {
6231            return false;
6232        }
6233        for (int i=list.size()-1; i>=0; i--) {
6234            for (int j=which.size()-1; j>=0; j--) {
6235                if (which.get(j).equals(list.get(i))) {
6236                    return true;
6237                }
6238            }
6239        }
6240        return false;
6241    }
6242
6243    private void updateAllSharedLibrariesLPw() {
6244        for (PackageParser.Package pkg : mPackages.values()) {
6245            try {
6246                updateSharedLibrariesLPw(pkg, null);
6247            } catch (PackageManagerException e) {
6248                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6249            }
6250        }
6251    }
6252
6253    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6254            PackageParser.Package changingPkg) {
6255        ArrayList<PackageParser.Package> res = null;
6256        for (PackageParser.Package pkg : mPackages.values()) {
6257            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6258                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6259                if (res == null) {
6260                    res = new ArrayList<PackageParser.Package>();
6261                }
6262                res.add(pkg);
6263                try {
6264                    updateSharedLibrariesLPw(pkg, changingPkg);
6265                } catch (PackageManagerException e) {
6266                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6267                }
6268            }
6269        }
6270        return res;
6271    }
6272
6273    /**
6274     * Derive the value of the {@code cpuAbiOverride} based on the provided
6275     * value and an optional stored value from the package settings.
6276     */
6277    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6278        String cpuAbiOverride = null;
6279
6280        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6281            cpuAbiOverride = null;
6282        } else if (abiOverride != null) {
6283            cpuAbiOverride = abiOverride;
6284        } else if (settings != null) {
6285            cpuAbiOverride = settings.cpuAbiOverrideString;
6286        }
6287
6288        return cpuAbiOverride;
6289    }
6290
6291    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6292            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6293        boolean success = false;
6294        try {
6295            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6296                    currentTime, user);
6297            success = true;
6298            return res;
6299        } finally {
6300            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6301                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6302            }
6303        }
6304    }
6305
6306    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6307            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6308        final File scanFile = new File(pkg.codePath);
6309        if (pkg.applicationInfo.getCodePath() == null ||
6310                pkg.applicationInfo.getResourcePath() == null) {
6311            // Bail out. The resource and code paths haven't been set.
6312            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6313                    "Code and resource paths haven't been set correctly");
6314        }
6315
6316        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6317            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6318        } else {
6319            // Only allow system apps to be flagged as core apps.
6320            pkg.coreApp = false;
6321        }
6322
6323        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6324            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6325        }
6326
6327        if (mCustomResolverComponentName != null &&
6328                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6329            setUpCustomResolverActivity(pkg);
6330        }
6331
6332        if (pkg.packageName.equals("android")) {
6333            synchronized (mPackages) {
6334                if (mAndroidApplication != null) {
6335                    Slog.w(TAG, "*************************************************");
6336                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6337                    Slog.w(TAG, " file=" + scanFile);
6338                    Slog.w(TAG, "*************************************************");
6339                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6340                            "Core android package being redefined.  Skipping.");
6341                }
6342
6343                // Set up information for our fall-back user intent resolution activity.
6344                mPlatformPackage = pkg;
6345                pkg.mVersionCode = mSdkVersion;
6346                mAndroidApplication = pkg.applicationInfo;
6347
6348                if (!mResolverReplaced) {
6349                    mResolveActivity.applicationInfo = mAndroidApplication;
6350                    mResolveActivity.name = ResolverActivity.class.getName();
6351                    mResolveActivity.packageName = mAndroidApplication.packageName;
6352                    mResolveActivity.processName = "system:ui";
6353                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6354                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6355                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6356                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6357                    mResolveActivity.exported = true;
6358                    mResolveActivity.enabled = true;
6359                    mResolveInfo.activityInfo = mResolveActivity;
6360                    mResolveInfo.priority = 0;
6361                    mResolveInfo.preferredOrder = 0;
6362                    mResolveInfo.match = 0;
6363                    mResolveComponentName = new ComponentName(
6364                            mAndroidApplication.packageName, mResolveActivity.name);
6365                }
6366            }
6367        }
6368
6369        if (DEBUG_PACKAGE_SCANNING) {
6370            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6371                Log.d(TAG, "Scanning package " + pkg.packageName);
6372        }
6373
6374        if (mPackages.containsKey(pkg.packageName)
6375                || mSharedLibraries.containsKey(pkg.packageName)) {
6376            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6377                    "Application package " + pkg.packageName
6378                    + " already installed.  Skipping duplicate.");
6379        }
6380
6381        // If we're only installing presumed-existing packages, require that the
6382        // scanned APK is both already known and at the path previously established
6383        // for it.  Previously unknown packages we pick up normally, but if we have an
6384        // a priori expectation about this package's install presence, enforce it.
6385        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6386            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6387            if (known != null) {
6388                if (DEBUG_PACKAGE_SCANNING) {
6389                    Log.d(TAG, "Examining " + pkg.codePath
6390                            + " and requiring known paths " + known.codePathString
6391                            + " & " + known.resourcePathString);
6392                }
6393                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6394                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6395                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6396                            "Application package " + pkg.packageName
6397                            + " found at " + pkg.applicationInfo.getCodePath()
6398                            + " but expected at " + known.codePathString + "; ignoring.");
6399                }
6400            }
6401        }
6402
6403        // Initialize package source and resource directories
6404        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6405        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6406
6407        SharedUserSetting suid = null;
6408        PackageSetting pkgSetting = null;
6409
6410        if (!isSystemApp(pkg)) {
6411            // Only system apps can use these features.
6412            pkg.mOriginalPackages = null;
6413            pkg.mRealPackage = null;
6414            pkg.mAdoptPermissions = null;
6415        }
6416
6417        // writer
6418        synchronized (mPackages) {
6419            if (pkg.mSharedUserId != null) {
6420                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6421                if (suid == null) {
6422                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6423                            "Creating application package " + pkg.packageName
6424                            + " for shared user failed");
6425                }
6426                if (DEBUG_PACKAGE_SCANNING) {
6427                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6428                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6429                                + "): packages=" + suid.packages);
6430                }
6431            }
6432
6433            // Check if we are renaming from an original package name.
6434            PackageSetting origPackage = null;
6435            String realName = null;
6436            if (pkg.mOriginalPackages != null) {
6437                // This package may need to be renamed to a previously
6438                // installed name.  Let's check on that...
6439                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6440                if (pkg.mOriginalPackages.contains(renamed)) {
6441                    // This package had originally been installed as the
6442                    // original name, and we have already taken care of
6443                    // transitioning to the new one.  Just update the new
6444                    // one to continue using the old name.
6445                    realName = pkg.mRealPackage;
6446                    if (!pkg.packageName.equals(renamed)) {
6447                        // Callers into this function may have already taken
6448                        // care of renaming the package; only do it here if
6449                        // it is not already done.
6450                        pkg.setPackageName(renamed);
6451                    }
6452
6453                } else {
6454                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6455                        if ((origPackage = mSettings.peekPackageLPr(
6456                                pkg.mOriginalPackages.get(i))) != null) {
6457                            // We do have the package already installed under its
6458                            // original name...  should we use it?
6459                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6460                                // New package is not compatible with original.
6461                                origPackage = null;
6462                                continue;
6463                            } else if (origPackage.sharedUser != null) {
6464                                // Make sure uid is compatible between packages.
6465                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6466                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6467                                            + " to " + pkg.packageName + ": old uid "
6468                                            + origPackage.sharedUser.name
6469                                            + " differs from " + pkg.mSharedUserId);
6470                                    origPackage = null;
6471                                    continue;
6472                                }
6473                            } else {
6474                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6475                                        + pkg.packageName + " to old name " + origPackage.name);
6476                            }
6477                            break;
6478                        }
6479                    }
6480                }
6481            }
6482
6483            if (mTransferedPackages.contains(pkg.packageName)) {
6484                Slog.w(TAG, "Package " + pkg.packageName
6485                        + " was transferred to another, but its .apk remains");
6486            }
6487
6488            // Just create the setting, don't add it yet. For already existing packages
6489            // the PkgSetting exists already and doesn't have to be created.
6490            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6491                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6492                    pkg.applicationInfo.primaryCpuAbi,
6493                    pkg.applicationInfo.secondaryCpuAbi,
6494                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6495                    user, false);
6496            if (pkgSetting == null) {
6497                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6498                        "Creating application package " + pkg.packageName + " failed");
6499            }
6500
6501            if (pkgSetting.origPackage != null) {
6502                // If we are first transitioning from an original package,
6503                // fix up the new package's name now.  We need to do this after
6504                // looking up the package under its new name, so getPackageLP
6505                // can take care of fiddling things correctly.
6506                pkg.setPackageName(origPackage.name);
6507
6508                // File a report about this.
6509                String msg = "New package " + pkgSetting.realName
6510                        + " renamed to replace old package " + pkgSetting.name;
6511                reportSettingsProblem(Log.WARN, msg);
6512
6513                // Make a note of it.
6514                mTransferedPackages.add(origPackage.name);
6515
6516                // No longer need to retain this.
6517                pkgSetting.origPackage = null;
6518            }
6519
6520            if (realName != null) {
6521                // Make a note of it.
6522                mTransferedPackages.add(pkg.packageName);
6523            }
6524
6525            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6526                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6527            }
6528
6529            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6530                // Check all shared libraries and map to their actual file path.
6531                // We only do this here for apps not on a system dir, because those
6532                // are the only ones that can fail an install due to this.  We
6533                // will take care of the system apps by updating all of their
6534                // library paths after the scan is done.
6535                updateSharedLibrariesLPw(pkg, null);
6536            }
6537
6538            if (mFoundPolicyFile) {
6539                SELinuxMMAC.assignSeinfoValue(pkg);
6540            }
6541
6542            pkg.applicationInfo.uid = pkgSetting.appId;
6543            pkg.mExtras = pkgSetting;
6544            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6545                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6546                    // We just determined the app is signed correctly, so bring
6547                    // over the latest parsed certs.
6548                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6549                } else {
6550                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6551                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6552                                "Package " + pkg.packageName + " upgrade keys do not match the "
6553                                + "previously installed version");
6554                    } else {
6555                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6556                        String msg = "System package " + pkg.packageName
6557                            + " signature changed; retaining data.";
6558                        reportSettingsProblem(Log.WARN, msg);
6559                    }
6560                }
6561            } else {
6562                try {
6563                    verifySignaturesLP(pkgSetting, pkg);
6564                    // We just determined the app is signed correctly, so bring
6565                    // over the latest parsed certs.
6566                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6567                } catch (PackageManagerException e) {
6568                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6569                        throw e;
6570                    }
6571                    // The signature has changed, but this package is in the system
6572                    // image...  let's recover!
6573                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6574                    // However...  if this package is part of a shared user, but it
6575                    // doesn't match the signature of the shared user, let's fail.
6576                    // What this means is that you can't change the signatures
6577                    // associated with an overall shared user, which doesn't seem all
6578                    // that unreasonable.
6579                    if (pkgSetting.sharedUser != null) {
6580                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6581                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6582                            throw new PackageManagerException(
6583                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6584                                            "Signature mismatch for shared user : "
6585                                            + pkgSetting.sharedUser);
6586                        }
6587                    }
6588                    // File a report about this.
6589                    String msg = "System package " + pkg.packageName
6590                        + " signature changed; retaining data.";
6591                    reportSettingsProblem(Log.WARN, msg);
6592                }
6593            }
6594            // Verify that this new package doesn't have any content providers
6595            // that conflict with existing packages.  Only do this if the
6596            // package isn't already installed, since we don't want to break
6597            // things that are installed.
6598            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6599                final int N = pkg.providers.size();
6600                int i;
6601                for (i=0; i<N; i++) {
6602                    PackageParser.Provider p = pkg.providers.get(i);
6603                    if (p.info.authority != null) {
6604                        String names[] = p.info.authority.split(";");
6605                        for (int j = 0; j < names.length; j++) {
6606                            if (mProvidersByAuthority.containsKey(names[j])) {
6607                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6608                                final String otherPackageName =
6609                                        ((other != null && other.getComponentName() != null) ?
6610                                                other.getComponentName().getPackageName() : "?");
6611                                throw new PackageManagerException(
6612                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6613                                                "Can't install because provider name " + names[j]
6614                                                + " (in package " + pkg.applicationInfo.packageName
6615                                                + ") is already used by " + otherPackageName);
6616                            }
6617                        }
6618                    }
6619                }
6620            }
6621
6622            if (pkg.mAdoptPermissions != null) {
6623                // This package wants to adopt ownership of permissions from
6624                // another package.
6625                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6626                    final String origName = pkg.mAdoptPermissions.get(i);
6627                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6628                    if (orig != null) {
6629                        if (verifyPackageUpdateLPr(orig, pkg)) {
6630                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6631                                    + pkg.packageName);
6632                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6633                        }
6634                    }
6635                }
6636            }
6637        }
6638
6639        final String pkgName = pkg.packageName;
6640
6641        final long scanFileTime = scanFile.lastModified();
6642        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6643        pkg.applicationInfo.processName = fixProcessName(
6644                pkg.applicationInfo.packageName,
6645                pkg.applicationInfo.processName,
6646                pkg.applicationInfo.uid);
6647
6648        File dataPath;
6649        if (mPlatformPackage == pkg) {
6650            // The system package is special.
6651            dataPath = new File(Environment.getDataDirectory(), "system");
6652
6653            pkg.applicationInfo.dataDir = dataPath.getPath();
6654
6655        } else {
6656            // This is a normal package, need to make its data directory.
6657            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6658                    UserHandle.USER_OWNER, pkg.packageName);
6659
6660            boolean uidError = false;
6661            if (dataPath.exists()) {
6662                int currentUid = 0;
6663                try {
6664                    StructStat stat = Os.stat(dataPath.getPath());
6665                    currentUid = stat.st_uid;
6666                } catch (ErrnoException e) {
6667                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6668                }
6669
6670                // If we have mismatched owners for the data path, we have a problem.
6671                if (currentUid != pkg.applicationInfo.uid) {
6672                    boolean recovered = false;
6673                    if (currentUid == 0) {
6674                        // The directory somehow became owned by root.  Wow.
6675                        // This is probably because the system was stopped while
6676                        // installd was in the middle of messing with its libs
6677                        // directory.  Ask installd to fix that.
6678                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6679                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6680                        if (ret >= 0) {
6681                            recovered = true;
6682                            String msg = "Package " + pkg.packageName
6683                                    + " unexpectedly changed to uid 0; recovered to " +
6684                                    + pkg.applicationInfo.uid;
6685                            reportSettingsProblem(Log.WARN, msg);
6686                        }
6687                    }
6688                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6689                            || (scanFlags&SCAN_BOOTING) != 0)) {
6690                        // If this is a system app, we can at least delete its
6691                        // current data so the application will still work.
6692                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6693                        if (ret >= 0) {
6694                            // TODO: Kill the processes first
6695                            // Old data gone!
6696                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6697                                    ? "System package " : "Third party package ";
6698                            String msg = prefix + pkg.packageName
6699                                    + " has changed from uid: "
6700                                    + currentUid + " to "
6701                                    + pkg.applicationInfo.uid + "; old data erased";
6702                            reportSettingsProblem(Log.WARN, msg);
6703                            recovered = true;
6704
6705                            // And now re-install the app.
6706                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6707                                    pkg.applicationInfo.seinfo);
6708                            if (ret == -1) {
6709                                // Ack should not happen!
6710                                msg = prefix + pkg.packageName
6711                                        + " could not have data directory re-created after delete.";
6712                                reportSettingsProblem(Log.WARN, msg);
6713                                throw new PackageManagerException(
6714                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6715                            }
6716                        }
6717                        if (!recovered) {
6718                            mHasSystemUidErrors = true;
6719                        }
6720                    } else if (!recovered) {
6721                        // If we allow this install to proceed, we will be broken.
6722                        // Abort, abort!
6723                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6724                                "scanPackageLI");
6725                    }
6726                    if (!recovered) {
6727                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6728                            + pkg.applicationInfo.uid + "/fs_"
6729                            + currentUid;
6730                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6731                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6732                        String msg = "Package " + pkg.packageName
6733                                + " has mismatched uid: "
6734                                + currentUid + " on disk, "
6735                                + pkg.applicationInfo.uid + " in settings";
6736                        // writer
6737                        synchronized (mPackages) {
6738                            mSettings.mReadMessages.append(msg);
6739                            mSettings.mReadMessages.append('\n');
6740                            uidError = true;
6741                            if (!pkgSetting.uidError) {
6742                                reportSettingsProblem(Log.ERROR, msg);
6743                            }
6744                        }
6745                    }
6746                }
6747                pkg.applicationInfo.dataDir = dataPath.getPath();
6748                if (mShouldRestoreconData) {
6749                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6750                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6751                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6752                }
6753            } else {
6754                if (DEBUG_PACKAGE_SCANNING) {
6755                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6756                        Log.v(TAG, "Want this data dir: " + dataPath);
6757                }
6758                //invoke installer to do the actual installation
6759                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6760                        pkg.applicationInfo.seinfo);
6761                if (ret < 0) {
6762                    // Error from installer
6763                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6764                            "Unable to create data dirs [errorCode=" + ret + "]");
6765                }
6766
6767                if (dataPath.exists()) {
6768                    pkg.applicationInfo.dataDir = dataPath.getPath();
6769                } else {
6770                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6771                    pkg.applicationInfo.dataDir = null;
6772                }
6773            }
6774
6775            pkgSetting.uidError = uidError;
6776        }
6777
6778        final String path = scanFile.getPath();
6779        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6780
6781        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6782            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6783
6784            // Some system apps still use directory structure for native libraries
6785            // in which case we might end up not detecting abi solely based on apk
6786            // structure. Try to detect abi based on directory structure.
6787            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6788                    pkg.applicationInfo.primaryCpuAbi == null) {
6789                setBundledAppAbisAndRoots(pkg, pkgSetting);
6790                setNativeLibraryPaths(pkg);
6791            }
6792
6793        } else {
6794            if ((scanFlags & SCAN_MOVE) != 0) {
6795                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6796                // but we already have this packages package info in the PackageSetting. We just
6797                // use that and derive the native library path based on the new codepath.
6798                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6799                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6800            }
6801
6802            // Set native library paths again. For moves, the path will be updated based on the
6803            // ABIs we've determined above. For non-moves, the path will be updated based on the
6804            // ABIs we determined during compilation, but the path will depend on the final
6805            // package path (after the rename away from the stage path).
6806            setNativeLibraryPaths(pkg);
6807        }
6808
6809        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6810        final int[] userIds = sUserManager.getUserIds();
6811        synchronized (mInstallLock) {
6812            // Make sure all user data directories are ready to roll; we're okay
6813            // if they already exist
6814            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6815                for (int userId : userIds) {
6816                    if (userId != 0) {
6817                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6818                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6819                                pkg.applicationInfo.seinfo);
6820                    }
6821                }
6822            }
6823
6824            // Create a native library symlink only if we have native libraries
6825            // and if the native libraries are 32 bit libraries. We do not provide
6826            // this symlink for 64 bit libraries.
6827            if (pkg.applicationInfo.primaryCpuAbi != null &&
6828                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6829                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6830                for (int userId : userIds) {
6831                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6832                            nativeLibPath, userId) < 0) {
6833                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6834                                "Failed linking native library dir (user=" + userId + ")");
6835                    }
6836                }
6837            }
6838        }
6839
6840        // This is a special case for the "system" package, where the ABI is
6841        // dictated by the zygote configuration (and init.rc). We should keep track
6842        // of this ABI so that we can deal with "normal" applications that run under
6843        // the same UID correctly.
6844        if (mPlatformPackage == pkg) {
6845            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6846                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6847        }
6848
6849        // If there's a mismatch between the abi-override in the package setting
6850        // and the abiOverride specified for the install. Warn about this because we
6851        // would've already compiled the app without taking the package setting into
6852        // account.
6853        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6854            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6855                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6856                        " for package: " + pkg.packageName);
6857            }
6858        }
6859
6860        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6861        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6862        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6863
6864        // Copy the derived override back to the parsed package, so that we can
6865        // update the package settings accordingly.
6866        pkg.cpuAbiOverride = cpuAbiOverride;
6867
6868        if (DEBUG_ABI_SELECTION) {
6869            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6870                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6871                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6872        }
6873
6874        // Push the derived path down into PackageSettings so we know what to
6875        // clean up at uninstall time.
6876        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6877
6878        if (DEBUG_ABI_SELECTION) {
6879            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6880                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6881                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6882        }
6883
6884        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6885            // We don't do this here during boot because we can do it all
6886            // at once after scanning all existing packages.
6887            //
6888            // We also do this *before* we perform dexopt on this package, so that
6889            // we can avoid redundant dexopts, and also to make sure we've got the
6890            // code and package path correct.
6891            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6892                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6893        }
6894
6895        if ((scanFlags & SCAN_NO_DEX) == 0) {
6896            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6897                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6898            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6899                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6900            }
6901        }
6902        if (mFactoryTest && pkg.requestedPermissions.contains(
6903                android.Manifest.permission.FACTORY_TEST)) {
6904            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6905        }
6906
6907        ArrayList<PackageParser.Package> clientLibPkgs = null;
6908
6909        // writer
6910        synchronized (mPackages) {
6911            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6912                // Only system apps can add new shared libraries.
6913                if (pkg.libraryNames != null) {
6914                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6915                        String name = pkg.libraryNames.get(i);
6916                        boolean allowed = false;
6917                        if (pkg.isUpdatedSystemApp()) {
6918                            // New library entries can only be added through the
6919                            // system image.  This is important to get rid of a lot
6920                            // of nasty edge cases: for example if we allowed a non-
6921                            // system update of the app to add a library, then uninstalling
6922                            // the update would make the library go away, and assumptions
6923                            // we made such as through app install filtering would now
6924                            // have allowed apps on the device which aren't compatible
6925                            // with it.  Better to just have the restriction here, be
6926                            // conservative, and create many fewer cases that can negatively
6927                            // impact the user experience.
6928                            final PackageSetting sysPs = mSettings
6929                                    .getDisabledSystemPkgLPr(pkg.packageName);
6930                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6931                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6932                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6933                                        allowed = true;
6934                                        allowed = true;
6935                                        break;
6936                                    }
6937                                }
6938                            }
6939                        } else {
6940                            allowed = true;
6941                        }
6942                        if (allowed) {
6943                            if (!mSharedLibraries.containsKey(name)) {
6944                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6945                            } else if (!name.equals(pkg.packageName)) {
6946                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6947                                        + name + " already exists; skipping");
6948                            }
6949                        } else {
6950                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6951                                    + name + " that is not declared on system image; skipping");
6952                        }
6953                    }
6954                    if ((scanFlags&SCAN_BOOTING) == 0) {
6955                        // If we are not booting, we need to update any applications
6956                        // that are clients of our shared library.  If we are booting,
6957                        // this will all be done once the scan is complete.
6958                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6959                    }
6960                }
6961            }
6962        }
6963
6964        // We also need to dexopt any apps that are dependent on this library.  Note that
6965        // if these fail, we should abort the install since installing the library will
6966        // result in some apps being broken.
6967        if (clientLibPkgs != null) {
6968            if ((scanFlags & SCAN_NO_DEX) == 0) {
6969                for (int i = 0; i < clientLibPkgs.size(); i++) {
6970                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6971                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6972                            null /* instruction sets */, forceDex,
6973                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6974                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6975                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6976                                "scanPackageLI failed to dexopt clientLibPkgs");
6977                    }
6978                }
6979            }
6980        }
6981
6982        // Also need to kill any apps that are dependent on the library.
6983        if (clientLibPkgs != null) {
6984            for (int i=0; i<clientLibPkgs.size(); i++) {
6985                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6986                killApplication(clientPkg.applicationInfo.packageName,
6987                        clientPkg.applicationInfo.uid, "update lib");
6988            }
6989        }
6990
6991        // Make sure we're not adding any bogus keyset info
6992        KeySetManagerService ksms = mSettings.mKeySetManagerService;
6993        ksms.assertScannedPackageValid(pkg);
6994
6995        // writer
6996        synchronized (mPackages) {
6997            // We don't expect installation to fail beyond this point
6998
6999            // Add the new setting to mSettings
7000            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7001            // Add the new setting to mPackages
7002            mPackages.put(pkg.applicationInfo.packageName, pkg);
7003            // Make sure we don't accidentally delete its data.
7004            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7005            while (iter.hasNext()) {
7006                PackageCleanItem item = iter.next();
7007                if (pkgName.equals(item.packageName)) {
7008                    iter.remove();
7009                }
7010            }
7011
7012            // Take care of first install / last update times.
7013            if (currentTime != 0) {
7014                if (pkgSetting.firstInstallTime == 0) {
7015                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7016                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7017                    pkgSetting.lastUpdateTime = currentTime;
7018                }
7019            } else if (pkgSetting.firstInstallTime == 0) {
7020                // We need *something*.  Take time time stamp of the file.
7021                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7022            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7023                if (scanFileTime != pkgSetting.timeStamp) {
7024                    // A package on the system image has changed; consider this
7025                    // to be an update.
7026                    pkgSetting.lastUpdateTime = scanFileTime;
7027                }
7028            }
7029
7030            // Add the package's KeySets to the global KeySetManagerService
7031            ksms.addScannedPackageLPw(pkg);
7032
7033            int N = pkg.providers.size();
7034            StringBuilder r = null;
7035            int i;
7036            for (i=0; i<N; i++) {
7037                PackageParser.Provider p = pkg.providers.get(i);
7038                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7039                        p.info.processName, pkg.applicationInfo.uid);
7040                mProviders.addProvider(p);
7041                p.syncable = p.info.isSyncable;
7042                if (p.info.authority != null) {
7043                    String names[] = p.info.authority.split(";");
7044                    p.info.authority = null;
7045                    for (int j = 0; j < names.length; j++) {
7046                        if (j == 1 && p.syncable) {
7047                            // We only want the first authority for a provider to possibly be
7048                            // syncable, so if we already added this provider using a different
7049                            // authority clear the syncable flag. We copy the provider before
7050                            // changing it because the mProviders object contains a reference
7051                            // to a provider that we don't want to change.
7052                            // Only do this for the second authority since the resulting provider
7053                            // object can be the same for all future authorities for this provider.
7054                            p = new PackageParser.Provider(p);
7055                            p.syncable = false;
7056                        }
7057                        if (!mProvidersByAuthority.containsKey(names[j])) {
7058                            mProvidersByAuthority.put(names[j], p);
7059                            if (p.info.authority == null) {
7060                                p.info.authority = names[j];
7061                            } else {
7062                                p.info.authority = p.info.authority + ";" + names[j];
7063                            }
7064                            if (DEBUG_PACKAGE_SCANNING) {
7065                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7066                                    Log.d(TAG, "Registered content provider: " + names[j]
7067                                            + ", className = " + p.info.name + ", isSyncable = "
7068                                            + p.info.isSyncable);
7069                            }
7070                        } else {
7071                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7072                            Slog.w(TAG, "Skipping provider name " + names[j] +
7073                                    " (in package " + pkg.applicationInfo.packageName +
7074                                    "): name already used by "
7075                                    + ((other != null && other.getComponentName() != null)
7076                                            ? other.getComponentName().getPackageName() : "?"));
7077                        }
7078                    }
7079                }
7080                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7081                    if (r == null) {
7082                        r = new StringBuilder(256);
7083                    } else {
7084                        r.append(' ');
7085                    }
7086                    r.append(p.info.name);
7087                }
7088            }
7089            if (r != null) {
7090                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7091            }
7092
7093            N = pkg.services.size();
7094            r = null;
7095            for (i=0; i<N; i++) {
7096                PackageParser.Service s = pkg.services.get(i);
7097                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7098                        s.info.processName, pkg.applicationInfo.uid);
7099                mServices.addService(s);
7100                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7101                    if (r == null) {
7102                        r = new StringBuilder(256);
7103                    } else {
7104                        r.append(' ');
7105                    }
7106                    r.append(s.info.name);
7107                }
7108            }
7109            if (r != null) {
7110                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7111            }
7112
7113            N = pkg.receivers.size();
7114            r = null;
7115            for (i=0; i<N; i++) {
7116                PackageParser.Activity a = pkg.receivers.get(i);
7117                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7118                        a.info.processName, pkg.applicationInfo.uid);
7119                mReceivers.addActivity(a, "receiver");
7120                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7121                    if (r == null) {
7122                        r = new StringBuilder(256);
7123                    } else {
7124                        r.append(' ');
7125                    }
7126                    r.append(a.info.name);
7127                }
7128            }
7129            if (r != null) {
7130                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7131            }
7132
7133            N = pkg.activities.size();
7134            r = null;
7135            for (i=0; i<N; i++) {
7136                PackageParser.Activity a = pkg.activities.get(i);
7137                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7138                        a.info.processName, pkg.applicationInfo.uid);
7139                mActivities.addActivity(a, "activity");
7140                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7141                    if (r == null) {
7142                        r = new StringBuilder(256);
7143                    } else {
7144                        r.append(' ');
7145                    }
7146                    r.append(a.info.name);
7147                }
7148            }
7149            if (r != null) {
7150                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7151            }
7152
7153            N = pkg.permissionGroups.size();
7154            r = null;
7155            for (i=0; i<N; i++) {
7156                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7157                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7158                if (cur == null) {
7159                    mPermissionGroups.put(pg.info.name, pg);
7160                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7161                        if (r == null) {
7162                            r = new StringBuilder(256);
7163                        } else {
7164                            r.append(' ');
7165                        }
7166                        r.append(pg.info.name);
7167                    }
7168                } else {
7169                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7170                            + pg.info.packageName + " ignored: original from "
7171                            + cur.info.packageName);
7172                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7173                        if (r == null) {
7174                            r = new StringBuilder(256);
7175                        } else {
7176                            r.append(' ');
7177                        }
7178                        r.append("DUP:");
7179                        r.append(pg.info.name);
7180                    }
7181                }
7182            }
7183            if (r != null) {
7184                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7185            }
7186
7187            N = pkg.permissions.size();
7188            r = null;
7189            for (i=0; i<N; i++) {
7190                PackageParser.Permission p = pkg.permissions.get(i);
7191
7192                // Now that permission groups have a special meaning, we ignore permission
7193                // groups for legacy apps to prevent unexpected behavior. In particular,
7194                // permissions for one app being granted to someone just becuase they happen
7195                // to be in a group defined by another app (before this had no implications).
7196                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7197                    p.group = mPermissionGroups.get(p.info.group);
7198                    // Warn for a permission in an unknown group.
7199                    if (p.info.group != null && p.group == null) {
7200                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7201                                + p.info.packageName + " in an unknown group " + p.info.group);
7202                    }
7203                }
7204
7205                ArrayMap<String, BasePermission> permissionMap =
7206                        p.tree ? mSettings.mPermissionTrees
7207                                : mSettings.mPermissions;
7208                BasePermission bp = permissionMap.get(p.info.name);
7209
7210                // Allow system apps to redefine non-system permissions
7211                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7212                    final boolean currentOwnerIsSystem = (bp.perm != null
7213                            && isSystemApp(bp.perm.owner));
7214                    if (isSystemApp(p.owner)) {
7215                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7216                            // It's a built-in permission and no owner, take ownership now
7217                            bp.packageSetting = pkgSetting;
7218                            bp.perm = p;
7219                            bp.uid = pkg.applicationInfo.uid;
7220                            bp.sourcePackage = p.info.packageName;
7221                        } else if (!currentOwnerIsSystem) {
7222                            String msg = "New decl " + p.owner + " of permission  "
7223                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7224                            reportSettingsProblem(Log.WARN, msg);
7225                            bp = null;
7226                        }
7227                    }
7228                }
7229
7230                if (bp == null) {
7231                    bp = new BasePermission(p.info.name, p.info.packageName,
7232                            BasePermission.TYPE_NORMAL);
7233                    permissionMap.put(p.info.name, bp);
7234                }
7235
7236                if (bp.perm == null) {
7237                    if (bp.sourcePackage == null
7238                            || bp.sourcePackage.equals(p.info.packageName)) {
7239                        BasePermission tree = findPermissionTreeLP(p.info.name);
7240                        if (tree == null
7241                                || tree.sourcePackage.equals(p.info.packageName)) {
7242                            bp.packageSetting = pkgSetting;
7243                            bp.perm = p;
7244                            bp.uid = pkg.applicationInfo.uid;
7245                            bp.sourcePackage = p.info.packageName;
7246                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7247                                if (r == null) {
7248                                    r = new StringBuilder(256);
7249                                } else {
7250                                    r.append(' ');
7251                                }
7252                                r.append(p.info.name);
7253                            }
7254                        } else {
7255                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7256                                    + p.info.packageName + " ignored: base tree "
7257                                    + tree.name + " is from package "
7258                                    + tree.sourcePackage);
7259                        }
7260                    } else {
7261                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7262                                + p.info.packageName + " ignored: original from "
7263                                + bp.sourcePackage);
7264                    }
7265                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7266                    if (r == null) {
7267                        r = new StringBuilder(256);
7268                    } else {
7269                        r.append(' ');
7270                    }
7271                    r.append("DUP:");
7272                    r.append(p.info.name);
7273                }
7274                if (bp.perm == p) {
7275                    bp.protectionLevel = p.info.protectionLevel;
7276                }
7277            }
7278
7279            if (r != null) {
7280                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7281            }
7282
7283            N = pkg.instrumentation.size();
7284            r = null;
7285            for (i=0; i<N; i++) {
7286                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7287                a.info.packageName = pkg.applicationInfo.packageName;
7288                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7289                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7290                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7291                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7292                a.info.dataDir = pkg.applicationInfo.dataDir;
7293
7294                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7295                // need other information about the application, like the ABI and what not ?
7296                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7297                mInstrumentation.put(a.getComponentName(), a);
7298                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7299                    if (r == null) {
7300                        r = new StringBuilder(256);
7301                    } else {
7302                        r.append(' ');
7303                    }
7304                    r.append(a.info.name);
7305                }
7306            }
7307            if (r != null) {
7308                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7309            }
7310
7311            if (pkg.protectedBroadcasts != null) {
7312                N = pkg.protectedBroadcasts.size();
7313                for (i=0; i<N; i++) {
7314                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7315                }
7316            }
7317
7318            pkgSetting.setTimeStamp(scanFileTime);
7319
7320            // Create idmap files for pairs of (packages, overlay packages).
7321            // Note: "android", ie framework-res.apk, is handled by native layers.
7322            if (pkg.mOverlayTarget != null) {
7323                // This is an overlay package.
7324                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7325                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7326                        mOverlays.put(pkg.mOverlayTarget,
7327                                new ArrayMap<String, PackageParser.Package>());
7328                    }
7329                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7330                    map.put(pkg.packageName, pkg);
7331                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7332                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7333                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7334                                "scanPackageLI failed to createIdmap");
7335                    }
7336                }
7337            } else if (mOverlays.containsKey(pkg.packageName) &&
7338                    !pkg.packageName.equals("android")) {
7339                // This is a regular package, with one or more known overlay packages.
7340                createIdmapsForPackageLI(pkg);
7341            }
7342        }
7343
7344        return pkg;
7345    }
7346
7347    /**
7348     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7349     * is derived purely on the basis of the contents of {@code scanFile} and
7350     * {@code cpuAbiOverride}.
7351     *
7352     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7353     */
7354    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7355                                 String cpuAbiOverride, boolean extractLibs)
7356            throws PackageManagerException {
7357        // TODO: We can probably be smarter about this stuff. For installed apps,
7358        // we can calculate this information at install time once and for all. For
7359        // system apps, we can probably assume that this information doesn't change
7360        // after the first boot scan. As things stand, we do lots of unnecessary work.
7361
7362        // Give ourselves some initial paths; we'll come back for another
7363        // pass once we've determined ABI below.
7364        setNativeLibraryPaths(pkg);
7365
7366        // We would never need to extract libs for forward-locked and external packages,
7367        // since the container service will do it for us. We shouldn't attempt to
7368        // extract libs from system app when it was not updated.
7369        if (pkg.isForwardLocked() || isExternal(pkg) ||
7370            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7371            extractLibs = false;
7372        }
7373
7374        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7375        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7376
7377        NativeLibraryHelper.Handle handle = null;
7378        try {
7379            handle = NativeLibraryHelper.Handle.create(pkg);
7380            // TODO(multiArch): This can be null for apps that didn't go through the
7381            // usual installation process. We can calculate it again, like we
7382            // do during install time.
7383            //
7384            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7385            // unnecessary.
7386            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7387
7388            // Null out the abis so that they can be recalculated.
7389            pkg.applicationInfo.primaryCpuAbi = null;
7390            pkg.applicationInfo.secondaryCpuAbi = null;
7391            if (isMultiArch(pkg.applicationInfo)) {
7392                // Warn if we've set an abiOverride for multi-lib packages..
7393                // By definition, we need to copy both 32 and 64 bit libraries for
7394                // such packages.
7395                if (pkg.cpuAbiOverride != null
7396                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7397                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7398                }
7399
7400                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7401                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7402                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7403                    if (extractLibs) {
7404                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7405                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7406                                useIsaSpecificSubdirs);
7407                    } else {
7408                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7409                    }
7410                }
7411
7412                maybeThrowExceptionForMultiArchCopy(
7413                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7414
7415                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7416                    if (extractLibs) {
7417                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7418                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7419                                useIsaSpecificSubdirs);
7420                    } else {
7421                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7422                    }
7423                }
7424
7425                maybeThrowExceptionForMultiArchCopy(
7426                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7427
7428                if (abi64 >= 0) {
7429                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7430                }
7431
7432                if (abi32 >= 0) {
7433                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7434                    if (abi64 >= 0) {
7435                        pkg.applicationInfo.secondaryCpuAbi = abi;
7436                    } else {
7437                        pkg.applicationInfo.primaryCpuAbi = abi;
7438                    }
7439                }
7440            } else {
7441                String[] abiList = (cpuAbiOverride != null) ?
7442                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7443
7444                // Enable gross and lame hacks for apps that are built with old
7445                // SDK tools. We must scan their APKs for renderscript bitcode and
7446                // not launch them if it's present. Don't bother checking on devices
7447                // that don't have 64 bit support.
7448                boolean needsRenderScriptOverride = false;
7449                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7450                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7451                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7452                    needsRenderScriptOverride = true;
7453                }
7454
7455                final int copyRet;
7456                if (extractLibs) {
7457                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7458                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7459                } else {
7460                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7461                }
7462
7463                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7464                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7465                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7466                }
7467
7468                if (copyRet >= 0) {
7469                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7470                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7471                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7472                } else if (needsRenderScriptOverride) {
7473                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7474                }
7475            }
7476        } catch (IOException ioe) {
7477            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7478        } finally {
7479            IoUtils.closeQuietly(handle);
7480        }
7481
7482        // Now that we've calculated the ABIs and determined if it's an internal app,
7483        // we will go ahead and populate the nativeLibraryPath.
7484        setNativeLibraryPaths(pkg);
7485    }
7486
7487    /**
7488     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7489     * i.e, so that all packages can be run inside a single process if required.
7490     *
7491     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7492     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7493     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7494     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7495     * updating a package that belongs to a shared user.
7496     *
7497     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7498     * adds unnecessary complexity.
7499     */
7500    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7501            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7502        String requiredInstructionSet = null;
7503        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7504            requiredInstructionSet = VMRuntime.getInstructionSet(
7505                     scannedPackage.applicationInfo.primaryCpuAbi);
7506        }
7507
7508        PackageSetting requirer = null;
7509        for (PackageSetting ps : packagesForUser) {
7510            // If packagesForUser contains scannedPackage, we skip it. This will happen
7511            // when scannedPackage is an update of an existing package. Without this check,
7512            // we will never be able to change the ABI of any package belonging to a shared
7513            // user, even if it's compatible with other packages.
7514            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7515                if (ps.primaryCpuAbiString == null) {
7516                    continue;
7517                }
7518
7519                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7520                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7521                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7522                    // this but there's not much we can do.
7523                    String errorMessage = "Instruction set mismatch, "
7524                            + ((requirer == null) ? "[caller]" : requirer)
7525                            + " requires " + requiredInstructionSet + " whereas " + ps
7526                            + " requires " + instructionSet;
7527                    Slog.w(TAG, errorMessage);
7528                }
7529
7530                if (requiredInstructionSet == null) {
7531                    requiredInstructionSet = instructionSet;
7532                    requirer = ps;
7533                }
7534            }
7535        }
7536
7537        if (requiredInstructionSet != null) {
7538            String adjustedAbi;
7539            if (requirer != null) {
7540                // requirer != null implies that either scannedPackage was null or that scannedPackage
7541                // did not require an ABI, in which case we have to adjust scannedPackage to match
7542                // the ABI of the set (which is the same as requirer's ABI)
7543                adjustedAbi = requirer.primaryCpuAbiString;
7544                if (scannedPackage != null) {
7545                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7546                }
7547            } else {
7548                // requirer == null implies that we're updating all ABIs in the set to
7549                // match scannedPackage.
7550                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7551            }
7552
7553            for (PackageSetting ps : packagesForUser) {
7554                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7555                    if (ps.primaryCpuAbiString != null) {
7556                        continue;
7557                    }
7558
7559                    ps.primaryCpuAbiString = adjustedAbi;
7560                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7561                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7562                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7563
7564                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7565                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7566                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7567                            ps.primaryCpuAbiString = null;
7568                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7569                            return;
7570                        } else {
7571                            mInstaller.rmdex(ps.codePathString,
7572                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7573                        }
7574                    }
7575                }
7576            }
7577        }
7578    }
7579
7580    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7581        synchronized (mPackages) {
7582            mResolverReplaced = true;
7583            // Set up information for custom user intent resolution activity.
7584            mResolveActivity.applicationInfo = pkg.applicationInfo;
7585            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7586            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7587            mResolveActivity.processName = pkg.applicationInfo.packageName;
7588            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7589            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7590                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7591            mResolveActivity.theme = 0;
7592            mResolveActivity.exported = true;
7593            mResolveActivity.enabled = true;
7594            mResolveInfo.activityInfo = mResolveActivity;
7595            mResolveInfo.priority = 0;
7596            mResolveInfo.preferredOrder = 0;
7597            mResolveInfo.match = 0;
7598            mResolveComponentName = mCustomResolverComponentName;
7599            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7600                    mResolveComponentName);
7601        }
7602    }
7603
7604    private static String calculateBundledApkRoot(final String codePathString) {
7605        final File codePath = new File(codePathString);
7606        final File codeRoot;
7607        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7608            codeRoot = Environment.getRootDirectory();
7609        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7610            codeRoot = Environment.getOemDirectory();
7611        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7612            codeRoot = Environment.getVendorDirectory();
7613        } else {
7614            // Unrecognized code path; take its top real segment as the apk root:
7615            // e.g. /something/app/blah.apk => /something
7616            try {
7617                File f = codePath.getCanonicalFile();
7618                File parent = f.getParentFile();    // non-null because codePath is a file
7619                File tmp;
7620                while ((tmp = parent.getParentFile()) != null) {
7621                    f = parent;
7622                    parent = tmp;
7623                }
7624                codeRoot = f;
7625                Slog.w(TAG, "Unrecognized code path "
7626                        + codePath + " - using " + codeRoot);
7627            } catch (IOException e) {
7628                // Can't canonicalize the code path -- shenanigans?
7629                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7630                return Environment.getRootDirectory().getPath();
7631            }
7632        }
7633        return codeRoot.getPath();
7634    }
7635
7636    /**
7637     * Derive and set the location of native libraries for the given package,
7638     * which varies depending on where and how the package was installed.
7639     */
7640    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7641        final ApplicationInfo info = pkg.applicationInfo;
7642        final String codePath = pkg.codePath;
7643        final File codeFile = new File(codePath);
7644        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7645        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7646
7647        info.nativeLibraryRootDir = null;
7648        info.nativeLibraryRootRequiresIsa = false;
7649        info.nativeLibraryDir = null;
7650        info.secondaryNativeLibraryDir = null;
7651
7652        if (isApkFile(codeFile)) {
7653            // Monolithic install
7654            if (bundledApp) {
7655                // If "/system/lib64/apkname" exists, assume that is the per-package
7656                // native library directory to use; otherwise use "/system/lib/apkname".
7657                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7658                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7659                        getPrimaryInstructionSet(info));
7660
7661                // This is a bundled system app so choose the path based on the ABI.
7662                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7663                // is just the default path.
7664                final String apkName = deriveCodePathName(codePath);
7665                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7666                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7667                        apkName).getAbsolutePath();
7668
7669                if (info.secondaryCpuAbi != null) {
7670                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7671                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7672                            secondaryLibDir, apkName).getAbsolutePath();
7673                }
7674            } else if (asecApp) {
7675                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7676                        .getAbsolutePath();
7677            } else {
7678                final String apkName = deriveCodePathName(codePath);
7679                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7680                        .getAbsolutePath();
7681            }
7682
7683            info.nativeLibraryRootRequiresIsa = false;
7684            info.nativeLibraryDir = info.nativeLibraryRootDir;
7685        } else {
7686            // Cluster install
7687            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7688            info.nativeLibraryRootRequiresIsa = true;
7689
7690            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7691                    getPrimaryInstructionSet(info)).getAbsolutePath();
7692
7693            if (info.secondaryCpuAbi != null) {
7694                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7695                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7696            }
7697        }
7698    }
7699
7700    /**
7701     * Calculate the abis and roots for a bundled app. These can uniquely
7702     * be determined from the contents of the system partition, i.e whether
7703     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7704     * of this information, and instead assume that the system was built
7705     * sensibly.
7706     */
7707    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7708                                           PackageSetting pkgSetting) {
7709        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7710
7711        // If "/system/lib64/apkname" exists, assume that is the per-package
7712        // native library directory to use; otherwise use "/system/lib/apkname".
7713        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7714        setBundledAppAbi(pkg, apkRoot, apkName);
7715        // pkgSetting might be null during rescan following uninstall of updates
7716        // to a bundled app, so accommodate that possibility.  The settings in
7717        // that case will be established later from the parsed package.
7718        //
7719        // If the settings aren't null, sync them up with what we've just derived.
7720        // note that apkRoot isn't stored in the package settings.
7721        if (pkgSetting != null) {
7722            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7723            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7724        }
7725    }
7726
7727    /**
7728     * Deduces the ABI of a bundled app and sets the relevant fields on the
7729     * parsed pkg object.
7730     *
7731     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7732     *        under which system libraries are installed.
7733     * @param apkName the name of the installed package.
7734     */
7735    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7736        final File codeFile = new File(pkg.codePath);
7737
7738        final boolean has64BitLibs;
7739        final boolean has32BitLibs;
7740        if (isApkFile(codeFile)) {
7741            // Monolithic install
7742            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7743            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7744        } else {
7745            // Cluster install
7746            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7747            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7748                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7749                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7750                has64BitLibs = (new File(rootDir, isa)).exists();
7751            } else {
7752                has64BitLibs = false;
7753            }
7754            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7755                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7756                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7757                has32BitLibs = (new File(rootDir, isa)).exists();
7758            } else {
7759                has32BitLibs = false;
7760            }
7761        }
7762
7763        if (has64BitLibs && !has32BitLibs) {
7764            // The package has 64 bit libs, but not 32 bit libs. Its primary
7765            // ABI should be 64 bit. We can safely assume here that the bundled
7766            // native libraries correspond to the most preferred ABI in the list.
7767
7768            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7769            pkg.applicationInfo.secondaryCpuAbi = null;
7770        } else if (has32BitLibs && !has64BitLibs) {
7771            // The package has 32 bit libs but not 64 bit libs. Its primary
7772            // ABI should be 32 bit.
7773
7774            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7775            pkg.applicationInfo.secondaryCpuAbi = null;
7776        } else if (has32BitLibs && has64BitLibs) {
7777            // The application has both 64 and 32 bit bundled libraries. We check
7778            // here that the app declares multiArch support, and warn if it doesn't.
7779            //
7780            // We will be lenient here and record both ABIs. The primary will be the
7781            // ABI that's higher on the list, i.e, a device that's configured to prefer
7782            // 64 bit apps will see a 64 bit primary ABI,
7783
7784            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7785                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7786            }
7787
7788            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7789                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7790                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7791            } else {
7792                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7793                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7794            }
7795        } else {
7796            pkg.applicationInfo.primaryCpuAbi = null;
7797            pkg.applicationInfo.secondaryCpuAbi = null;
7798        }
7799    }
7800
7801    private void killApplication(String pkgName, int appId, String reason) {
7802        // Request the ActivityManager to kill the process(only for existing packages)
7803        // so that we do not end up in a confused state while the user is still using the older
7804        // version of the application while the new one gets installed.
7805        IActivityManager am = ActivityManagerNative.getDefault();
7806        if (am != null) {
7807            try {
7808                am.killApplicationWithAppId(pkgName, appId, reason);
7809            } catch (RemoteException e) {
7810            }
7811        }
7812    }
7813
7814    void removePackageLI(PackageSetting ps, boolean chatty) {
7815        if (DEBUG_INSTALL) {
7816            if (chatty)
7817                Log.d(TAG, "Removing package " + ps.name);
7818        }
7819
7820        // writer
7821        synchronized (mPackages) {
7822            mPackages.remove(ps.name);
7823            final PackageParser.Package pkg = ps.pkg;
7824            if (pkg != null) {
7825                cleanPackageDataStructuresLILPw(pkg, chatty);
7826            }
7827        }
7828    }
7829
7830    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7831        if (DEBUG_INSTALL) {
7832            if (chatty)
7833                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7834        }
7835
7836        // writer
7837        synchronized (mPackages) {
7838            mPackages.remove(pkg.applicationInfo.packageName);
7839            cleanPackageDataStructuresLILPw(pkg, chatty);
7840        }
7841    }
7842
7843    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7844        int N = pkg.providers.size();
7845        StringBuilder r = null;
7846        int i;
7847        for (i=0; i<N; i++) {
7848            PackageParser.Provider p = pkg.providers.get(i);
7849            mProviders.removeProvider(p);
7850            if (p.info.authority == null) {
7851
7852                /* There was another ContentProvider with this authority when
7853                 * this app was installed so this authority is null,
7854                 * Ignore it as we don't have to unregister the provider.
7855                 */
7856                continue;
7857            }
7858            String names[] = p.info.authority.split(";");
7859            for (int j = 0; j < names.length; j++) {
7860                if (mProvidersByAuthority.get(names[j]) == p) {
7861                    mProvidersByAuthority.remove(names[j]);
7862                    if (DEBUG_REMOVE) {
7863                        if (chatty)
7864                            Log.d(TAG, "Unregistered content provider: " + names[j]
7865                                    + ", className = " + p.info.name + ", isSyncable = "
7866                                    + p.info.isSyncable);
7867                    }
7868                }
7869            }
7870            if (DEBUG_REMOVE && chatty) {
7871                if (r == null) {
7872                    r = new StringBuilder(256);
7873                } else {
7874                    r.append(' ');
7875                }
7876                r.append(p.info.name);
7877            }
7878        }
7879        if (r != null) {
7880            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7881        }
7882
7883        N = pkg.services.size();
7884        r = null;
7885        for (i=0; i<N; i++) {
7886            PackageParser.Service s = pkg.services.get(i);
7887            mServices.removeService(s);
7888            if (chatty) {
7889                if (r == null) {
7890                    r = new StringBuilder(256);
7891                } else {
7892                    r.append(' ');
7893                }
7894                r.append(s.info.name);
7895            }
7896        }
7897        if (r != null) {
7898            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7899        }
7900
7901        N = pkg.receivers.size();
7902        r = null;
7903        for (i=0; i<N; i++) {
7904            PackageParser.Activity a = pkg.receivers.get(i);
7905            mReceivers.removeActivity(a, "receiver");
7906            if (DEBUG_REMOVE && chatty) {
7907                if (r == null) {
7908                    r = new StringBuilder(256);
7909                } else {
7910                    r.append(' ');
7911                }
7912                r.append(a.info.name);
7913            }
7914        }
7915        if (r != null) {
7916            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7917        }
7918
7919        N = pkg.activities.size();
7920        r = null;
7921        for (i=0; i<N; i++) {
7922            PackageParser.Activity a = pkg.activities.get(i);
7923            mActivities.removeActivity(a, "activity");
7924            if (DEBUG_REMOVE && chatty) {
7925                if (r == null) {
7926                    r = new StringBuilder(256);
7927                } else {
7928                    r.append(' ');
7929                }
7930                r.append(a.info.name);
7931            }
7932        }
7933        if (r != null) {
7934            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7935        }
7936
7937        N = pkg.permissions.size();
7938        r = null;
7939        for (i=0; i<N; i++) {
7940            PackageParser.Permission p = pkg.permissions.get(i);
7941            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7942            if (bp == null) {
7943                bp = mSettings.mPermissionTrees.get(p.info.name);
7944            }
7945            if (bp != null && bp.perm == p) {
7946                bp.perm = null;
7947                if (DEBUG_REMOVE && chatty) {
7948                    if (r == null) {
7949                        r = new StringBuilder(256);
7950                    } else {
7951                        r.append(' ');
7952                    }
7953                    r.append(p.info.name);
7954                }
7955            }
7956            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7957                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7958                if (appOpPerms != null) {
7959                    appOpPerms.remove(pkg.packageName);
7960                }
7961            }
7962        }
7963        if (r != null) {
7964            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7965        }
7966
7967        N = pkg.requestedPermissions.size();
7968        r = null;
7969        for (i=0; i<N; i++) {
7970            String perm = pkg.requestedPermissions.get(i);
7971            BasePermission bp = mSettings.mPermissions.get(perm);
7972            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7973                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7974                if (appOpPerms != null) {
7975                    appOpPerms.remove(pkg.packageName);
7976                    if (appOpPerms.isEmpty()) {
7977                        mAppOpPermissionPackages.remove(perm);
7978                    }
7979                }
7980            }
7981        }
7982        if (r != null) {
7983            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7984        }
7985
7986        N = pkg.instrumentation.size();
7987        r = null;
7988        for (i=0; i<N; i++) {
7989            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7990            mInstrumentation.remove(a.getComponentName());
7991            if (DEBUG_REMOVE && chatty) {
7992                if (r == null) {
7993                    r = new StringBuilder(256);
7994                } else {
7995                    r.append(' ');
7996                }
7997                r.append(a.info.name);
7998            }
7999        }
8000        if (r != null) {
8001            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8002        }
8003
8004        r = null;
8005        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8006            // Only system apps can hold shared libraries.
8007            if (pkg.libraryNames != null) {
8008                for (i=0; i<pkg.libraryNames.size(); i++) {
8009                    String name = pkg.libraryNames.get(i);
8010                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8011                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8012                        mSharedLibraries.remove(name);
8013                        if (DEBUG_REMOVE && chatty) {
8014                            if (r == null) {
8015                                r = new StringBuilder(256);
8016                            } else {
8017                                r.append(' ');
8018                            }
8019                            r.append(name);
8020                        }
8021                    }
8022                }
8023            }
8024        }
8025        if (r != null) {
8026            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8027        }
8028    }
8029
8030    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8031        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8032            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8033                return true;
8034            }
8035        }
8036        return false;
8037    }
8038
8039    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8040    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8041    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8042
8043    private void updatePermissionsLPw(String changingPkg,
8044            PackageParser.Package pkgInfo, int flags) {
8045        // Make sure there are no dangling permission trees.
8046        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8047        while (it.hasNext()) {
8048            final BasePermission bp = it.next();
8049            if (bp.packageSetting == null) {
8050                // We may not yet have parsed the package, so just see if
8051                // we still know about its settings.
8052                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8053            }
8054            if (bp.packageSetting == null) {
8055                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8056                        + " from package " + bp.sourcePackage);
8057                it.remove();
8058            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8059                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8060                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8061                            + " from package " + bp.sourcePackage);
8062                    flags |= UPDATE_PERMISSIONS_ALL;
8063                    it.remove();
8064                }
8065            }
8066        }
8067
8068        // Make sure all dynamic permissions have been assigned to a package,
8069        // and make sure there are no dangling permissions.
8070        it = mSettings.mPermissions.values().iterator();
8071        while (it.hasNext()) {
8072            final BasePermission bp = it.next();
8073            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8074                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8075                        + bp.name + " pkg=" + bp.sourcePackage
8076                        + " info=" + bp.pendingInfo);
8077                if (bp.packageSetting == null && bp.pendingInfo != null) {
8078                    final BasePermission tree = findPermissionTreeLP(bp.name);
8079                    if (tree != null && tree.perm != null) {
8080                        bp.packageSetting = tree.packageSetting;
8081                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8082                                new PermissionInfo(bp.pendingInfo));
8083                        bp.perm.info.packageName = tree.perm.info.packageName;
8084                        bp.perm.info.name = bp.name;
8085                        bp.uid = tree.uid;
8086                    }
8087                }
8088            }
8089            if (bp.packageSetting == null) {
8090                // We may not yet have parsed the package, so just see if
8091                // we still know about its settings.
8092                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8093            }
8094            if (bp.packageSetting == null) {
8095                Slog.w(TAG, "Removing dangling permission: " + bp.name
8096                        + " from package " + bp.sourcePackage);
8097                it.remove();
8098            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8099                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8100                    Slog.i(TAG, "Removing old permission: " + bp.name
8101                            + " from package " + bp.sourcePackage);
8102                    flags |= UPDATE_PERMISSIONS_ALL;
8103                    it.remove();
8104                }
8105            }
8106        }
8107
8108        // Now update the permissions for all packages, in particular
8109        // replace the granted permissions of the system packages.
8110        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8111            for (PackageParser.Package pkg : mPackages.values()) {
8112                if (pkg != pkgInfo) {
8113                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8114                            changingPkg);
8115                }
8116            }
8117        }
8118
8119        if (pkgInfo != null) {
8120            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8121        }
8122    }
8123
8124    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8125            String packageOfInterest) {
8126        // IMPORTANT: There are two types of permissions: install and runtime.
8127        // Install time permissions are granted when the app is installed to
8128        // all device users and users added in the future. Runtime permissions
8129        // are granted at runtime explicitly to specific users. Normal and signature
8130        // protected permissions are install time permissions. Dangerous permissions
8131        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8132        // otherwise they are runtime permissions. This function does not manage
8133        // runtime permissions except for the case an app targeting Lollipop MR1
8134        // being upgraded to target a newer SDK, in which case dangerous permissions
8135        // are transformed from install time to runtime ones.
8136
8137        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8138        if (ps == null) {
8139            return;
8140        }
8141
8142        PermissionsState permissionsState = ps.getPermissionsState();
8143        PermissionsState origPermissions = permissionsState;
8144
8145        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8146
8147        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8148
8149        boolean changedInstallPermission = false;
8150
8151        if (replace) {
8152            ps.installPermissionsFixed = false;
8153            if (!ps.isSharedUser()) {
8154                origPermissions = new PermissionsState(permissionsState);
8155                permissionsState.reset();
8156            }
8157        }
8158
8159        permissionsState.setGlobalGids(mGlobalGids);
8160
8161        final int N = pkg.requestedPermissions.size();
8162        for (int i=0; i<N; i++) {
8163            final String name = pkg.requestedPermissions.get(i);
8164            final BasePermission bp = mSettings.mPermissions.get(name);
8165
8166            if (DEBUG_INSTALL) {
8167                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8168            }
8169
8170            if (bp == null || bp.packageSetting == null) {
8171                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8172                    Slog.w(TAG, "Unknown permission " + name
8173                            + " in package " + pkg.packageName);
8174                }
8175                continue;
8176            }
8177
8178            final String perm = bp.name;
8179            boolean allowedSig = false;
8180            int grant = GRANT_DENIED;
8181
8182            // Keep track of app op permissions.
8183            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8184                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8185                if (pkgs == null) {
8186                    pkgs = new ArraySet<>();
8187                    mAppOpPermissionPackages.put(bp.name, pkgs);
8188                }
8189                pkgs.add(pkg.packageName);
8190            }
8191
8192            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8193            switch (level) {
8194                case PermissionInfo.PROTECTION_NORMAL: {
8195                    // For all apps normal permissions are install time ones.
8196                    grant = GRANT_INSTALL;
8197                } break;
8198
8199                case PermissionInfo.PROTECTION_DANGEROUS: {
8200                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8201                        // For legacy apps dangerous permissions are install time ones.
8202                        grant = GRANT_INSTALL_LEGACY;
8203                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8204                        // For legacy apps that became modern, install becomes runtime.
8205                        grant = GRANT_UPGRADE;
8206                    } else {
8207                        // For modern apps keep runtime permissions unchanged.
8208                        grant = GRANT_RUNTIME;
8209                    }
8210                } break;
8211
8212                case PermissionInfo.PROTECTION_SIGNATURE: {
8213                    // For all apps signature permissions are install time ones.
8214                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8215                    if (allowedSig) {
8216                        grant = GRANT_INSTALL;
8217                    }
8218                } break;
8219            }
8220
8221            if (DEBUG_INSTALL) {
8222                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8223            }
8224
8225            if (grant != GRANT_DENIED) {
8226                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8227                    // If this is an existing, non-system package, then
8228                    // we can't add any new permissions to it.
8229                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8230                        // Except...  if this is a permission that was added
8231                        // to the platform (note: need to only do this when
8232                        // updating the platform).
8233                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8234                            grant = GRANT_DENIED;
8235                        }
8236                    }
8237                }
8238
8239                switch (grant) {
8240                    case GRANT_INSTALL: {
8241                        // Revoke this as runtime permission to handle the case of
8242                        // a runtime permission being downgraded to an install one.
8243                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8244                            if (origPermissions.getRuntimePermissionState(
8245                                    bp.name, userId) != null) {
8246                                // Revoke the runtime permission and clear the flags.
8247                                origPermissions.revokeRuntimePermission(bp, userId);
8248                                origPermissions.updatePermissionFlags(bp, userId,
8249                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8250                                // If we revoked a permission permission, we have to write.
8251                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8252                                        changedRuntimePermissionUserIds, userId);
8253                            }
8254                        }
8255                        // Grant an install permission.
8256                        if (permissionsState.grantInstallPermission(bp) !=
8257                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8258                            changedInstallPermission = true;
8259                        }
8260                    } break;
8261
8262                    case GRANT_INSTALL_LEGACY: {
8263                        // Grant an install permission.
8264                        if (permissionsState.grantInstallPermission(bp) !=
8265                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8266                            changedInstallPermission = true;
8267                        }
8268                    } break;
8269
8270                    case GRANT_RUNTIME: {
8271                        // Grant previously granted runtime permissions.
8272                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8273                            PermissionState permissionState = origPermissions
8274                                    .getRuntimePermissionState(bp.name, userId);
8275                            final int flags = permissionState != null
8276                                    ? permissionState.getFlags() : 0;
8277                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8278                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8279                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8280                                    // If we cannot put the permission as it was, we have to write.
8281                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8282                                            changedRuntimePermissionUserIds, userId);
8283                                }
8284                            }
8285                            // Propagate the permission flags.
8286                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8287                        }
8288                    } break;
8289
8290                    case GRANT_UPGRADE: {
8291                        // Grant runtime permissions for a previously held install permission.
8292                        PermissionState permissionState = origPermissions
8293                                .getInstallPermissionState(bp.name);
8294                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8295
8296                        if (origPermissions.revokeInstallPermission(bp)
8297                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8298                            // We will be transferring the permission flags, so clear them.
8299                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8300                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8301                            changedInstallPermission = true;
8302                        }
8303
8304                        // If the permission is not to be promoted to runtime we ignore it and
8305                        // also its other flags as they are not applicable to install permissions.
8306                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8307                            for (int userId : currentUserIds) {
8308                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8309                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8310                                    // Transfer the permission flags.
8311                                    permissionsState.updatePermissionFlags(bp, userId,
8312                                            flags, flags);
8313                                    // If we granted the permission, we have to write.
8314                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8315                                            changedRuntimePermissionUserIds, userId);
8316                                }
8317                            }
8318                        }
8319                    } break;
8320
8321                    default: {
8322                        if (packageOfInterest == null
8323                                || packageOfInterest.equals(pkg.packageName)) {
8324                            Slog.w(TAG, "Not granting permission " + perm
8325                                    + " to package " + pkg.packageName
8326                                    + " because it was previously installed without");
8327                        }
8328                    } break;
8329                }
8330            } else {
8331                if (permissionsState.revokeInstallPermission(bp) !=
8332                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8333                    // Also drop the permission flags.
8334                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8335                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8336                    changedInstallPermission = true;
8337                    Slog.i(TAG, "Un-granting permission " + perm
8338                            + " from package " + pkg.packageName
8339                            + " (protectionLevel=" + bp.protectionLevel
8340                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8341                            + ")");
8342                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8343                    // Don't print warning for app op permissions, since it is fine for them
8344                    // not to be granted, there is a UI for the user to decide.
8345                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8346                        Slog.w(TAG, "Not granting permission " + perm
8347                                + " to package " + pkg.packageName
8348                                + " (protectionLevel=" + bp.protectionLevel
8349                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8350                                + ")");
8351                    }
8352                }
8353            }
8354        }
8355
8356        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8357                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8358            // This is the first that we have heard about this package, so the
8359            // permissions we have now selected are fixed until explicitly
8360            // changed.
8361            ps.installPermissionsFixed = true;
8362        }
8363
8364        // Persist the runtime permissions state for users with changes.
8365        for (int userId : changedRuntimePermissionUserIds) {
8366            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8367        }
8368    }
8369
8370    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8371        boolean allowed = false;
8372        final int NP = PackageParser.NEW_PERMISSIONS.length;
8373        for (int ip=0; ip<NP; ip++) {
8374            final PackageParser.NewPermissionInfo npi
8375                    = PackageParser.NEW_PERMISSIONS[ip];
8376            if (npi.name.equals(perm)
8377                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8378                allowed = true;
8379                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8380                        + pkg.packageName);
8381                break;
8382            }
8383        }
8384        return allowed;
8385    }
8386
8387    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8388            BasePermission bp, PermissionsState origPermissions) {
8389        boolean allowed;
8390        allowed = (compareSignatures(
8391                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8392                        == PackageManager.SIGNATURE_MATCH)
8393                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8394                        == PackageManager.SIGNATURE_MATCH);
8395        if (!allowed && (bp.protectionLevel
8396                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
8397            if (isSystemApp(pkg)) {
8398                // For updated system applications, a system permission
8399                // is granted only if it had been defined by the original application.
8400                if (pkg.isUpdatedSystemApp()) {
8401                    final PackageSetting sysPs = mSettings
8402                            .getDisabledSystemPkgLPr(pkg.packageName);
8403                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8404                        // If the original was granted this permission, we take
8405                        // that grant decision as read and propagate it to the
8406                        // update.
8407                        if (sysPs.isPrivileged()) {
8408                            allowed = true;
8409                        }
8410                    } else {
8411                        // The system apk may have been updated with an older
8412                        // version of the one on the data partition, but which
8413                        // granted a new system permission that it didn't have
8414                        // before.  In this case we do want to allow the app to
8415                        // now get the new permission if the ancestral apk is
8416                        // privileged to get it.
8417                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8418                            for (int j=0;
8419                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8420                                if (perm.equals(
8421                                        sysPs.pkg.requestedPermissions.get(j))) {
8422                                    allowed = true;
8423                                    break;
8424                                }
8425                            }
8426                        }
8427                    }
8428                } else {
8429                    allowed = isPrivilegedApp(pkg);
8430                }
8431            }
8432        }
8433        if (!allowed && (bp.protectionLevel
8434                & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8435                && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8436            // If this was a previously normal/dangerous permission that got moved
8437            // to a system permission as part of the runtime permission redesign, then
8438            // we still want to blindly grant it to old apps.
8439            allowed = true;
8440        }
8441        if (!allowed && (bp.protectionLevel
8442                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8443            // For development permissions, a development permission
8444            // is granted only if it was already granted.
8445            allowed = origPermissions.hasInstallPermission(perm);
8446        }
8447        return allowed;
8448    }
8449
8450    final class ActivityIntentResolver
8451            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8452        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8453                boolean defaultOnly, int userId) {
8454            if (!sUserManager.exists(userId)) return null;
8455            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8456            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8457        }
8458
8459        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8460                int userId) {
8461            if (!sUserManager.exists(userId)) return null;
8462            mFlags = flags;
8463            return super.queryIntent(intent, resolvedType,
8464                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8465        }
8466
8467        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8468                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8469            if (!sUserManager.exists(userId)) return null;
8470            if (packageActivities == null) {
8471                return null;
8472            }
8473            mFlags = flags;
8474            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8475            final int N = packageActivities.size();
8476            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8477                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8478
8479            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8480            for (int i = 0; i < N; ++i) {
8481                intentFilters = packageActivities.get(i).intents;
8482                if (intentFilters != null && intentFilters.size() > 0) {
8483                    PackageParser.ActivityIntentInfo[] array =
8484                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8485                    intentFilters.toArray(array);
8486                    listCut.add(array);
8487                }
8488            }
8489            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8490        }
8491
8492        public final void addActivity(PackageParser.Activity a, String type) {
8493            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8494            mActivities.put(a.getComponentName(), a);
8495            if (DEBUG_SHOW_INFO)
8496                Log.v(
8497                TAG, "  " + type + " " +
8498                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8499            if (DEBUG_SHOW_INFO)
8500                Log.v(TAG, "    Class=" + a.info.name);
8501            final int NI = a.intents.size();
8502            for (int j=0; j<NI; j++) {
8503                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8504                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8505                    intent.setPriority(0);
8506                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8507                            + a.className + " with priority > 0, forcing to 0");
8508                }
8509                if (DEBUG_SHOW_INFO) {
8510                    Log.v(TAG, "    IntentFilter:");
8511                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8512                }
8513                if (!intent.debugCheck()) {
8514                    Log.w(TAG, "==> For Activity " + a.info.name);
8515                }
8516                addFilter(intent);
8517            }
8518        }
8519
8520        public final void removeActivity(PackageParser.Activity a, String type) {
8521            mActivities.remove(a.getComponentName());
8522            if (DEBUG_SHOW_INFO) {
8523                Log.v(TAG, "  " + type + " "
8524                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8525                                : a.info.name) + ":");
8526                Log.v(TAG, "    Class=" + a.info.name);
8527            }
8528            final int NI = a.intents.size();
8529            for (int j=0; j<NI; j++) {
8530                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8531                if (DEBUG_SHOW_INFO) {
8532                    Log.v(TAG, "    IntentFilter:");
8533                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8534                }
8535                removeFilter(intent);
8536            }
8537        }
8538
8539        @Override
8540        protected boolean allowFilterResult(
8541                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8542            ActivityInfo filterAi = filter.activity.info;
8543            for (int i=dest.size()-1; i>=0; i--) {
8544                ActivityInfo destAi = dest.get(i).activityInfo;
8545                if (destAi.name == filterAi.name
8546                        && destAi.packageName == filterAi.packageName) {
8547                    return false;
8548                }
8549            }
8550            return true;
8551        }
8552
8553        @Override
8554        protected ActivityIntentInfo[] newArray(int size) {
8555            return new ActivityIntentInfo[size];
8556        }
8557
8558        @Override
8559        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8560            if (!sUserManager.exists(userId)) return true;
8561            PackageParser.Package p = filter.activity.owner;
8562            if (p != null) {
8563                PackageSetting ps = (PackageSetting)p.mExtras;
8564                if (ps != null) {
8565                    // System apps are never considered stopped for purposes of
8566                    // filtering, because there may be no way for the user to
8567                    // actually re-launch them.
8568                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8569                            && ps.getStopped(userId);
8570                }
8571            }
8572            return false;
8573        }
8574
8575        @Override
8576        protected boolean isPackageForFilter(String packageName,
8577                PackageParser.ActivityIntentInfo info) {
8578            return packageName.equals(info.activity.owner.packageName);
8579        }
8580
8581        @Override
8582        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8583                int match, int userId) {
8584            if (!sUserManager.exists(userId)) return null;
8585            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8586                return null;
8587            }
8588            final PackageParser.Activity activity = info.activity;
8589            if (mSafeMode && (activity.info.applicationInfo.flags
8590                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8591                return null;
8592            }
8593            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8594            if (ps == null) {
8595                return null;
8596            }
8597            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8598                    ps.readUserState(userId), userId);
8599            if (ai == null) {
8600                return null;
8601            }
8602            final ResolveInfo res = new ResolveInfo();
8603            res.activityInfo = ai;
8604            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8605                res.filter = info;
8606            }
8607            if (info != null) {
8608                res.handleAllWebDataURI = info.handleAllWebDataURI();
8609            }
8610            res.priority = info.getPriority();
8611            res.preferredOrder = activity.owner.mPreferredOrder;
8612            //System.out.println("Result: " + res.activityInfo.className +
8613            //                   " = " + res.priority);
8614            res.match = match;
8615            res.isDefault = info.hasDefault;
8616            res.labelRes = info.labelRes;
8617            res.nonLocalizedLabel = info.nonLocalizedLabel;
8618            if (userNeedsBadging(userId)) {
8619                res.noResourceId = true;
8620            } else {
8621                res.icon = info.icon;
8622            }
8623            res.iconResourceId = info.icon;
8624            res.system = res.activityInfo.applicationInfo.isSystemApp();
8625            return res;
8626        }
8627
8628        @Override
8629        protected void sortResults(List<ResolveInfo> results) {
8630            Collections.sort(results, mResolvePrioritySorter);
8631        }
8632
8633        @Override
8634        protected void dumpFilter(PrintWriter out, String prefix,
8635                PackageParser.ActivityIntentInfo filter) {
8636            out.print(prefix); out.print(
8637                    Integer.toHexString(System.identityHashCode(filter.activity)));
8638                    out.print(' ');
8639                    filter.activity.printComponentShortName(out);
8640                    out.print(" filter ");
8641                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8642        }
8643
8644        @Override
8645        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8646            return filter.activity;
8647        }
8648
8649        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8650            PackageParser.Activity activity = (PackageParser.Activity)label;
8651            out.print(prefix); out.print(
8652                    Integer.toHexString(System.identityHashCode(activity)));
8653                    out.print(' ');
8654                    activity.printComponentShortName(out);
8655            if (count > 1) {
8656                out.print(" ("); out.print(count); out.print(" filters)");
8657            }
8658            out.println();
8659        }
8660
8661//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8662//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8663//            final List<ResolveInfo> retList = Lists.newArrayList();
8664//            while (i.hasNext()) {
8665//                final ResolveInfo resolveInfo = i.next();
8666//                if (isEnabledLP(resolveInfo.activityInfo)) {
8667//                    retList.add(resolveInfo);
8668//                }
8669//            }
8670//            return retList;
8671//        }
8672
8673        // Keys are String (activity class name), values are Activity.
8674        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8675                = new ArrayMap<ComponentName, PackageParser.Activity>();
8676        private int mFlags;
8677    }
8678
8679    private final class ServiceIntentResolver
8680            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8681        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8682                boolean defaultOnly, int userId) {
8683            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8684            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8685        }
8686
8687        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8688                int userId) {
8689            if (!sUserManager.exists(userId)) return null;
8690            mFlags = flags;
8691            return super.queryIntent(intent, resolvedType,
8692                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8693        }
8694
8695        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8696                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8697            if (!sUserManager.exists(userId)) return null;
8698            if (packageServices == null) {
8699                return null;
8700            }
8701            mFlags = flags;
8702            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8703            final int N = packageServices.size();
8704            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8705                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8706
8707            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8708            for (int i = 0; i < N; ++i) {
8709                intentFilters = packageServices.get(i).intents;
8710                if (intentFilters != null && intentFilters.size() > 0) {
8711                    PackageParser.ServiceIntentInfo[] array =
8712                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8713                    intentFilters.toArray(array);
8714                    listCut.add(array);
8715                }
8716            }
8717            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8718        }
8719
8720        public final void addService(PackageParser.Service s) {
8721            mServices.put(s.getComponentName(), s);
8722            if (DEBUG_SHOW_INFO) {
8723                Log.v(TAG, "  "
8724                        + (s.info.nonLocalizedLabel != null
8725                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8726                Log.v(TAG, "    Class=" + s.info.name);
8727            }
8728            final int NI = s.intents.size();
8729            int j;
8730            for (j=0; j<NI; j++) {
8731                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8732                if (DEBUG_SHOW_INFO) {
8733                    Log.v(TAG, "    IntentFilter:");
8734                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8735                }
8736                if (!intent.debugCheck()) {
8737                    Log.w(TAG, "==> For Service " + s.info.name);
8738                }
8739                addFilter(intent);
8740            }
8741        }
8742
8743        public final void removeService(PackageParser.Service s) {
8744            mServices.remove(s.getComponentName());
8745            if (DEBUG_SHOW_INFO) {
8746                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8747                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8748                Log.v(TAG, "    Class=" + s.info.name);
8749            }
8750            final int NI = s.intents.size();
8751            int j;
8752            for (j=0; j<NI; j++) {
8753                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8754                if (DEBUG_SHOW_INFO) {
8755                    Log.v(TAG, "    IntentFilter:");
8756                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8757                }
8758                removeFilter(intent);
8759            }
8760        }
8761
8762        @Override
8763        protected boolean allowFilterResult(
8764                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8765            ServiceInfo filterSi = filter.service.info;
8766            for (int i=dest.size()-1; i>=0; i--) {
8767                ServiceInfo destAi = dest.get(i).serviceInfo;
8768                if (destAi.name == filterSi.name
8769                        && destAi.packageName == filterSi.packageName) {
8770                    return false;
8771                }
8772            }
8773            return true;
8774        }
8775
8776        @Override
8777        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8778            return new PackageParser.ServiceIntentInfo[size];
8779        }
8780
8781        @Override
8782        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8783            if (!sUserManager.exists(userId)) return true;
8784            PackageParser.Package p = filter.service.owner;
8785            if (p != null) {
8786                PackageSetting ps = (PackageSetting)p.mExtras;
8787                if (ps != null) {
8788                    // System apps are never considered stopped for purposes of
8789                    // filtering, because there may be no way for the user to
8790                    // actually re-launch them.
8791                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8792                            && ps.getStopped(userId);
8793                }
8794            }
8795            return false;
8796        }
8797
8798        @Override
8799        protected boolean isPackageForFilter(String packageName,
8800                PackageParser.ServiceIntentInfo info) {
8801            return packageName.equals(info.service.owner.packageName);
8802        }
8803
8804        @Override
8805        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8806                int match, int userId) {
8807            if (!sUserManager.exists(userId)) return null;
8808            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8809            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8810                return null;
8811            }
8812            final PackageParser.Service service = info.service;
8813            if (mSafeMode && (service.info.applicationInfo.flags
8814                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8815                return null;
8816            }
8817            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8818            if (ps == null) {
8819                return null;
8820            }
8821            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8822                    ps.readUserState(userId), userId);
8823            if (si == null) {
8824                return null;
8825            }
8826            final ResolveInfo res = new ResolveInfo();
8827            res.serviceInfo = si;
8828            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8829                res.filter = filter;
8830            }
8831            res.priority = info.getPriority();
8832            res.preferredOrder = service.owner.mPreferredOrder;
8833            res.match = match;
8834            res.isDefault = info.hasDefault;
8835            res.labelRes = info.labelRes;
8836            res.nonLocalizedLabel = info.nonLocalizedLabel;
8837            res.icon = info.icon;
8838            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8839            return res;
8840        }
8841
8842        @Override
8843        protected void sortResults(List<ResolveInfo> results) {
8844            Collections.sort(results, mResolvePrioritySorter);
8845        }
8846
8847        @Override
8848        protected void dumpFilter(PrintWriter out, String prefix,
8849                PackageParser.ServiceIntentInfo filter) {
8850            out.print(prefix); out.print(
8851                    Integer.toHexString(System.identityHashCode(filter.service)));
8852                    out.print(' ');
8853                    filter.service.printComponentShortName(out);
8854                    out.print(" filter ");
8855                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8856        }
8857
8858        @Override
8859        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8860            return filter.service;
8861        }
8862
8863        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8864            PackageParser.Service service = (PackageParser.Service)label;
8865            out.print(prefix); out.print(
8866                    Integer.toHexString(System.identityHashCode(service)));
8867                    out.print(' ');
8868                    service.printComponentShortName(out);
8869            if (count > 1) {
8870                out.print(" ("); out.print(count); out.print(" filters)");
8871            }
8872            out.println();
8873        }
8874
8875//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8876//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8877//            final List<ResolveInfo> retList = Lists.newArrayList();
8878//            while (i.hasNext()) {
8879//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8880//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8881//                    retList.add(resolveInfo);
8882//                }
8883//            }
8884//            return retList;
8885//        }
8886
8887        // Keys are String (activity class name), values are Activity.
8888        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8889                = new ArrayMap<ComponentName, PackageParser.Service>();
8890        private int mFlags;
8891    };
8892
8893    private final class ProviderIntentResolver
8894            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8895        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8896                boolean defaultOnly, int userId) {
8897            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8898            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8899        }
8900
8901        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8902                int userId) {
8903            if (!sUserManager.exists(userId))
8904                return null;
8905            mFlags = flags;
8906            return super.queryIntent(intent, resolvedType,
8907                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8908        }
8909
8910        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8911                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8912            if (!sUserManager.exists(userId))
8913                return null;
8914            if (packageProviders == null) {
8915                return null;
8916            }
8917            mFlags = flags;
8918            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8919            final int N = packageProviders.size();
8920            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8921                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8922
8923            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8924            for (int i = 0; i < N; ++i) {
8925                intentFilters = packageProviders.get(i).intents;
8926                if (intentFilters != null && intentFilters.size() > 0) {
8927                    PackageParser.ProviderIntentInfo[] array =
8928                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8929                    intentFilters.toArray(array);
8930                    listCut.add(array);
8931                }
8932            }
8933            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8934        }
8935
8936        public final void addProvider(PackageParser.Provider p) {
8937            if (mProviders.containsKey(p.getComponentName())) {
8938                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8939                return;
8940            }
8941
8942            mProviders.put(p.getComponentName(), p);
8943            if (DEBUG_SHOW_INFO) {
8944                Log.v(TAG, "  "
8945                        + (p.info.nonLocalizedLabel != null
8946                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8947                Log.v(TAG, "    Class=" + p.info.name);
8948            }
8949            final int NI = p.intents.size();
8950            int j;
8951            for (j = 0; j < NI; j++) {
8952                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8953                if (DEBUG_SHOW_INFO) {
8954                    Log.v(TAG, "    IntentFilter:");
8955                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8956                }
8957                if (!intent.debugCheck()) {
8958                    Log.w(TAG, "==> For Provider " + p.info.name);
8959                }
8960                addFilter(intent);
8961            }
8962        }
8963
8964        public final void removeProvider(PackageParser.Provider p) {
8965            mProviders.remove(p.getComponentName());
8966            if (DEBUG_SHOW_INFO) {
8967                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8968                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8969                Log.v(TAG, "    Class=" + p.info.name);
8970            }
8971            final int NI = p.intents.size();
8972            int j;
8973            for (j = 0; j < NI; j++) {
8974                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8975                if (DEBUG_SHOW_INFO) {
8976                    Log.v(TAG, "    IntentFilter:");
8977                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8978                }
8979                removeFilter(intent);
8980            }
8981        }
8982
8983        @Override
8984        protected boolean allowFilterResult(
8985                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8986            ProviderInfo filterPi = filter.provider.info;
8987            for (int i = dest.size() - 1; i >= 0; i--) {
8988                ProviderInfo destPi = dest.get(i).providerInfo;
8989                if (destPi.name == filterPi.name
8990                        && destPi.packageName == filterPi.packageName) {
8991                    return false;
8992                }
8993            }
8994            return true;
8995        }
8996
8997        @Override
8998        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8999            return new PackageParser.ProviderIntentInfo[size];
9000        }
9001
9002        @Override
9003        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9004            if (!sUserManager.exists(userId))
9005                return true;
9006            PackageParser.Package p = filter.provider.owner;
9007            if (p != null) {
9008                PackageSetting ps = (PackageSetting) p.mExtras;
9009                if (ps != null) {
9010                    // System apps are never considered stopped for purposes of
9011                    // filtering, because there may be no way for the user to
9012                    // actually re-launch them.
9013                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9014                            && ps.getStopped(userId);
9015                }
9016            }
9017            return false;
9018        }
9019
9020        @Override
9021        protected boolean isPackageForFilter(String packageName,
9022                PackageParser.ProviderIntentInfo info) {
9023            return packageName.equals(info.provider.owner.packageName);
9024        }
9025
9026        @Override
9027        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9028                int match, int userId) {
9029            if (!sUserManager.exists(userId))
9030                return null;
9031            final PackageParser.ProviderIntentInfo info = filter;
9032            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9033                return null;
9034            }
9035            final PackageParser.Provider provider = info.provider;
9036            if (mSafeMode && (provider.info.applicationInfo.flags
9037                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9038                return null;
9039            }
9040            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9041            if (ps == null) {
9042                return null;
9043            }
9044            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9045                    ps.readUserState(userId), userId);
9046            if (pi == null) {
9047                return null;
9048            }
9049            final ResolveInfo res = new ResolveInfo();
9050            res.providerInfo = pi;
9051            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9052                res.filter = filter;
9053            }
9054            res.priority = info.getPriority();
9055            res.preferredOrder = provider.owner.mPreferredOrder;
9056            res.match = match;
9057            res.isDefault = info.hasDefault;
9058            res.labelRes = info.labelRes;
9059            res.nonLocalizedLabel = info.nonLocalizedLabel;
9060            res.icon = info.icon;
9061            res.system = res.providerInfo.applicationInfo.isSystemApp();
9062            return res;
9063        }
9064
9065        @Override
9066        protected void sortResults(List<ResolveInfo> results) {
9067            Collections.sort(results, mResolvePrioritySorter);
9068        }
9069
9070        @Override
9071        protected void dumpFilter(PrintWriter out, String prefix,
9072                PackageParser.ProviderIntentInfo filter) {
9073            out.print(prefix);
9074            out.print(
9075                    Integer.toHexString(System.identityHashCode(filter.provider)));
9076            out.print(' ');
9077            filter.provider.printComponentShortName(out);
9078            out.print(" filter ");
9079            out.println(Integer.toHexString(System.identityHashCode(filter)));
9080        }
9081
9082        @Override
9083        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9084            return filter.provider;
9085        }
9086
9087        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9088            PackageParser.Provider provider = (PackageParser.Provider)label;
9089            out.print(prefix); out.print(
9090                    Integer.toHexString(System.identityHashCode(provider)));
9091                    out.print(' ');
9092                    provider.printComponentShortName(out);
9093            if (count > 1) {
9094                out.print(" ("); out.print(count); out.print(" filters)");
9095            }
9096            out.println();
9097        }
9098
9099        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9100                = new ArrayMap<ComponentName, PackageParser.Provider>();
9101        private int mFlags;
9102    };
9103
9104    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9105            new Comparator<ResolveInfo>() {
9106        public int compare(ResolveInfo r1, ResolveInfo r2) {
9107            int v1 = r1.priority;
9108            int v2 = r2.priority;
9109            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9110            if (v1 != v2) {
9111                return (v1 > v2) ? -1 : 1;
9112            }
9113            v1 = r1.preferredOrder;
9114            v2 = r2.preferredOrder;
9115            if (v1 != v2) {
9116                return (v1 > v2) ? -1 : 1;
9117            }
9118            if (r1.isDefault != r2.isDefault) {
9119                return r1.isDefault ? -1 : 1;
9120            }
9121            v1 = r1.match;
9122            v2 = r2.match;
9123            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9124            if (v1 != v2) {
9125                return (v1 > v2) ? -1 : 1;
9126            }
9127            if (r1.system != r2.system) {
9128                return r1.system ? -1 : 1;
9129            }
9130            return 0;
9131        }
9132    };
9133
9134    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9135            new Comparator<ProviderInfo>() {
9136        public int compare(ProviderInfo p1, ProviderInfo p2) {
9137            final int v1 = p1.initOrder;
9138            final int v2 = p2.initOrder;
9139            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9140        }
9141    };
9142
9143    final void sendPackageBroadcast(final String action, final String pkg,
9144            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9145            final int[] userIds) {
9146        mHandler.post(new Runnable() {
9147            @Override
9148            public void run() {
9149                try {
9150                    final IActivityManager am = ActivityManagerNative.getDefault();
9151                    if (am == null) return;
9152                    final int[] resolvedUserIds;
9153                    if (userIds == null) {
9154                        resolvedUserIds = am.getRunningUserIds();
9155                    } else {
9156                        resolvedUserIds = userIds;
9157                    }
9158                    for (int id : resolvedUserIds) {
9159                        final Intent intent = new Intent(action,
9160                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9161                        if (extras != null) {
9162                            intent.putExtras(extras);
9163                        }
9164                        if (targetPkg != null) {
9165                            intent.setPackage(targetPkg);
9166                        }
9167                        // Modify the UID when posting to other users
9168                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9169                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9170                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9171                            intent.putExtra(Intent.EXTRA_UID, uid);
9172                        }
9173                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9174                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9175                        if (DEBUG_BROADCASTS) {
9176                            RuntimeException here = new RuntimeException("here");
9177                            here.fillInStackTrace();
9178                            Slog.d(TAG, "Sending to user " + id + ": "
9179                                    + intent.toShortString(false, true, false, false)
9180                                    + " " + intent.getExtras(), here);
9181                        }
9182                        am.broadcastIntent(null, intent, null, finishedReceiver,
9183                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9184                                null, finishedReceiver != null, false, id);
9185                    }
9186                } catch (RemoteException ex) {
9187                }
9188            }
9189        });
9190    }
9191
9192    /**
9193     * Check if the external storage media is available. This is true if there
9194     * is a mounted external storage medium or if the external storage is
9195     * emulated.
9196     */
9197    private boolean isExternalMediaAvailable() {
9198        return mMediaMounted || Environment.isExternalStorageEmulated();
9199    }
9200
9201    @Override
9202    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9203        // writer
9204        synchronized (mPackages) {
9205            if (!isExternalMediaAvailable()) {
9206                // If the external storage is no longer mounted at this point,
9207                // the caller may not have been able to delete all of this
9208                // packages files and can not delete any more.  Bail.
9209                return null;
9210            }
9211            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9212            if (lastPackage != null) {
9213                pkgs.remove(lastPackage);
9214            }
9215            if (pkgs.size() > 0) {
9216                return pkgs.get(0);
9217            }
9218        }
9219        return null;
9220    }
9221
9222    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9223        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9224                userId, andCode ? 1 : 0, packageName);
9225        if (mSystemReady) {
9226            msg.sendToTarget();
9227        } else {
9228            if (mPostSystemReadyMessages == null) {
9229                mPostSystemReadyMessages = new ArrayList<>();
9230            }
9231            mPostSystemReadyMessages.add(msg);
9232        }
9233    }
9234
9235    void startCleaningPackages() {
9236        // reader
9237        synchronized (mPackages) {
9238            if (!isExternalMediaAvailable()) {
9239                return;
9240            }
9241            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9242                return;
9243            }
9244        }
9245        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9246        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9247        IActivityManager am = ActivityManagerNative.getDefault();
9248        if (am != null) {
9249            try {
9250                am.startService(null, intent, null, mContext.getOpPackageName(),
9251                        UserHandle.USER_OWNER);
9252            } catch (RemoteException e) {
9253            }
9254        }
9255    }
9256
9257    @Override
9258    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9259            int installFlags, String installerPackageName, VerificationParams verificationParams,
9260            String packageAbiOverride) {
9261        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9262                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9263    }
9264
9265    @Override
9266    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9267            int installFlags, String installerPackageName, VerificationParams verificationParams,
9268            String packageAbiOverride, int userId) {
9269        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9270
9271        final int callingUid = Binder.getCallingUid();
9272        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9273
9274        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9275            try {
9276                if (observer != null) {
9277                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9278                }
9279            } catch (RemoteException re) {
9280            }
9281            return;
9282        }
9283
9284        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9285            installFlags |= PackageManager.INSTALL_FROM_ADB;
9286
9287        } else {
9288            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9289            // about installerPackageName.
9290
9291            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9292            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9293        }
9294
9295        UserHandle user;
9296        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9297            user = UserHandle.ALL;
9298        } else {
9299            user = new UserHandle(userId);
9300        }
9301
9302        // Only system components can circumvent runtime permissions when installing.
9303        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9304                && mContext.checkCallingOrSelfPermission(Manifest.permission
9305                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9306            throw new SecurityException("You need the "
9307                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9308                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9309        }
9310
9311        verificationParams.setInstallerUid(callingUid);
9312
9313        final File originFile = new File(originPath);
9314        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9315
9316        final Message msg = mHandler.obtainMessage(INIT_COPY);
9317        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9318                null, verificationParams, user, packageAbiOverride);
9319        mHandler.sendMessage(msg);
9320    }
9321
9322    void installStage(String packageName, File stagedDir, String stagedCid,
9323            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9324            String installerPackageName, int installerUid, UserHandle user) {
9325        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9326                params.referrerUri, installerUid, null);
9327        verifParams.setInstallerUid(installerUid);
9328
9329        final OriginInfo origin;
9330        if (stagedDir != null) {
9331            origin = OriginInfo.fromStagedFile(stagedDir);
9332        } else {
9333            origin = OriginInfo.fromStagedContainer(stagedCid);
9334        }
9335
9336        final Message msg = mHandler.obtainMessage(INIT_COPY);
9337        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9338                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9339        mHandler.sendMessage(msg);
9340    }
9341
9342    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9343        Bundle extras = new Bundle(1);
9344        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9345
9346        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9347                packageName, extras, null, null, new int[] {userId});
9348        try {
9349            IActivityManager am = ActivityManagerNative.getDefault();
9350            final boolean isSystem =
9351                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9352            if (isSystem && am.isUserRunning(userId, false)) {
9353                // The just-installed/enabled app is bundled on the system, so presumed
9354                // to be able to run automatically without needing an explicit launch.
9355                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9356                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9357                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9358                        .setPackage(packageName);
9359                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9360                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9361            }
9362        } catch (RemoteException e) {
9363            // shouldn't happen
9364            Slog.w(TAG, "Unable to bootstrap installed package", e);
9365        }
9366    }
9367
9368    @Override
9369    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9370            int userId) {
9371        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9372        PackageSetting pkgSetting;
9373        final int uid = Binder.getCallingUid();
9374        enforceCrossUserPermission(uid, userId, true, true,
9375                "setApplicationHiddenSetting for user " + userId);
9376
9377        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9378            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9379            return false;
9380        }
9381
9382        long callingId = Binder.clearCallingIdentity();
9383        try {
9384            boolean sendAdded = false;
9385            boolean sendRemoved = false;
9386            // writer
9387            synchronized (mPackages) {
9388                pkgSetting = mSettings.mPackages.get(packageName);
9389                if (pkgSetting == null) {
9390                    return false;
9391                }
9392                if (pkgSetting.getHidden(userId) != hidden) {
9393                    pkgSetting.setHidden(hidden, userId);
9394                    mSettings.writePackageRestrictionsLPr(userId);
9395                    if (hidden) {
9396                        sendRemoved = true;
9397                    } else {
9398                        sendAdded = true;
9399                    }
9400                }
9401            }
9402            if (sendAdded) {
9403                sendPackageAddedForUser(packageName, pkgSetting, userId);
9404                return true;
9405            }
9406            if (sendRemoved) {
9407                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9408                        "hiding pkg");
9409                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9410            }
9411        } finally {
9412            Binder.restoreCallingIdentity(callingId);
9413        }
9414        return false;
9415    }
9416
9417    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9418            int userId) {
9419        final PackageRemovedInfo info = new PackageRemovedInfo();
9420        info.removedPackage = packageName;
9421        info.removedUsers = new int[] {userId};
9422        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9423        info.sendBroadcast(false, false, false);
9424    }
9425
9426    /**
9427     * Returns true if application is not found or there was an error. Otherwise it returns
9428     * the hidden state of the package for the given user.
9429     */
9430    @Override
9431    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9432        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9433        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9434                false, "getApplicationHidden for user " + userId);
9435        PackageSetting pkgSetting;
9436        long callingId = Binder.clearCallingIdentity();
9437        try {
9438            // writer
9439            synchronized (mPackages) {
9440                pkgSetting = mSettings.mPackages.get(packageName);
9441                if (pkgSetting == null) {
9442                    return true;
9443                }
9444                return pkgSetting.getHidden(userId);
9445            }
9446        } finally {
9447            Binder.restoreCallingIdentity(callingId);
9448        }
9449    }
9450
9451    /**
9452     * @hide
9453     */
9454    @Override
9455    public int installExistingPackageAsUser(String packageName, int userId) {
9456        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9457                null);
9458        PackageSetting pkgSetting;
9459        final int uid = Binder.getCallingUid();
9460        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9461                + userId);
9462        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9463            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9464        }
9465
9466        long callingId = Binder.clearCallingIdentity();
9467        try {
9468            boolean sendAdded = false;
9469
9470            // writer
9471            synchronized (mPackages) {
9472                pkgSetting = mSettings.mPackages.get(packageName);
9473                if (pkgSetting == null) {
9474                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9475                }
9476                if (!pkgSetting.getInstalled(userId)) {
9477                    pkgSetting.setInstalled(true, userId);
9478                    pkgSetting.setHidden(false, userId);
9479                    mSettings.writePackageRestrictionsLPr(userId);
9480                    sendAdded = true;
9481                }
9482            }
9483
9484            if (sendAdded) {
9485                sendPackageAddedForUser(packageName, pkgSetting, userId);
9486            }
9487        } finally {
9488            Binder.restoreCallingIdentity(callingId);
9489        }
9490
9491        return PackageManager.INSTALL_SUCCEEDED;
9492    }
9493
9494    boolean isUserRestricted(int userId, String restrictionKey) {
9495        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9496        if (restrictions.getBoolean(restrictionKey, false)) {
9497            Log.w(TAG, "User is restricted: " + restrictionKey);
9498            return true;
9499        }
9500        return false;
9501    }
9502
9503    @Override
9504    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9505        mContext.enforceCallingOrSelfPermission(
9506                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9507                "Only package verification agents can verify applications");
9508
9509        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9510        final PackageVerificationResponse response = new PackageVerificationResponse(
9511                verificationCode, Binder.getCallingUid());
9512        msg.arg1 = id;
9513        msg.obj = response;
9514        mHandler.sendMessage(msg);
9515    }
9516
9517    @Override
9518    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9519            long millisecondsToDelay) {
9520        mContext.enforceCallingOrSelfPermission(
9521                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9522                "Only package verification agents can extend verification timeouts");
9523
9524        final PackageVerificationState state = mPendingVerification.get(id);
9525        final PackageVerificationResponse response = new PackageVerificationResponse(
9526                verificationCodeAtTimeout, Binder.getCallingUid());
9527
9528        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9529            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9530        }
9531        if (millisecondsToDelay < 0) {
9532            millisecondsToDelay = 0;
9533        }
9534        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9535                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9536            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9537        }
9538
9539        if ((state != null) && !state.timeoutExtended()) {
9540            state.extendTimeout();
9541
9542            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9543            msg.arg1 = id;
9544            msg.obj = response;
9545            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9546        }
9547    }
9548
9549    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9550            int verificationCode, UserHandle user) {
9551        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9552        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9553        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9554        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9555        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9556
9557        mContext.sendBroadcastAsUser(intent, user,
9558                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9559    }
9560
9561    private ComponentName matchComponentForVerifier(String packageName,
9562            List<ResolveInfo> receivers) {
9563        ActivityInfo targetReceiver = null;
9564
9565        final int NR = receivers.size();
9566        for (int i = 0; i < NR; i++) {
9567            final ResolveInfo info = receivers.get(i);
9568            if (info.activityInfo == null) {
9569                continue;
9570            }
9571
9572            if (packageName.equals(info.activityInfo.packageName)) {
9573                targetReceiver = info.activityInfo;
9574                break;
9575            }
9576        }
9577
9578        if (targetReceiver == null) {
9579            return null;
9580        }
9581
9582        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9583    }
9584
9585    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9586            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9587        if (pkgInfo.verifiers.length == 0) {
9588            return null;
9589        }
9590
9591        final int N = pkgInfo.verifiers.length;
9592        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9593        for (int i = 0; i < N; i++) {
9594            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9595
9596            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9597                    receivers);
9598            if (comp == null) {
9599                continue;
9600            }
9601
9602            final int verifierUid = getUidForVerifier(verifierInfo);
9603            if (verifierUid == -1) {
9604                continue;
9605            }
9606
9607            if (DEBUG_VERIFY) {
9608                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9609                        + " with the correct signature");
9610            }
9611            sufficientVerifiers.add(comp);
9612            verificationState.addSufficientVerifier(verifierUid);
9613        }
9614
9615        return sufficientVerifiers;
9616    }
9617
9618    private int getUidForVerifier(VerifierInfo verifierInfo) {
9619        synchronized (mPackages) {
9620            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9621            if (pkg == null) {
9622                return -1;
9623            } else if (pkg.mSignatures.length != 1) {
9624                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9625                        + " has more than one signature; ignoring");
9626                return -1;
9627            }
9628
9629            /*
9630             * If the public key of the package's signature does not match
9631             * our expected public key, then this is a different package and
9632             * we should skip.
9633             */
9634
9635            final byte[] expectedPublicKey;
9636            try {
9637                final Signature verifierSig = pkg.mSignatures[0];
9638                final PublicKey publicKey = verifierSig.getPublicKey();
9639                expectedPublicKey = publicKey.getEncoded();
9640            } catch (CertificateException e) {
9641                return -1;
9642            }
9643
9644            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9645
9646            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9647                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9648                        + " does not have the expected public key; ignoring");
9649                return -1;
9650            }
9651
9652            return pkg.applicationInfo.uid;
9653        }
9654    }
9655
9656    @Override
9657    public void finishPackageInstall(int token) {
9658        enforceSystemOrRoot("Only the system is allowed to finish installs");
9659
9660        if (DEBUG_INSTALL) {
9661            Slog.v(TAG, "BM finishing package install for " + token);
9662        }
9663
9664        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9665        mHandler.sendMessage(msg);
9666    }
9667
9668    /**
9669     * Get the verification agent timeout.
9670     *
9671     * @return verification timeout in milliseconds
9672     */
9673    private long getVerificationTimeout() {
9674        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9675                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9676                DEFAULT_VERIFICATION_TIMEOUT);
9677    }
9678
9679    /**
9680     * Get the default verification agent response code.
9681     *
9682     * @return default verification response code
9683     */
9684    private int getDefaultVerificationResponse() {
9685        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9686                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9687                DEFAULT_VERIFICATION_RESPONSE);
9688    }
9689
9690    /**
9691     * Check whether or not package verification has been enabled.
9692     *
9693     * @return true if verification should be performed
9694     */
9695    private boolean isVerificationEnabled(int userId, int installFlags) {
9696        if (!DEFAULT_VERIFY_ENABLE) {
9697            return false;
9698        }
9699
9700        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9701
9702        // Check if installing from ADB
9703        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9704            // Do not run verification in a test harness environment
9705            if (ActivityManager.isRunningInTestHarness()) {
9706                return false;
9707            }
9708            if (ensureVerifyAppsEnabled) {
9709                return true;
9710            }
9711            // Check if the developer does not want package verification for ADB installs
9712            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9713                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9714                return false;
9715            }
9716        }
9717
9718        if (ensureVerifyAppsEnabled) {
9719            return true;
9720        }
9721
9722        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9723                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9724    }
9725
9726    @Override
9727    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9728            throws RemoteException {
9729        mContext.enforceCallingOrSelfPermission(
9730                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9731                "Only intentfilter verification agents can verify applications");
9732
9733        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9734        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9735                Binder.getCallingUid(), verificationCode, failedDomains);
9736        msg.arg1 = id;
9737        msg.obj = response;
9738        mHandler.sendMessage(msg);
9739    }
9740
9741    @Override
9742    public int getIntentVerificationStatus(String packageName, int userId) {
9743        synchronized (mPackages) {
9744            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9745        }
9746    }
9747
9748    @Override
9749    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9750        mContext.enforceCallingOrSelfPermission(
9751                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9752
9753        boolean result = false;
9754        synchronized (mPackages) {
9755            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9756        }
9757        if (result) {
9758            scheduleWritePackageRestrictionsLocked(userId);
9759        }
9760        return result;
9761    }
9762
9763    @Override
9764    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9765        synchronized (mPackages) {
9766            return mSettings.getIntentFilterVerificationsLPr(packageName);
9767        }
9768    }
9769
9770    @Override
9771    public List<IntentFilter> getAllIntentFilters(String packageName) {
9772        if (TextUtils.isEmpty(packageName)) {
9773            return Collections.<IntentFilter>emptyList();
9774        }
9775        synchronized (mPackages) {
9776            PackageParser.Package pkg = mPackages.get(packageName);
9777            if (pkg == null || pkg.activities == null) {
9778                return Collections.<IntentFilter>emptyList();
9779            }
9780            final int count = pkg.activities.size();
9781            ArrayList<IntentFilter> result = new ArrayList<>();
9782            for (int n=0; n<count; n++) {
9783                PackageParser.Activity activity = pkg.activities.get(n);
9784                if (activity.intents != null || activity.intents.size() > 0) {
9785                    result.addAll(activity.intents);
9786                }
9787            }
9788            return result;
9789        }
9790    }
9791
9792    @Override
9793    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9794        mContext.enforceCallingOrSelfPermission(
9795                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9796
9797        synchronized (mPackages) {
9798            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9799            if (packageName != null) {
9800                result |= updateIntentVerificationStatus(packageName,
9801                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9802                        UserHandle.myUserId());
9803                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9804                        packageName, userId);
9805            }
9806            return result;
9807        }
9808    }
9809
9810    @Override
9811    public String getDefaultBrowserPackageName(int userId) {
9812        synchronized (mPackages) {
9813            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9814        }
9815    }
9816
9817    /**
9818     * Get the "allow unknown sources" setting.
9819     *
9820     * @return the current "allow unknown sources" setting
9821     */
9822    private int getUnknownSourcesSettings() {
9823        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9824                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9825                -1);
9826    }
9827
9828    @Override
9829    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9830        final int uid = Binder.getCallingUid();
9831        // writer
9832        synchronized (mPackages) {
9833            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9834            if (targetPackageSetting == null) {
9835                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9836            }
9837
9838            PackageSetting installerPackageSetting;
9839            if (installerPackageName != null) {
9840                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9841                if (installerPackageSetting == null) {
9842                    throw new IllegalArgumentException("Unknown installer package: "
9843                            + installerPackageName);
9844                }
9845            } else {
9846                installerPackageSetting = null;
9847            }
9848
9849            Signature[] callerSignature;
9850            Object obj = mSettings.getUserIdLPr(uid);
9851            if (obj != null) {
9852                if (obj instanceof SharedUserSetting) {
9853                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9854                } else if (obj instanceof PackageSetting) {
9855                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9856                } else {
9857                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9858                }
9859            } else {
9860                throw new SecurityException("Unknown calling uid " + uid);
9861            }
9862
9863            // Verify: can't set installerPackageName to a package that is
9864            // not signed with the same cert as the caller.
9865            if (installerPackageSetting != null) {
9866                if (compareSignatures(callerSignature,
9867                        installerPackageSetting.signatures.mSignatures)
9868                        != PackageManager.SIGNATURE_MATCH) {
9869                    throw new SecurityException(
9870                            "Caller does not have same cert as new installer package "
9871                            + installerPackageName);
9872                }
9873            }
9874
9875            // Verify: if target already has an installer package, it must
9876            // be signed with the same cert as the caller.
9877            if (targetPackageSetting.installerPackageName != null) {
9878                PackageSetting setting = mSettings.mPackages.get(
9879                        targetPackageSetting.installerPackageName);
9880                // If the currently set package isn't valid, then it's always
9881                // okay to change it.
9882                if (setting != null) {
9883                    if (compareSignatures(callerSignature,
9884                            setting.signatures.mSignatures)
9885                            != PackageManager.SIGNATURE_MATCH) {
9886                        throw new SecurityException(
9887                                "Caller does not have same cert as old installer package "
9888                                + targetPackageSetting.installerPackageName);
9889                    }
9890                }
9891            }
9892
9893            // Okay!
9894            targetPackageSetting.installerPackageName = installerPackageName;
9895            scheduleWriteSettingsLocked();
9896        }
9897    }
9898
9899    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9900        // Queue up an async operation since the package installation may take a little while.
9901        mHandler.post(new Runnable() {
9902            public void run() {
9903                mHandler.removeCallbacks(this);
9904                 // Result object to be returned
9905                PackageInstalledInfo res = new PackageInstalledInfo();
9906                res.returnCode = currentStatus;
9907                res.uid = -1;
9908                res.pkg = null;
9909                res.removedInfo = new PackageRemovedInfo();
9910                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9911                    args.doPreInstall(res.returnCode);
9912                    synchronized (mInstallLock) {
9913                        installPackageLI(args, res);
9914                    }
9915                    args.doPostInstall(res.returnCode, res.uid);
9916                }
9917
9918                // A restore should be performed at this point if (a) the install
9919                // succeeded, (b) the operation is not an update, and (c) the new
9920                // package has not opted out of backup participation.
9921                final boolean update = res.removedInfo.removedPackage != null;
9922                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9923                boolean doRestore = !update
9924                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9925
9926                // Set up the post-install work request bookkeeping.  This will be used
9927                // and cleaned up by the post-install event handling regardless of whether
9928                // there's a restore pass performed.  Token values are >= 1.
9929                int token;
9930                if (mNextInstallToken < 0) mNextInstallToken = 1;
9931                token = mNextInstallToken++;
9932
9933                PostInstallData data = new PostInstallData(args, res);
9934                mRunningInstalls.put(token, data);
9935                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9936
9937                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9938                    // Pass responsibility to the Backup Manager.  It will perform a
9939                    // restore if appropriate, then pass responsibility back to the
9940                    // Package Manager to run the post-install observer callbacks
9941                    // and broadcasts.
9942                    IBackupManager bm = IBackupManager.Stub.asInterface(
9943                            ServiceManager.getService(Context.BACKUP_SERVICE));
9944                    if (bm != null) {
9945                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9946                                + " to BM for possible restore");
9947                        try {
9948                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9949                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9950                            } else {
9951                                doRestore = false;
9952                            }
9953                        } catch (RemoteException e) {
9954                            // can't happen; the backup manager is local
9955                        } catch (Exception e) {
9956                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9957                            doRestore = false;
9958                        }
9959                    } else {
9960                        Slog.e(TAG, "Backup Manager not found!");
9961                        doRestore = false;
9962                    }
9963                }
9964
9965                if (!doRestore) {
9966                    // No restore possible, or the Backup Manager was mysteriously not
9967                    // available -- just fire the post-install work request directly.
9968                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9969                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9970                    mHandler.sendMessage(msg);
9971                }
9972            }
9973        });
9974    }
9975
9976    private abstract class HandlerParams {
9977        private static final int MAX_RETRIES = 4;
9978
9979        /**
9980         * Number of times startCopy() has been attempted and had a non-fatal
9981         * error.
9982         */
9983        private int mRetries = 0;
9984
9985        /** User handle for the user requesting the information or installation. */
9986        private final UserHandle mUser;
9987
9988        HandlerParams(UserHandle user) {
9989            mUser = user;
9990        }
9991
9992        UserHandle getUser() {
9993            return mUser;
9994        }
9995
9996        final boolean startCopy() {
9997            boolean res;
9998            try {
9999                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10000
10001                if (++mRetries > MAX_RETRIES) {
10002                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10003                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10004                    handleServiceError();
10005                    return false;
10006                } else {
10007                    handleStartCopy();
10008                    res = true;
10009                }
10010            } catch (RemoteException e) {
10011                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10012                mHandler.sendEmptyMessage(MCS_RECONNECT);
10013                res = false;
10014            }
10015            handleReturnCode();
10016            return res;
10017        }
10018
10019        final void serviceError() {
10020            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10021            handleServiceError();
10022            handleReturnCode();
10023        }
10024
10025        abstract void handleStartCopy() throws RemoteException;
10026        abstract void handleServiceError();
10027        abstract void handleReturnCode();
10028    }
10029
10030    class MeasureParams extends HandlerParams {
10031        private final PackageStats mStats;
10032        private boolean mSuccess;
10033
10034        private final IPackageStatsObserver mObserver;
10035
10036        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10037            super(new UserHandle(stats.userHandle));
10038            mObserver = observer;
10039            mStats = stats;
10040        }
10041
10042        @Override
10043        public String toString() {
10044            return "MeasureParams{"
10045                + Integer.toHexString(System.identityHashCode(this))
10046                + " " + mStats.packageName + "}";
10047        }
10048
10049        @Override
10050        void handleStartCopy() throws RemoteException {
10051            synchronized (mInstallLock) {
10052                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10053            }
10054
10055            if (mSuccess) {
10056                final boolean mounted;
10057                if (Environment.isExternalStorageEmulated()) {
10058                    mounted = true;
10059                } else {
10060                    final String status = Environment.getExternalStorageState();
10061                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10062                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10063                }
10064
10065                if (mounted) {
10066                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10067
10068                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10069                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10070
10071                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10072                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10073
10074                    // Always subtract cache size, since it's a subdirectory
10075                    mStats.externalDataSize -= mStats.externalCacheSize;
10076
10077                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10078                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10079
10080                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10081                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10082                }
10083            }
10084        }
10085
10086        @Override
10087        void handleReturnCode() {
10088            if (mObserver != null) {
10089                try {
10090                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10091                } catch (RemoteException e) {
10092                    Slog.i(TAG, "Observer no longer exists.");
10093                }
10094            }
10095        }
10096
10097        @Override
10098        void handleServiceError() {
10099            Slog.e(TAG, "Could not measure application " + mStats.packageName
10100                            + " external storage");
10101        }
10102    }
10103
10104    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10105            throws RemoteException {
10106        long result = 0;
10107        for (File path : paths) {
10108            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10109        }
10110        return result;
10111    }
10112
10113    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10114        for (File path : paths) {
10115            try {
10116                mcs.clearDirectory(path.getAbsolutePath());
10117            } catch (RemoteException e) {
10118            }
10119        }
10120    }
10121
10122    static class OriginInfo {
10123        /**
10124         * Location where install is coming from, before it has been
10125         * copied/renamed into place. This could be a single monolithic APK
10126         * file, or a cluster directory. This location may be untrusted.
10127         */
10128        final File file;
10129        final String cid;
10130
10131        /**
10132         * Flag indicating that {@link #file} or {@link #cid} has already been
10133         * staged, meaning downstream users don't need to defensively copy the
10134         * contents.
10135         */
10136        final boolean staged;
10137
10138        /**
10139         * Flag indicating that {@link #file} or {@link #cid} is an already
10140         * installed app that is being moved.
10141         */
10142        final boolean existing;
10143
10144        final String resolvedPath;
10145        final File resolvedFile;
10146
10147        static OriginInfo fromNothing() {
10148            return new OriginInfo(null, null, false, false);
10149        }
10150
10151        static OriginInfo fromUntrustedFile(File file) {
10152            return new OriginInfo(file, null, false, false);
10153        }
10154
10155        static OriginInfo fromExistingFile(File file) {
10156            return new OriginInfo(file, null, false, true);
10157        }
10158
10159        static OriginInfo fromStagedFile(File file) {
10160            return new OriginInfo(file, null, true, false);
10161        }
10162
10163        static OriginInfo fromStagedContainer(String cid) {
10164            return new OriginInfo(null, cid, true, false);
10165        }
10166
10167        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10168            this.file = file;
10169            this.cid = cid;
10170            this.staged = staged;
10171            this.existing = existing;
10172
10173            if (cid != null) {
10174                resolvedPath = PackageHelper.getSdDir(cid);
10175                resolvedFile = new File(resolvedPath);
10176            } else if (file != null) {
10177                resolvedPath = file.getAbsolutePath();
10178                resolvedFile = file;
10179            } else {
10180                resolvedPath = null;
10181                resolvedFile = null;
10182            }
10183        }
10184    }
10185
10186    class MoveInfo {
10187        final int moveId;
10188        final String fromUuid;
10189        final String toUuid;
10190        final String packageName;
10191        final String dataAppName;
10192        final int appId;
10193        final String seinfo;
10194
10195        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10196                String dataAppName, int appId, String seinfo) {
10197            this.moveId = moveId;
10198            this.fromUuid = fromUuid;
10199            this.toUuid = toUuid;
10200            this.packageName = packageName;
10201            this.dataAppName = dataAppName;
10202            this.appId = appId;
10203            this.seinfo = seinfo;
10204        }
10205    }
10206
10207    class InstallParams extends HandlerParams {
10208        final OriginInfo origin;
10209        final MoveInfo move;
10210        final IPackageInstallObserver2 observer;
10211        int installFlags;
10212        final String installerPackageName;
10213        final String volumeUuid;
10214        final VerificationParams verificationParams;
10215        private InstallArgs mArgs;
10216        private int mRet;
10217        final String packageAbiOverride;
10218
10219        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10220                int installFlags, String installerPackageName, String volumeUuid,
10221                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10222            super(user);
10223            this.origin = origin;
10224            this.move = move;
10225            this.observer = observer;
10226            this.installFlags = installFlags;
10227            this.installerPackageName = installerPackageName;
10228            this.volumeUuid = volumeUuid;
10229            this.verificationParams = verificationParams;
10230            this.packageAbiOverride = packageAbiOverride;
10231        }
10232
10233        @Override
10234        public String toString() {
10235            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10236                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10237        }
10238
10239        public ManifestDigest getManifestDigest() {
10240            if (verificationParams == null) {
10241                return null;
10242            }
10243            return verificationParams.getManifestDigest();
10244        }
10245
10246        private int installLocationPolicy(PackageInfoLite pkgLite) {
10247            String packageName = pkgLite.packageName;
10248            int installLocation = pkgLite.installLocation;
10249            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10250            // reader
10251            synchronized (mPackages) {
10252                PackageParser.Package pkg = mPackages.get(packageName);
10253                if (pkg != null) {
10254                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10255                        // Check for downgrading.
10256                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10257                            try {
10258                                checkDowngrade(pkg, pkgLite);
10259                            } catch (PackageManagerException e) {
10260                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10261                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10262                            }
10263                        }
10264                        // Check for updated system application.
10265                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10266                            if (onSd) {
10267                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10268                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10269                            }
10270                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10271                        } else {
10272                            if (onSd) {
10273                                // Install flag overrides everything.
10274                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10275                            }
10276                            // If current upgrade specifies particular preference
10277                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10278                                // Application explicitly specified internal.
10279                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10280                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10281                                // App explictly prefers external. Let policy decide
10282                            } else {
10283                                // Prefer previous location
10284                                if (isExternal(pkg)) {
10285                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10286                                }
10287                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10288                            }
10289                        }
10290                    } else {
10291                        // Invalid install. Return error code
10292                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10293                    }
10294                }
10295            }
10296            // All the special cases have been taken care of.
10297            // Return result based on recommended install location.
10298            if (onSd) {
10299                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10300            }
10301            return pkgLite.recommendedInstallLocation;
10302        }
10303
10304        /*
10305         * Invoke remote method to get package information and install
10306         * location values. Override install location based on default
10307         * policy if needed and then create install arguments based
10308         * on the install location.
10309         */
10310        public void handleStartCopy() throws RemoteException {
10311            int ret = PackageManager.INSTALL_SUCCEEDED;
10312
10313            // If we're already staged, we've firmly committed to an install location
10314            if (origin.staged) {
10315                if (origin.file != null) {
10316                    installFlags |= PackageManager.INSTALL_INTERNAL;
10317                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10318                } else if (origin.cid != null) {
10319                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10320                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10321                } else {
10322                    throw new IllegalStateException("Invalid stage location");
10323                }
10324            }
10325
10326            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10327            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10328
10329            PackageInfoLite pkgLite = null;
10330
10331            if (onInt && onSd) {
10332                // Check if both bits are set.
10333                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10334                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10335            } else {
10336                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10337                        packageAbiOverride);
10338
10339                /*
10340                 * If we have too little free space, try to free cache
10341                 * before giving up.
10342                 */
10343                if (!origin.staged && pkgLite.recommendedInstallLocation
10344                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10345                    // TODO: focus freeing disk space on the target device
10346                    final StorageManager storage = StorageManager.from(mContext);
10347                    final long lowThreshold = storage.getStorageLowBytes(
10348                            Environment.getDataDirectory());
10349
10350                    final long sizeBytes = mContainerService.calculateInstalledSize(
10351                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10352
10353                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10354                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10355                                installFlags, packageAbiOverride);
10356                    }
10357
10358                    /*
10359                     * The cache free must have deleted the file we
10360                     * downloaded to install.
10361                     *
10362                     * TODO: fix the "freeCache" call to not delete
10363                     *       the file we care about.
10364                     */
10365                    if (pkgLite.recommendedInstallLocation
10366                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10367                        pkgLite.recommendedInstallLocation
10368                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10369                    }
10370                }
10371            }
10372
10373            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10374                int loc = pkgLite.recommendedInstallLocation;
10375                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10376                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10377                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10378                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10379                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10380                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10381                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10382                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10383                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10384                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10385                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10386                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10387                } else {
10388                    // Override with defaults if needed.
10389                    loc = installLocationPolicy(pkgLite);
10390                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10391                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10392                    } else if (!onSd && !onInt) {
10393                        // Override install location with flags
10394                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10395                            // Set the flag to install on external media.
10396                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10397                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10398                        } else {
10399                            // Make sure the flag for installing on external
10400                            // media is unset
10401                            installFlags |= PackageManager.INSTALL_INTERNAL;
10402                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10403                        }
10404                    }
10405                }
10406            }
10407
10408            final InstallArgs args = createInstallArgs(this);
10409            mArgs = args;
10410
10411            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10412                 /*
10413                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10414                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10415                 */
10416                int userIdentifier = getUser().getIdentifier();
10417                if (userIdentifier == UserHandle.USER_ALL
10418                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10419                    userIdentifier = UserHandle.USER_OWNER;
10420                }
10421
10422                /*
10423                 * Determine if we have any installed package verifiers. If we
10424                 * do, then we'll defer to them to verify the packages.
10425                 */
10426                final int requiredUid = mRequiredVerifierPackage == null ? -1
10427                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10428                if (!origin.existing && requiredUid != -1
10429                        && isVerificationEnabled(userIdentifier, installFlags)) {
10430                    final Intent verification = new Intent(
10431                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10432                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10433                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10434                            PACKAGE_MIME_TYPE);
10435                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10436
10437                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10438                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10439                            0 /* TODO: Which userId? */);
10440
10441                    if (DEBUG_VERIFY) {
10442                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10443                                + verification.toString() + " with " + pkgLite.verifiers.length
10444                                + " optional verifiers");
10445                    }
10446
10447                    final int verificationId = mPendingVerificationToken++;
10448
10449                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10450
10451                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10452                            installerPackageName);
10453
10454                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10455                            installFlags);
10456
10457                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10458                            pkgLite.packageName);
10459
10460                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10461                            pkgLite.versionCode);
10462
10463                    if (verificationParams != null) {
10464                        if (verificationParams.getVerificationURI() != null) {
10465                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10466                                 verificationParams.getVerificationURI());
10467                        }
10468                        if (verificationParams.getOriginatingURI() != null) {
10469                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10470                                  verificationParams.getOriginatingURI());
10471                        }
10472                        if (verificationParams.getReferrer() != null) {
10473                            verification.putExtra(Intent.EXTRA_REFERRER,
10474                                  verificationParams.getReferrer());
10475                        }
10476                        if (verificationParams.getOriginatingUid() >= 0) {
10477                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10478                                  verificationParams.getOriginatingUid());
10479                        }
10480                        if (verificationParams.getInstallerUid() >= 0) {
10481                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10482                                  verificationParams.getInstallerUid());
10483                        }
10484                    }
10485
10486                    final PackageVerificationState verificationState = new PackageVerificationState(
10487                            requiredUid, args);
10488
10489                    mPendingVerification.append(verificationId, verificationState);
10490
10491                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10492                            receivers, verificationState);
10493
10494                    /*
10495                     * If any sufficient verifiers were listed in the package
10496                     * manifest, attempt to ask them.
10497                     */
10498                    if (sufficientVerifiers != null) {
10499                        final int N = sufficientVerifiers.size();
10500                        if (N == 0) {
10501                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10502                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10503                        } else {
10504                            for (int i = 0; i < N; i++) {
10505                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10506
10507                                final Intent sufficientIntent = new Intent(verification);
10508                                sufficientIntent.setComponent(verifierComponent);
10509
10510                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10511                            }
10512                        }
10513                    }
10514
10515                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10516                            mRequiredVerifierPackage, receivers);
10517                    if (ret == PackageManager.INSTALL_SUCCEEDED
10518                            && mRequiredVerifierPackage != null) {
10519                        /*
10520                         * Send the intent to the required verification agent,
10521                         * but only start the verification timeout after the
10522                         * target BroadcastReceivers have run.
10523                         */
10524                        verification.setComponent(requiredVerifierComponent);
10525                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10526                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10527                                new BroadcastReceiver() {
10528                                    @Override
10529                                    public void onReceive(Context context, Intent intent) {
10530                                        final Message msg = mHandler
10531                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10532                                        msg.arg1 = verificationId;
10533                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10534                                    }
10535                                }, null, 0, null, null);
10536
10537                        /*
10538                         * We don't want the copy to proceed until verification
10539                         * succeeds, so null out this field.
10540                         */
10541                        mArgs = null;
10542                    }
10543                } else {
10544                    /*
10545                     * No package verification is enabled, so immediately start
10546                     * the remote call to initiate copy using temporary file.
10547                     */
10548                    ret = args.copyApk(mContainerService, true);
10549                }
10550            }
10551
10552            mRet = ret;
10553        }
10554
10555        @Override
10556        void handleReturnCode() {
10557            // If mArgs is null, then MCS couldn't be reached. When it
10558            // reconnects, it will try again to install. At that point, this
10559            // will succeed.
10560            if (mArgs != null) {
10561                processPendingInstall(mArgs, mRet);
10562            }
10563        }
10564
10565        @Override
10566        void handleServiceError() {
10567            mArgs = createInstallArgs(this);
10568            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10569        }
10570
10571        public boolean isForwardLocked() {
10572            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10573        }
10574    }
10575
10576    /**
10577     * Used during creation of InstallArgs
10578     *
10579     * @param installFlags package installation flags
10580     * @return true if should be installed on external storage
10581     */
10582    private static boolean installOnExternalAsec(int installFlags) {
10583        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10584            return false;
10585        }
10586        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10587            return true;
10588        }
10589        return false;
10590    }
10591
10592    /**
10593     * Used during creation of InstallArgs
10594     *
10595     * @param installFlags package installation flags
10596     * @return true if should be installed as forward locked
10597     */
10598    private static boolean installForwardLocked(int installFlags) {
10599        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10600    }
10601
10602    private InstallArgs createInstallArgs(InstallParams params) {
10603        if (params.move != null) {
10604            return new MoveInstallArgs(params);
10605        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10606            return new AsecInstallArgs(params);
10607        } else {
10608            return new FileInstallArgs(params);
10609        }
10610    }
10611
10612    /**
10613     * Create args that describe an existing installed package. Typically used
10614     * when cleaning up old installs, or used as a move source.
10615     */
10616    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10617            String resourcePath, String[] instructionSets) {
10618        final boolean isInAsec;
10619        if (installOnExternalAsec(installFlags)) {
10620            /* Apps on SD card are always in ASEC containers. */
10621            isInAsec = true;
10622        } else if (installForwardLocked(installFlags)
10623                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10624            /*
10625             * Forward-locked apps are only in ASEC containers if they're the
10626             * new style
10627             */
10628            isInAsec = true;
10629        } else {
10630            isInAsec = false;
10631        }
10632
10633        if (isInAsec) {
10634            return new AsecInstallArgs(codePath, instructionSets,
10635                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10636        } else {
10637            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10638        }
10639    }
10640
10641    static abstract class InstallArgs {
10642        /** @see InstallParams#origin */
10643        final OriginInfo origin;
10644        /** @see InstallParams#move */
10645        final MoveInfo move;
10646
10647        final IPackageInstallObserver2 observer;
10648        // Always refers to PackageManager flags only
10649        final int installFlags;
10650        final String installerPackageName;
10651        final String volumeUuid;
10652        final ManifestDigest manifestDigest;
10653        final UserHandle user;
10654        final String abiOverride;
10655
10656        // The list of instruction sets supported by this app. This is currently
10657        // only used during the rmdex() phase to clean up resources. We can get rid of this
10658        // if we move dex files under the common app path.
10659        /* nullable */ String[] instructionSets;
10660
10661        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10662                int installFlags, String installerPackageName, String volumeUuid,
10663                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10664                String abiOverride) {
10665            this.origin = origin;
10666            this.move = move;
10667            this.installFlags = installFlags;
10668            this.observer = observer;
10669            this.installerPackageName = installerPackageName;
10670            this.volumeUuid = volumeUuid;
10671            this.manifestDigest = manifestDigest;
10672            this.user = user;
10673            this.instructionSets = instructionSets;
10674            this.abiOverride = abiOverride;
10675        }
10676
10677        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10678        abstract int doPreInstall(int status);
10679
10680        /**
10681         * Rename package into final resting place. All paths on the given
10682         * scanned package should be updated to reflect the rename.
10683         */
10684        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10685        abstract int doPostInstall(int status, int uid);
10686
10687        /** @see PackageSettingBase#codePathString */
10688        abstract String getCodePath();
10689        /** @see PackageSettingBase#resourcePathString */
10690        abstract String getResourcePath();
10691
10692        // Need installer lock especially for dex file removal.
10693        abstract void cleanUpResourcesLI();
10694        abstract boolean doPostDeleteLI(boolean delete);
10695
10696        /**
10697         * Called before the source arguments are copied. This is used mostly
10698         * for MoveParams when it needs to read the source file to put it in the
10699         * destination.
10700         */
10701        int doPreCopy() {
10702            return PackageManager.INSTALL_SUCCEEDED;
10703        }
10704
10705        /**
10706         * Called after the source arguments are copied. This is used mostly for
10707         * MoveParams when it needs to read the source file to put it in the
10708         * destination.
10709         *
10710         * @return
10711         */
10712        int doPostCopy(int uid) {
10713            return PackageManager.INSTALL_SUCCEEDED;
10714        }
10715
10716        protected boolean isFwdLocked() {
10717            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10718        }
10719
10720        protected boolean isExternalAsec() {
10721            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10722        }
10723
10724        UserHandle getUser() {
10725            return user;
10726        }
10727    }
10728
10729    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10730        if (!allCodePaths.isEmpty()) {
10731            if (instructionSets == null) {
10732                throw new IllegalStateException("instructionSet == null");
10733            }
10734            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10735            for (String codePath : allCodePaths) {
10736                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10737                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10738                    if (retCode < 0) {
10739                        Slog.w(TAG, "Couldn't remove dex file for package: "
10740                                + " at location " + codePath + ", retcode=" + retCode);
10741                        // we don't consider this to be a failure of the core package deletion
10742                    }
10743                }
10744            }
10745        }
10746    }
10747
10748    /**
10749     * Logic to handle installation of non-ASEC applications, including copying
10750     * and renaming logic.
10751     */
10752    class FileInstallArgs extends InstallArgs {
10753        private File codeFile;
10754        private File resourceFile;
10755
10756        // Example topology:
10757        // /data/app/com.example/base.apk
10758        // /data/app/com.example/split_foo.apk
10759        // /data/app/com.example/lib/arm/libfoo.so
10760        // /data/app/com.example/lib/arm64/libfoo.so
10761        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10762
10763        /** New install */
10764        FileInstallArgs(InstallParams params) {
10765            super(params.origin, params.move, params.observer, params.installFlags,
10766                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10767                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10768            if (isFwdLocked()) {
10769                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10770            }
10771        }
10772
10773        /** Existing install */
10774        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10775            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10776                    null);
10777            this.codeFile = (codePath != null) ? new File(codePath) : null;
10778            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10779        }
10780
10781        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10782            if (origin.staged) {
10783                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10784                codeFile = origin.file;
10785                resourceFile = origin.file;
10786                return PackageManager.INSTALL_SUCCEEDED;
10787            }
10788
10789            try {
10790                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10791                codeFile = tempDir;
10792                resourceFile = tempDir;
10793            } catch (IOException e) {
10794                Slog.w(TAG, "Failed to create copy file: " + e);
10795                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10796            }
10797
10798            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10799                @Override
10800                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10801                    if (!FileUtils.isValidExtFilename(name)) {
10802                        throw new IllegalArgumentException("Invalid filename: " + name);
10803                    }
10804                    try {
10805                        final File file = new File(codeFile, name);
10806                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10807                                O_RDWR | O_CREAT, 0644);
10808                        Os.chmod(file.getAbsolutePath(), 0644);
10809                        return new ParcelFileDescriptor(fd);
10810                    } catch (ErrnoException e) {
10811                        throw new RemoteException("Failed to open: " + e.getMessage());
10812                    }
10813                }
10814            };
10815
10816            int ret = PackageManager.INSTALL_SUCCEEDED;
10817            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10818            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10819                Slog.e(TAG, "Failed to copy package");
10820                return ret;
10821            }
10822
10823            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10824            NativeLibraryHelper.Handle handle = null;
10825            try {
10826                handle = NativeLibraryHelper.Handle.create(codeFile);
10827                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10828                        abiOverride);
10829            } catch (IOException e) {
10830                Slog.e(TAG, "Copying native libraries failed", e);
10831                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10832            } finally {
10833                IoUtils.closeQuietly(handle);
10834            }
10835
10836            return ret;
10837        }
10838
10839        int doPreInstall(int status) {
10840            if (status != PackageManager.INSTALL_SUCCEEDED) {
10841                cleanUp();
10842            }
10843            return status;
10844        }
10845
10846        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10847            if (status != PackageManager.INSTALL_SUCCEEDED) {
10848                cleanUp();
10849                return false;
10850            }
10851
10852            final File targetDir = codeFile.getParentFile();
10853            final File beforeCodeFile = codeFile;
10854            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10855
10856            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10857            try {
10858                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10859            } catch (ErrnoException e) {
10860                Slog.w(TAG, "Failed to rename", e);
10861                return false;
10862            }
10863
10864            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10865                Slog.w(TAG, "Failed to restorecon");
10866                return false;
10867            }
10868
10869            // Reflect the rename internally
10870            codeFile = afterCodeFile;
10871            resourceFile = afterCodeFile;
10872
10873            // Reflect the rename in scanned details
10874            pkg.codePath = afterCodeFile.getAbsolutePath();
10875            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10876                    pkg.baseCodePath);
10877            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10878                    pkg.splitCodePaths);
10879
10880            // Reflect the rename in app info
10881            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10882            pkg.applicationInfo.setCodePath(pkg.codePath);
10883            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10884            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10885            pkg.applicationInfo.setResourcePath(pkg.codePath);
10886            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10887            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10888
10889            return true;
10890        }
10891
10892        int doPostInstall(int status, int uid) {
10893            if (status != PackageManager.INSTALL_SUCCEEDED) {
10894                cleanUp();
10895            }
10896            return status;
10897        }
10898
10899        @Override
10900        String getCodePath() {
10901            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10902        }
10903
10904        @Override
10905        String getResourcePath() {
10906            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10907        }
10908
10909        private boolean cleanUp() {
10910            if (codeFile == null || !codeFile.exists()) {
10911                return false;
10912            }
10913
10914            if (codeFile.isDirectory()) {
10915                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10916            } else {
10917                codeFile.delete();
10918            }
10919
10920            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10921                resourceFile.delete();
10922            }
10923
10924            return true;
10925        }
10926
10927        void cleanUpResourcesLI() {
10928            // Try enumerating all code paths before deleting
10929            List<String> allCodePaths = Collections.EMPTY_LIST;
10930            if (codeFile != null && codeFile.exists()) {
10931                try {
10932                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10933                    allCodePaths = pkg.getAllCodePaths();
10934                } catch (PackageParserException e) {
10935                    // Ignored; we tried our best
10936                }
10937            }
10938
10939            cleanUp();
10940            removeDexFiles(allCodePaths, instructionSets);
10941        }
10942
10943        boolean doPostDeleteLI(boolean delete) {
10944            // XXX err, shouldn't we respect the delete flag?
10945            cleanUpResourcesLI();
10946            return true;
10947        }
10948    }
10949
10950    private boolean isAsecExternal(String cid) {
10951        final String asecPath = PackageHelper.getSdFilesystem(cid);
10952        return !asecPath.startsWith(mAsecInternalPath);
10953    }
10954
10955    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10956            PackageManagerException {
10957        if (copyRet < 0) {
10958            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10959                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10960                throw new PackageManagerException(copyRet, message);
10961            }
10962        }
10963    }
10964
10965    /**
10966     * Extract the MountService "container ID" from the full code path of an
10967     * .apk.
10968     */
10969    static String cidFromCodePath(String fullCodePath) {
10970        int eidx = fullCodePath.lastIndexOf("/");
10971        String subStr1 = fullCodePath.substring(0, eidx);
10972        int sidx = subStr1.lastIndexOf("/");
10973        return subStr1.substring(sidx+1, eidx);
10974    }
10975
10976    /**
10977     * Logic to handle installation of ASEC applications, including copying and
10978     * renaming logic.
10979     */
10980    class AsecInstallArgs extends InstallArgs {
10981        static final String RES_FILE_NAME = "pkg.apk";
10982        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10983
10984        String cid;
10985        String packagePath;
10986        String resourcePath;
10987
10988        /** New install */
10989        AsecInstallArgs(InstallParams params) {
10990            super(params.origin, params.move, params.observer, params.installFlags,
10991                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10992                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10993        }
10994
10995        /** Existing install */
10996        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10997                        boolean isExternal, boolean isForwardLocked) {
10998            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10999                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11000                    instructionSets, null);
11001            // Hackily pretend we're still looking at a full code path
11002            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11003                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11004            }
11005
11006            // Extract cid from fullCodePath
11007            int eidx = fullCodePath.lastIndexOf("/");
11008            String subStr1 = fullCodePath.substring(0, eidx);
11009            int sidx = subStr1.lastIndexOf("/");
11010            cid = subStr1.substring(sidx+1, eidx);
11011            setMountPath(subStr1);
11012        }
11013
11014        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11015            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11016                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11017                    instructionSets, null);
11018            this.cid = cid;
11019            setMountPath(PackageHelper.getSdDir(cid));
11020        }
11021
11022        void createCopyFile() {
11023            cid = mInstallerService.allocateExternalStageCidLegacy();
11024        }
11025
11026        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11027            if (origin.staged) {
11028                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11029                cid = origin.cid;
11030                setMountPath(PackageHelper.getSdDir(cid));
11031                return PackageManager.INSTALL_SUCCEEDED;
11032            }
11033
11034            if (temp) {
11035                createCopyFile();
11036            } else {
11037                /*
11038                 * Pre-emptively destroy the container since it's destroyed if
11039                 * copying fails due to it existing anyway.
11040                 */
11041                PackageHelper.destroySdDir(cid);
11042            }
11043
11044            final String newMountPath = imcs.copyPackageToContainer(
11045                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11046                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11047
11048            if (newMountPath != null) {
11049                setMountPath(newMountPath);
11050                return PackageManager.INSTALL_SUCCEEDED;
11051            } else {
11052                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11053            }
11054        }
11055
11056        @Override
11057        String getCodePath() {
11058            return packagePath;
11059        }
11060
11061        @Override
11062        String getResourcePath() {
11063            return resourcePath;
11064        }
11065
11066        int doPreInstall(int status) {
11067            if (status != PackageManager.INSTALL_SUCCEEDED) {
11068                // Destroy container
11069                PackageHelper.destroySdDir(cid);
11070            } else {
11071                boolean mounted = PackageHelper.isContainerMounted(cid);
11072                if (!mounted) {
11073                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11074                            Process.SYSTEM_UID);
11075                    if (newMountPath != null) {
11076                        setMountPath(newMountPath);
11077                    } else {
11078                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11079                    }
11080                }
11081            }
11082            return status;
11083        }
11084
11085        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11086            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11087            String newMountPath = null;
11088            if (PackageHelper.isContainerMounted(cid)) {
11089                // Unmount the container
11090                if (!PackageHelper.unMountSdDir(cid)) {
11091                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11092                    return false;
11093                }
11094            }
11095            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11096                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11097                        " which might be stale. Will try to clean up.");
11098                // Clean up the stale container and proceed to recreate.
11099                if (!PackageHelper.destroySdDir(newCacheId)) {
11100                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11101                    return false;
11102                }
11103                // Successfully cleaned up stale container. Try to rename again.
11104                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11105                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11106                            + " inspite of cleaning it up.");
11107                    return false;
11108                }
11109            }
11110            if (!PackageHelper.isContainerMounted(newCacheId)) {
11111                Slog.w(TAG, "Mounting container " + newCacheId);
11112                newMountPath = PackageHelper.mountSdDir(newCacheId,
11113                        getEncryptKey(), Process.SYSTEM_UID);
11114            } else {
11115                newMountPath = PackageHelper.getSdDir(newCacheId);
11116            }
11117            if (newMountPath == null) {
11118                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11119                return false;
11120            }
11121            Log.i(TAG, "Succesfully renamed " + cid +
11122                    " to " + newCacheId +
11123                    " at new path: " + newMountPath);
11124            cid = newCacheId;
11125
11126            final File beforeCodeFile = new File(packagePath);
11127            setMountPath(newMountPath);
11128            final File afterCodeFile = new File(packagePath);
11129
11130            // Reflect the rename in scanned details
11131            pkg.codePath = afterCodeFile.getAbsolutePath();
11132            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11133                    pkg.baseCodePath);
11134            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11135                    pkg.splitCodePaths);
11136
11137            // Reflect the rename in app info
11138            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11139            pkg.applicationInfo.setCodePath(pkg.codePath);
11140            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11141            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11142            pkg.applicationInfo.setResourcePath(pkg.codePath);
11143            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11144            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11145
11146            return true;
11147        }
11148
11149        private void setMountPath(String mountPath) {
11150            final File mountFile = new File(mountPath);
11151
11152            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11153            if (monolithicFile.exists()) {
11154                packagePath = monolithicFile.getAbsolutePath();
11155                if (isFwdLocked()) {
11156                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11157                } else {
11158                    resourcePath = packagePath;
11159                }
11160            } else {
11161                packagePath = mountFile.getAbsolutePath();
11162                resourcePath = packagePath;
11163            }
11164        }
11165
11166        int doPostInstall(int status, int uid) {
11167            if (status != PackageManager.INSTALL_SUCCEEDED) {
11168                cleanUp();
11169            } else {
11170                final int groupOwner;
11171                final String protectedFile;
11172                if (isFwdLocked()) {
11173                    groupOwner = UserHandle.getSharedAppGid(uid);
11174                    protectedFile = RES_FILE_NAME;
11175                } else {
11176                    groupOwner = -1;
11177                    protectedFile = null;
11178                }
11179
11180                if (uid < Process.FIRST_APPLICATION_UID
11181                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11182                    Slog.e(TAG, "Failed to finalize " + cid);
11183                    PackageHelper.destroySdDir(cid);
11184                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11185                }
11186
11187                boolean mounted = PackageHelper.isContainerMounted(cid);
11188                if (!mounted) {
11189                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11190                }
11191            }
11192            return status;
11193        }
11194
11195        private void cleanUp() {
11196            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11197
11198            // Destroy secure container
11199            PackageHelper.destroySdDir(cid);
11200        }
11201
11202        private List<String> getAllCodePaths() {
11203            final File codeFile = new File(getCodePath());
11204            if (codeFile != null && codeFile.exists()) {
11205                try {
11206                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11207                    return pkg.getAllCodePaths();
11208                } catch (PackageParserException e) {
11209                    // Ignored; we tried our best
11210                }
11211            }
11212            return Collections.EMPTY_LIST;
11213        }
11214
11215        void cleanUpResourcesLI() {
11216            // Enumerate all code paths before deleting
11217            cleanUpResourcesLI(getAllCodePaths());
11218        }
11219
11220        private void cleanUpResourcesLI(List<String> allCodePaths) {
11221            cleanUp();
11222            removeDexFiles(allCodePaths, instructionSets);
11223        }
11224
11225        String getPackageName() {
11226            return getAsecPackageName(cid);
11227        }
11228
11229        boolean doPostDeleteLI(boolean delete) {
11230            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11231            final List<String> allCodePaths = getAllCodePaths();
11232            boolean mounted = PackageHelper.isContainerMounted(cid);
11233            if (mounted) {
11234                // Unmount first
11235                if (PackageHelper.unMountSdDir(cid)) {
11236                    mounted = false;
11237                }
11238            }
11239            if (!mounted && delete) {
11240                cleanUpResourcesLI(allCodePaths);
11241            }
11242            return !mounted;
11243        }
11244
11245        @Override
11246        int doPreCopy() {
11247            if (isFwdLocked()) {
11248                if (!PackageHelper.fixSdPermissions(cid,
11249                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11250                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11251                }
11252            }
11253
11254            return PackageManager.INSTALL_SUCCEEDED;
11255        }
11256
11257        @Override
11258        int doPostCopy(int uid) {
11259            if (isFwdLocked()) {
11260                if (uid < Process.FIRST_APPLICATION_UID
11261                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11262                                RES_FILE_NAME)) {
11263                    Slog.e(TAG, "Failed to finalize " + cid);
11264                    PackageHelper.destroySdDir(cid);
11265                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11266                }
11267            }
11268
11269            return PackageManager.INSTALL_SUCCEEDED;
11270        }
11271    }
11272
11273    /**
11274     * Logic to handle movement of existing installed applications.
11275     */
11276    class MoveInstallArgs extends InstallArgs {
11277        private File codeFile;
11278        private File resourceFile;
11279
11280        /** New install */
11281        MoveInstallArgs(InstallParams params) {
11282            super(params.origin, params.move, params.observer, params.installFlags,
11283                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11284                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11285        }
11286
11287        int copyApk(IMediaContainerService imcs, boolean temp) {
11288            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11289                    + move.fromUuid + " to " + move.toUuid);
11290            synchronized (mInstaller) {
11291                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11292                        move.dataAppName, move.appId, move.seinfo) != 0) {
11293                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11294                }
11295            }
11296
11297            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11298            resourceFile = codeFile;
11299            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11300
11301            return PackageManager.INSTALL_SUCCEEDED;
11302        }
11303
11304        int doPreInstall(int status) {
11305            if (status != PackageManager.INSTALL_SUCCEEDED) {
11306                cleanUp(move.toUuid);
11307            }
11308            return status;
11309        }
11310
11311        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11312            if (status != PackageManager.INSTALL_SUCCEEDED) {
11313                cleanUp(move.toUuid);
11314                return false;
11315            }
11316
11317            // Reflect the move in app info
11318            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11319            pkg.applicationInfo.setCodePath(pkg.codePath);
11320            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11321            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11322            pkg.applicationInfo.setResourcePath(pkg.codePath);
11323            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11324            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11325
11326            return true;
11327        }
11328
11329        int doPostInstall(int status, int uid) {
11330            if (status == PackageManager.INSTALL_SUCCEEDED) {
11331                cleanUp(move.fromUuid);
11332            } else {
11333                cleanUp(move.toUuid);
11334            }
11335            return status;
11336        }
11337
11338        @Override
11339        String getCodePath() {
11340            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11341        }
11342
11343        @Override
11344        String getResourcePath() {
11345            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11346        }
11347
11348        private boolean cleanUp(String volumeUuid) {
11349            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11350                    move.dataAppName);
11351            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11352            synchronized (mInstallLock) {
11353                // Clean up both app data and code
11354                removeDataDirsLI(volumeUuid, move.packageName);
11355                if (codeFile.isDirectory()) {
11356                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11357                } else {
11358                    codeFile.delete();
11359                }
11360            }
11361            return true;
11362        }
11363
11364        void cleanUpResourcesLI() {
11365            throw new UnsupportedOperationException();
11366        }
11367
11368        boolean doPostDeleteLI(boolean delete) {
11369            throw new UnsupportedOperationException();
11370        }
11371    }
11372
11373    static String getAsecPackageName(String packageCid) {
11374        int idx = packageCid.lastIndexOf("-");
11375        if (idx == -1) {
11376            return packageCid;
11377        }
11378        return packageCid.substring(0, idx);
11379    }
11380
11381    // Utility method used to create code paths based on package name and available index.
11382    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11383        String idxStr = "";
11384        int idx = 1;
11385        // Fall back to default value of idx=1 if prefix is not
11386        // part of oldCodePath
11387        if (oldCodePath != null) {
11388            String subStr = oldCodePath;
11389            // Drop the suffix right away
11390            if (suffix != null && subStr.endsWith(suffix)) {
11391                subStr = subStr.substring(0, subStr.length() - suffix.length());
11392            }
11393            // If oldCodePath already contains prefix find out the
11394            // ending index to either increment or decrement.
11395            int sidx = subStr.lastIndexOf(prefix);
11396            if (sidx != -1) {
11397                subStr = subStr.substring(sidx + prefix.length());
11398                if (subStr != null) {
11399                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11400                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11401                    }
11402                    try {
11403                        idx = Integer.parseInt(subStr);
11404                        if (idx <= 1) {
11405                            idx++;
11406                        } else {
11407                            idx--;
11408                        }
11409                    } catch(NumberFormatException e) {
11410                    }
11411                }
11412            }
11413        }
11414        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11415        return prefix + idxStr;
11416    }
11417
11418    private File getNextCodePath(File targetDir, String packageName) {
11419        int suffix = 1;
11420        File result;
11421        do {
11422            result = new File(targetDir, packageName + "-" + suffix);
11423            suffix++;
11424        } while (result.exists());
11425        return result;
11426    }
11427
11428    // Utility method that returns the relative package path with respect
11429    // to the installation directory. Like say for /data/data/com.test-1.apk
11430    // string com.test-1 is returned.
11431    static String deriveCodePathName(String codePath) {
11432        if (codePath == null) {
11433            return null;
11434        }
11435        final File codeFile = new File(codePath);
11436        final String name = codeFile.getName();
11437        if (codeFile.isDirectory()) {
11438            return name;
11439        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11440            final int lastDot = name.lastIndexOf('.');
11441            return name.substring(0, lastDot);
11442        } else {
11443            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11444            return null;
11445        }
11446    }
11447
11448    class PackageInstalledInfo {
11449        String name;
11450        int uid;
11451        // The set of users that originally had this package installed.
11452        int[] origUsers;
11453        // The set of users that now have this package installed.
11454        int[] newUsers;
11455        PackageParser.Package pkg;
11456        int returnCode;
11457        String returnMsg;
11458        PackageRemovedInfo removedInfo;
11459
11460        public void setError(int code, String msg) {
11461            returnCode = code;
11462            returnMsg = msg;
11463            Slog.w(TAG, msg);
11464        }
11465
11466        public void setError(String msg, PackageParserException e) {
11467            returnCode = e.error;
11468            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11469            Slog.w(TAG, msg, e);
11470        }
11471
11472        public void setError(String msg, PackageManagerException e) {
11473            returnCode = e.error;
11474            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11475            Slog.w(TAG, msg, e);
11476        }
11477
11478        // In some error cases we want to convey more info back to the observer
11479        String origPackage;
11480        String origPermission;
11481    }
11482
11483    /*
11484     * Install a non-existing package.
11485     */
11486    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11487            UserHandle user, String installerPackageName, String volumeUuid,
11488            PackageInstalledInfo res) {
11489        // Remember this for later, in case we need to rollback this install
11490        String pkgName = pkg.packageName;
11491
11492        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11493        final boolean dataDirExists = Environment
11494                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11495        synchronized(mPackages) {
11496            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11497                // A package with the same name is already installed, though
11498                // it has been renamed to an older name.  The package we
11499                // are trying to install should be installed as an update to
11500                // the existing one, but that has not been requested, so bail.
11501                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11502                        + " without first uninstalling package running as "
11503                        + mSettings.mRenamedPackages.get(pkgName));
11504                return;
11505            }
11506            if (mPackages.containsKey(pkgName)) {
11507                // Don't allow installation over an existing package with the same name.
11508                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11509                        + " without first uninstalling.");
11510                return;
11511            }
11512        }
11513
11514        try {
11515            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11516                    System.currentTimeMillis(), user);
11517
11518            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11519            // delete the partially installed application. the data directory will have to be
11520            // restored if it was already existing
11521            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11522                // remove package from internal structures.  Note that we want deletePackageX to
11523                // delete the package data and cache directories that it created in
11524                // scanPackageLocked, unless those directories existed before we even tried to
11525                // install.
11526                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11527                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11528                                res.removedInfo, true);
11529            }
11530
11531        } catch (PackageManagerException e) {
11532            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11533        }
11534    }
11535
11536    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11537        // Can't rotate keys during boot or if sharedUser.
11538        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11539                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11540            return false;
11541        }
11542        // app is using upgradeKeySets; make sure all are valid
11543        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11544        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11545        for (int i = 0; i < upgradeKeySets.length; i++) {
11546            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11547                Slog.wtf(TAG, "Package "
11548                         + (oldPs.name != null ? oldPs.name : "<null>")
11549                         + " contains upgrade-key-set reference to unknown key-set: "
11550                         + upgradeKeySets[i]
11551                         + " reverting to signatures check.");
11552                return false;
11553            }
11554        }
11555        return true;
11556    }
11557
11558    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11559        // Upgrade keysets are being used.  Determine if new package has a superset of the
11560        // required keys.
11561        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11562        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11563        for (int i = 0; i < upgradeKeySets.length; i++) {
11564            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11565            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11566                return true;
11567            }
11568        }
11569        return false;
11570    }
11571
11572    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11573            UserHandle user, String installerPackageName, String volumeUuid,
11574            PackageInstalledInfo res) {
11575        final PackageParser.Package oldPackage;
11576        final String pkgName = pkg.packageName;
11577        final int[] allUsers;
11578        final boolean[] perUserInstalled;
11579        final boolean weFroze;
11580
11581        // First find the old package info and check signatures
11582        synchronized(mPackages) {
11583            oldPackage = mPackages.get(pkgName);
11584            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11585            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11586            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11587                if(!checkUpgradeKeySetLP(ps, pkg)) {
11588                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11589                            "New package not signed by keys specified by upgrade-keysets: "
11590                            + pkgName);
11591                    return;
11592                }
11593            } else {
11594                // default to original signature matching
11595                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11596                    != PackageManager.SIGNATURE_MATCH) {
11597                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11598                            "New package has a different signature: " + pkgName);
11599                    return;
11600                }
11601            }
11602
11603            // In case of rollback, remember per-user/profile install state
11604            allUsers = sUserManager.getUserIds();
11605            perUserInstalled = new boolean[allUsers.length];
11606            for (int i = 0; i < allUsers.length; i++) {
11607                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11608            }
11609
11610            // Mark the app as frozen to prevent launching during the upgrade
11611            // process, and then kill all running instances
11612            if (!ps.frozen) {
11613                ps.frozen = true;
11614                weFroze = true;
11615            } else {
11616                weFroze = false;
11617            }
11618        }
11619
11620        // Now that we're guarded by frozen state, kill app during upgrade
11621        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11622
11623        try {
11624            boolean sysPkg = (isSystemApp(oldPackage));
11625            if (sysPkg) {
11626                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11627                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11628            } else {
11629                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11630                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11631            }
11632        } finally {
11633            // Regardless of success or failure of upgrade steps above, always
11634            // unfreeze the package if we froze it
11635            if (weFroze) {
11636                unfreezePackage(pkgName);
11637            }
11638        }
11639    }
11640
11641    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11642            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11643            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11644            String volumeUuid, PackageInstalledInfo res) {
11645        String pkgName = deletedPackage.packageName;
11646        boolean deletedPkg = true;
11647        boolean updatedSettings = false;
11648
11649        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11650                + deletedPackage);
11651        long origUpdateTime;
11652        if (pkg.mExtras != null) {
11653            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11654        } else {
11655            origUpdateTime = 0;
11656        }
11657
11658        // First delete the existing package while retaining the data directory
11659        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11660                res.removedInfo, true)) {
11661            // If the existing package wasn't successfully deleted
11662            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11663            deletedPkg = false;
11664        } else {
11665            // Successfully deleted the old package; proceed with replace.
11666
11667            // If deleted package lived in a container, give users a chance to
11668            // relinquish resources before killing.
11669            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11670                if (DEBUG_INSTALL) {
11671                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11672                }
11673                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11674                final ArrayList<String> pkgList = new ArrayList<String>(1);
11675                pkgList.add(deletedPackage.applicationInfo.packageName);
11676                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11677            }
11678
11679            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11680            try {
11681                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11682                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11683                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11684                        perUserInstalled, res, user);
11685                updatedSettings = true;
11686            } catch (PackageManagerException e) {
11687                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11688            }
11689        }
11690
11691        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11692            // remove package from internal structures.  Note that we want deletePackageX to
11693            // delete the package data and cache directories that it created in
11694            // scanPackageLocked, unless those directories existed before we even tried to
11695            // install.
11696            if(updatedSettings) {
11697                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11698                deletePackageLI(
11699                        pkgName, null, true, allUsers, perUserInstalled,
11700                        PackageManager.DELETE_KEEP_DATA,
11701                                res.removedInfo, true);
11702            }
11703            // Since we failed to install the new package we need to restore the old
11704            // package that we deleted.
11705            if (deletedPkg) {
11706                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11707                File restoreFile = new File(deletedPackage.codePath);
11708                // Parse old package
11709                boolean oldExternal = isExternal(deletedPackage);
11710                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11711                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11712                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11713                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11714                try {
11715                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11716                } catch (PackageManagerException e) {
11717                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11718                            + e.getMessage());
11719                    return;
11720                }
11721                // Restore of old package succeeded. Update permissions.
11722                // writer
11723                synchronized (mPackages) {
11724                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11725                            UPDATE_PERMISSIONS_ALL);
11726                    // can downgrade to reader
11727                    mSettings.writeLPr();
11728                }
11729                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11730            }
11731        }
11732    }
11733
11734    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11735            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11736            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11737            String volumeUuid, PackageInstalledInfo res) {
11738        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11739                + ", old=" + deletedPackage);
11740        boolean disabledSystem = false;
11741        boolean updatedSettings = false;
11742        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11743        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11744                != 0) {
11745            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11746        }
11747        String packageName = deletedPackage.packageName;
11748        if (packageName == null) {
11749            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11750                    "Attempt to delete null packageName.");
11751            return;
11752        }
11753        PackageParser.Package oldPkg;
11754        PackageSetting oldPkgSetting;
11755        // reader
11756        synchronized (mPackages) {
11757            oldPkg = mPackages.get(packageName);
11758            oldPkgSetting = mSettings.mPackages.get(packageName);
11759            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11760                    (oldPkgSetting == null)) {
11761                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11762                        "Couldn't find package:" + packageName + " information");
11763                return;
11764            }
11765        }
11766
11767        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11768        res.removedInfo.removedPackage = packageName;
11769        // Remove existing system package
11770        removePackageLI(oldPkgSetting, true);
11771        // writer
11772        synchronized (mPackages) {
11773            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11774            if (!disabledSystem && deletedPackage != null) {
11775                // We didn't need to disable the .apk as a current system package,
11776                // which means we are replacing another update that is already
11777                // installed.  We need to make sure to delete the older one's .apk.
11778                res.removedInfo.args = createInstallArgsForExisting(0,
11779                        deletedPackage.applicationInfo.getCodePath(),
11780                        deletedPackage.applicationInfo.getResourcePath(),
11781                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11782            } else {
11783                res.removedInfo.args = null;
11784            }
11785        }
11786
11787        // Successfully disabled the old package. Now proceed with re-installation
11788        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11789
11790        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11791        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11792
11793        PackageParser.Package newPackage = null;
11794        try {
11795            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11796            if (newPackage.mExtras != null) {
11797                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11798                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11799                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11800
11801                // is the update attempting to change shared user? that isn't going to work...
11802                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11803                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11804                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11805                            + " to " + newPkgSetting.sharedUser);
11806                    updatedSettings = true;
11807                }
11808            }
11809
11810            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11811                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11812                        perUserInstalled, res, user);
11813                updatedSettings = true;
11814            }
11815
11816        } catch (PackageManagerException e) {
11817            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11818        }
11819
11820        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11821            // Re installation failed. Restore old information
11822            // Remove new pkg information
11823            if (newPackage != null) {
11824                removeInstalledPackageLI(newPackage, true);
11825            }
11826            // Add back the old system package
11827            try {
11828                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11829            } catch (PackageManagerException e) {
11830                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11831            }
11832            // Restore the old system information in Settings
11833            synchronized (mPackages) {
11834                if (disabledSystem) {
11835                    mSettings.enableSystemPackageLPw(packageName);
11836                }
11837                if (updatedSettings) {
11838                    mSettings.setInstallerPackageName(packageName,
11839                            oldPkgSetting.installerPackageName);
11840                }
11841                mSettings.writeLPr();
11842            }
11843        }
11844    }
11845
11846    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11847            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11848            UserHandle user) {
11849        String pkgName = newPackage.packageName;
11850        synchronized (mPackages) {
11851            //write settings. the installStatus will be incomplete at this stage.
11852            //note that the new package setting would have already been
11853            //added to mPackages. It hasn't been persisted yet.
11854            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11855            mSettings.writeLPr();
11856        }
11857
11858        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11859
11860        synchronized (mPackages) {
11861            updatePermissionsLPw(newPackage.packageName, newPackage,
11862                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11863                            ? UPDATE_PERMISSIONS_ALL : 0));
11864            // For system-bundled packages, we assume that installing an upgraded version
11865            // of the package implies that the user actually wants to run that new code,
11866            // so we enable the package.
11867            PackageSetting ps = mSettings.mPackages.get(pkgName);
11868            if (ps != null) {
11869                if (isSystemApp(newPackage)) {
11870                    // NB: implicit assumption that system package upgrades apply to all users
11871                    if (DEBUG_INSTALL) {
11872                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11873                    }
11874                    if (res.origUsers != null) {
11875                        for (int userHandle : res.origUsers) {
11876                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11877                                    userHandle, installerPackageName);
11878                        }
11879                    }
11880                    // Also convey the prior install/uninstall state
11881                    if (allUsers != null && perUserInstalled != null) {
11882                        for (int i = 0; i < allUsers.length; i++) {
11883                            if (DEBUG_INSTALL) {
11884                                Slog.d(TAG, "    user " + allUsers[i]
11885                                        + " => " + perUserInstalled[i]);
11886                            }
11887                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11888                        }
11889                        // these install state changes will be persisted in the
11890                        // upcoming call to mSettings.writeLPr().
11891                    }
11892                }
11893                // It's implied that when a user requests installation, they want the app to be
11894                // installed and enabled.
11895                int userId = user.getIdentifier();
11896                if (userId != UserHandle.USER_ALL) {
11897                    ps.setInstalled(true, userId);
11898                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11899                }
11900            }
11901            res.name = pkgName;
11902            res.uid = newPackage.applicationInfo.uid;
11903            res.pkg = newPackage;
11904            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11905            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11906            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11907            //to update install status
11908            mSettings.writeLPr();
11909        }
11910    }
11911
11912    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11913        final int installFlags = args.installFlags;
11914        final String installerPackageName = args.installerPackageName;
11915        final String volumeUuid = args.volumeUuid;
11916        final File tmpPackageFile = new File(args.getCodePath());
11917        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11918        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11919                || (args.volumeUuid != null));
11920        boolean replace = false;
11921        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11922        if (args.move != null) {
11923            // moving a complete application; perfom an initial scan on the new install location
11924            scanFlags |= SCAN_INITIAL;
11925        }
11926        // Result object to be returned
11927        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11928
11929        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11930        // Retrieve PackageSettings and parse package
11931        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11932                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11933                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11934        PackageParser pp = new PackageParser();
11935        pp.setSeparateProcesses(mSeparateProcesses);
11936        pp.setDisplayMetrics(mMetrics);
11937
11938        final PackageParser.Package pkg;
11939        try {
11940            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11941        } catch (PackageParserException e) {
11942            res.setError("Failed parse during installPackageLI", e);
11943            return;
11944        }
11945
11946        // Mark that we have an install time CPU ABI override.
11947        pkg.cpuAbiOverride = args.abiOverride;
11948
11949        String pkgName = res.name = pkg.packageName;
11950        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11951            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11952                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11953                return;
11954            }
11955        }
11956
11957        try {
11958            pp.collectCertificates(pkg, parseFlags);
11959            pp.collectManifestDigest(pkg);
11960        } catch (PackageParserException e) {
11961            res.setError("Failed collect during installPackageLI", e);
11962            return;
11963        }
11964
11965        /* If the installer passed in a manifest digest, compare it now. */
11966        if (args.manifestDigest != null) {
11967            if (DEBUG_INSTALL) {
11968                final String parsedManifest = pkg.manifestDigest == null ? "null"
11969                        : pkg.manifestDigest.toString();
11970                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11971                        + parsedManifest);
11972            }
11973
11974            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11975                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11976                return;
11977            }
11978        } else if (DEBUG_INSTALL) {
11979            final String parsedManifest = pkg.manifestDigest == null
11980                    ? "null" : pkg.manifestDigest.toString();
11981            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11982        }
11983
11984        // Get rid of all references to package scan path via parser.
11985        pp = null;
11986        String oldCodePath = null;
11987        boolean systemApp = false;
11988        synchronized (mPackages) {
11989            // Check if installing already existing package
11990            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11991                String oldName = mSettings.mRenamedPackages.get(pkgName);
11992                if (pkg.mOriginalPackages != null
11993                        && pkg.mOriginalPackages.contains(oldName)
11994                        && mPackages.containsKey(oldName)) {
11995                    // This package is derived from an original package,
11996                    // and this device has been updating from that original
11997                    // name.  We must continue using the original name, so
11998                    // rename the new package here.
11999                    pkg.setPackageName(oldName);
12000                    pkgName = pkg.packageName;
12001                    replace = true;
12002                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12003                            + oldName + " pkgName=" + pkgName);
12004                } else if (mPackages.containsKey(pkgName)) {
12005                    // This package, under its official name, already exists
12006                    // on the device; we should replace it.
12007                    replace = true;
12008                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12009                }
12010
12011                // Prevent apps opting out from runtime permissions
12012                if (replace) {
12013                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12014                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12015                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12016                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12017                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12018                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12019                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12020                                        + " doesn't support runtime permissions but the old"
12021                                        + " target SDK " + oldTargetSdk + " does.");
12022                        return;
12023                    }
12024                }
12025            }
12026
12027            PackageSetting ps = mSettings.mPackages.get(pkgName);
12028            if (ps != null) {
12029                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12030
12031                // Quick sanity check that we're signed correctly if updating;
12032                // we'll check this again later when scanning, but we want to
12033                // bail early here before tripping over redefined permissions.
12034                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12035                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12036                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12037                                + pkg.packageName + " upgrade keys do not match the "
12038                                + "previously installed version");
12039                        return;
12040                    }
12041                } else {
12042                    try {
12043                        verifySignaturesLP(ps, pkg);
12044                    } catch (PackageManagerException e) {
12045                        res.setError(e.error, e.getMessage());
12046                        return;
12047                    }
12048                }
12049
12050                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12051                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12052                    systemApp = (ps.pkg.applicationInfo.flags &
12053                            ApplicationInfo.FLAG_SYSTEM) != 0;
12054                }
12055                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12056            }
12057
12058            // Check whether the newly-scanned package wants to define an already-defined perm
12059            int N = pkg.permissions.size();
12060            for (int i = N-1; i >= 0; i--) {
12061                PackageParser.Permission perm = pkg.permissions.get(i);
12062                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12063                if (bp != null) {
12064                    // If the defining package is signed with our cert, it's okay.  This
12065                    // also includes the "updating the same package" case, of course.
12066                    // "updating same package" could also involve key-rotation.
12067                    final boolean sigsOk;
12068                    if (bp.sourcePackage.equals(pkg.packageName)
12069                            && (bp.packageSetting instanceof PackageSetting)
12070                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12071                                    scanFlags))) {
12072                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12073                    } else {
12074                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12075                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12076                    }
12077                    if (!sigsOk) {
12078                        // If the owning package is the system itself, we log but allow
12079                        // install to proceed; we fail the install on all other permission
12080                        // redefinitions.
12081                        if (!bp.sourcePackage.equals("android")) {
12082                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12083                                    + pkg.packageName + " attempting to redeclare permission "
12084                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12085                            res.origPermission = perm.info.name;
12086                            res.origPackage = bp.sourcePackage;
12087                            return;
12088                        } else {
12089                            Slog.w(TAG, "Package " + pkg.packageName
12090                                    + " attempting to redeclare system permission "
12091                                    + perm.info.name + "; ignoring new declaration");
12092                            pkg.permissions.remove(i);
12093                        }
12094                    }
12095                }
12096            }
12097
12098        }
12099
12100        if (systemApp && onExternal) {
12101            // Disable updates to system apps on sdcard
12102            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12103                    "Cannot install updates to system apps on sdcard");
12104            return;
12105        }
12106
12107        if (args.move != null) {
12108            // We did an in-place move, so dex is ready to roll
12109            scanFlags |= SCAN_NO_DEX;
12110            scanFlags |= SCAN_MOVE;
12111        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12112            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12113            scanFlags |= SCAN_NO_DEX;
12114
12115            try {
12116                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12117                        true /* extract libs */);
12118            } catch (PackageManagerException pme) {
12119                Slog.e(TAG, "Error deriving application ABI", pme);
12120                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12121                return;
12122            }
12123
12124            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12125            int result = mPackageDexOptimizer
12126                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12127                            false /* defer */, false /* inclDependencies */);
12128            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12129                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12130                return;
12131            }
12132        }
12133
12134        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12135            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12136            return;
12137        }
12138
12139        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12140
12141        if (replace) {
12142            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12143                    installerPackageName, volumeUuid, res);
12144        } else {
12145            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12146                    args.user, installerPackageName, volumeUuid, res);
12147        }
12148        synchronized (mPackages) {
12149            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12150            if (ps != null) {
12151                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12152            }
12153        }
12154    }
12155
12156    private void startIntentFilterVerifications(int userId, boolean replacing,
12157            PackageParser.Package pkg) {
12158        if (mIntentFilterVerifierComponent == null) {
12159            Slog.w(TAG, "No IntentFilter verification will not be done as "
12160                    + "there is no IntentFilterVerifier available!");
12161            return;
12162        }
12163
12164        final int verifierUid = getPackageUid(
12165                mIntentFilterVerifierComponent.getPackageName(),
12166                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12167
12168        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12169        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12170        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12171        mHandler.sendMessage(msg);
12172    }
12173
12174    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12175            PackageParser.Package pkg) {
12176        int size = pkg.activities.size();
12177        if (size == 0) {
12178            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12179                    "No activity, so no need to verify any IntentFilter!");
12180            return;
12181        }
12182
12183        final boolean hasDomainURLs = hasDomainURLs(pkg);
12184        if (!hasDomainURLs) {
12185            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12186                    "No domain URLs, so no need to verify any IntentFilter!");
12187            return;
12188        }
12189
12190        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12191                + " if any IntentFilter from the " + size
12192                + " Activities needs verification ...");
12193
12194        int count = 0;
12195        final String packageName = pkg.packageName;
12196
12197        synchronized (mPackages) {
12198            // If this is a new install and we see that we've already run verification for this
12199            // package, we have nothing to do: it means the state was restored from backup.
12200            if (!replacing) {
12201                IntentFilterVerificationInfo ivi =
12202                        mSettings.getIntentFilterVerificationLPr(packageName);
12203                if (ivi != null) {
12204                    if (DEBUG_DOMAIN_VERIFICATION) {
12205                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12206                                + ivi.getStatusString());
12207                    }
12208                    return;
12209                }
12210            }
12211
12212            // If any filters need to be verified, then all need to be.
12213            boolean needToVerify = false;
12214            for (PackageParser.Activity a : pkg.activities) {
12215                for (ActivityIntentInfo filter : a.intents) {
12216                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12217                        if (DEBUG_DOMAIN_VERIFICATION) {
12218                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12219                        }
12220                        needToVerify = true;
12221                        break;
12222                    }
12223                }
12224            }
12225
12226            if (needToVerify) {
12227                final int verificationId = mIntentFilterVerificationToken++;
12228                for (PackageParser.Activity a : pkg.activities) {
12229                    for (ActivityIntentInfo filter : a.intents) {
12230                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12231                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12232                                    "Verification needed for IntentFilter:" + filter.toString());
12233                            mIntentFilterVerifier.addOneIntentFilterVerification(
12234                                    verifierUid, userId, verificationId, filter, packageName);
12235                            count++;
12236                        }
12237                    }
12238                }
12239            }
12240        }
12241
12242        if (count > 0) {
12243            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12244                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12245                    +  " for userId:" + userId);
12246            mIntentFilterVerifier.startVerifications(userId);
12247        } else {
12248            if (DEBUG_DOMAIN_VERIFICATION) {
12249                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12250            }
12251        }
12252    }
12253
12254    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12255        final ComponentName cn  = filter.activity.getComponentName();
12256        final String packageName = cn.getPackageName();
12257
12258        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12259                packageName);
12260        if (ivi == null) {
12261            return true;
12262        }
12263        int status = ivi.getStatus();
12264        switch (status) {
12265            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12266            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12267                return true;
12268
12269            default:
12270                // Nothing to do
12271                return false;
12272        }
12273    }
12274
12275    private static boolean isMultiArch(PackageSetting ps) {
12276        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12277    }
12278
12279    private static boolean isMultiArch(ApplicationInfo info) {
12280        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12281    }
12282
12283    private static boolean isExternal(PackageParser.Package pkg) {
12284        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12285    }
12286
12287    private static boolean isExternal(PackageSetting ps) {
12288        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12289    }
12290
12291    private static boolean isExternal(ApplicationInfo info) {
12292        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12293    }
12294
12295    private static boolean isSystemApp(PackageParser.Package pkg) {
12296        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12297    }
12298
12299    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12300        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12301    }
12302
12303    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12304        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12305    }
12306
12307    private static boolean isSystemApp(PackageSetting ps) {
12308        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12309    }
12310
12311    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12312        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12313    }
12314
12315    private int packageFlagsToInstallFlags(PackageSetting ps) {
12316        int installFlags = 0;
12317        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12318            // This existing package was an external ASEC install when we have
12319            // the external flag without a UUID
12320            installFlags |= PackageManager.INSTALL_EXTERNAL;
12321        }
12322        if (ps.isForwardLocked()) {
12323            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12324        }
12325        return installFlags;
12326    }
12327
12328    private void deleteTempPackageFiles() {
12329        final FilenameFilter filter = new FilenameFilter() {
12330            public boolean accept(File dir, String name) {
12331                return name.startsWith("vmdl") && name.endsWith(".tmp");
12332            }
12333        };
12334        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12335            file.delete();
12336        }
12337    }
12338
12339    @Override
12340    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12341            int flags) {
12342        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12343                flags);
12344    }
12345
12346    @Override
12347    public void deletePackage(final String packageName,
12348            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12349        mContext.enforceCallingOrSelfPermission(
12350                android.Manifest.permission.DELETE_PACKAGES, null);
12351        Preconditions.checkNotNull(packageName);
12352        Preconditions.checkNotNull(observer);
12353        final int uid = Binder.getCallingUid();
12354        if (UserHandle.getUserId(uid) != userId) {
12355            mContext.enforceCallingPermission(
12356                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12357                    "deletePackage for user " + userId);
12358        }
12359        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12360            try {
12361                observer.onPackageDeleted(packageName,
12362                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12363            } catch (RemoteException re) {
12364            }
12365            return;
12366        }
12367
12368        boolean uninstallBlocked = false;
12369        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12370            int[] users = sUserManager.getUserIds();
12371            for (int i = 0; i < users.length; ++i) {
12372                if (getBlockUninstallForUser(packageName, users[i])) {
12373                    uninstallBlocked = true;
12374                    break;
12375                }
12376            }
12377        } else {
12378            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12379        }
12380        if (uninstallBlocked) {
12381            try {
12382                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12383                        null);
12384            } catch (RemoteException re) {
12385            }
12386            return;
12387        }
12388
12389        if (DEBUG_REMOVE) {
12390            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12391        }
12392        // Queue up an async operation since the package deletion may take a little while.
12393        mHandler.post(new Runnable() {
12394            public void run() {
12395                mHandler.removeCallbacks(this);
12396                final int returnCode = deletePackageX(packageName, userId, flags);
12397                if (observer != null) {
12398                    try {
12399                        observer.onPackageDeleted(packageName, returnCode, null);
12400                    } catch (RemoteException e) {
12401                        Log.i(TAG, "Observer no longer exists.");
12402                    } //end catch
12403                } //end if
12404            } //end run
12405        });
12406    }
12407
12408    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12409        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12410                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12411        try {
12412            if (dpm != null) {
12413                if (dpm.isDeviceOwner(packageName)) {
12414                    return true;
12415                }
12416                int[] users;
12417                if (userId == UserHandle.USER_ALL) {
12418                    users = sUserManager.getUserIds();
12419                } else {
12420                    users = new int[]{userId};
12421                }
12422                for (int i = 0; i < users.length; ++i) {
12423                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12424                        return true;
12425                    }
12426                }
12427            }
12428        } catch (RemoteException e) {
12429        }
12430        return false;
12431    }
12432
12433    /**
12434     *  This method is an internal method that could be get invoked either
12435     *  to delete an installed package or to clean up a failed installation.
12436     *  After deleting an installed package, a broadcast is sent to notify any
12437     *  listeners that the package has been installed. For cleaning up a failed
12438     *  installation, the broadcast is not necessary since the package's
12439     *  installation wouldn't have sent the initial broadcast either
12440     *  The key steps in deleting a package are
12441     *  deleting the package information in internal structures like mPackages,
12442     *  deleting the packages base directories through installd
12443     *  updating mSettings to reflect current status
12444     *  persisting settings for later use
12445     *  sending a broadcast if necessary
12446     */
12447    private int deletePackageX(String packageName, int userId, int flags) {
12448        final PackageRemovedInfo info = new PackageRemovedInfo();
12449        final boolean res;
12450
12451        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12452                ? UserHandle.ALL : new UserHandle(userId);
12453
12454        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12455            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12456            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12457        }
12458
12459        boolean removedForAllUsers = false;
12460        boolean systemUpdate = false;
12461
12462        // for the uninstall-updates case and restricted profiles, remember the per-
12463        // userhandle installed state
12464        int[] allUsers;
12465        boolean[] perUserInstalled;
12466        synchronized (mPackages) {
12467            PackageSetting ps = mSettings.mPackages.get(packageName);
12468            allUsers = sUserManager.getUserIds();
12469            perUserInstalled = new boolean[allUsers.length];
12470            for (int i = 0; i < allUsers.length; i++) {
12471                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12472            }
12473        }
12474
12475        synchronized (mInstallLock) {
12476            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12477            res = deletePackageLI(packageName, removeForUser,
12478                    true, allUsers, perUserInstalled,
12479                    flags | REMOVE_CHATTY, info, true);
12480            systemUpdate = info.isRemovedPackageSystemUpdate;
12481            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12482                removedForAllUsers = true;
12483            }
12484            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12485                    + " removedForAllUsers=" + removedForAllUsers);
12486        }
12487
12488        if (res) {
12489            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12490
12491            // If the removed package was a system update, the old system package
12492            // was re-enabled; we need to broadcast this information
12493            if (systemUpdate) {
12494                Bundle extras = new Bundle(1);
12495                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12496                        ? info.removedAppId : info.uid);
12497                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12498
12499                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12500                        extras, null, null, null);
12501                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12502                        extras, null, null, null);
12503                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12504                        null, packageName, null, null);
12505            }
12506        }
12507        // Force a gc here.
12508        Runtime.getRuntime().gc();
12509        // Delete the resources here after sending the broadcast to let
12510        // other processes clean up before deleting resources.
12511        if (info.args != null) {
12512            synchronized (mInstallLock) {
12513                info.args.doPostDeleteLI(true);
12514            }
12515        }
12516
12517        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12518    }
12519
12520    class PackageRemovedInfo {
12521        String removedPackage;
12522        int uid = -1;
12523        int removedAppId = -1;
12524        int[] removedUsers = null;
12525        boolean isRemovedPackageSystemUpdate = false;
12526        // Clean up resources deleted packages.
12527        InstallArgs args = null;
12528
12529        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12530            Bundle extras = new Bundle(1);
12531            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12532            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12533            if (replacing) {
12534                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12535            }
12536            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12537            if (removedPackage != null) {
12538                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12539                        extras, null, null, removedUsers);
12540                if (fullRemove && !replacing) {
12541                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12542                            extras, null, null, removedUsers);
12543                }
12544            }
12545            if (removedAppId >= 0) {
12546                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12547                        removedUsers);
12548            }
12549        }
12550    }
12551
12552    /*
12553     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12554     * flag is not set, the data directory is removed as well.
12555     * make sure this flag is set for partially installed apps. If not its meaningless to
12556     * delete a partially installed application.
12557     */
12558    private void removePackageDataLI(PackageSetting ps,
12559            int[] allUserHandles, boolean[] perUserInstalled,
12560            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12561        String packageName = ps.name;
12562        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12563        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12564        // Retrieve object to delete permissions for shared user later on
12565        final PackageSetting deletedPs;
12566        // reader
12567        synchronized (mPackages) {
12568            deletedPs = mSettings.mPackages.get(packageName);
12569            if (outInfo != null) {
12570                outInfo.removedPackage = packageName;
12571                outInfo.removedUsers = deletedPs != null
12572                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12573                        : null;
12574            }
12575        }
12576        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12577            removeDataDirsLI(ps.volumeUuid, packageName);
12578            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12579        }
12580        // writer
12581        synchronized (mPackages) {
12582            if (deletedPs != null) {
12583                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12584                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12585                    clearDefaultBrowserIfNeeded(packageName);
12586                    if (outInfo != null) {
12587                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12588                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12589                    }
12590                    updatePermissionsLPw(deletedPs.name, null, 0);
12591                    if (deletedPs.sharedUser != null) {
12592                        // Remove permissions associated with package. Since runtime
12593                        // permissions are per user we have to kill the removed package
12594                        // or packages running under the shared user of the removed
12595                        // package if revoking the permissions requested only by the removed
12596                        // package is successful and this causes a change in gids.
12597                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12598                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12599                                    userId);
12600                            if (userIdToKill == UserHandle.USER_ALL
12601                                    || userIdToKill >= UserHandle.USER_OWNER) {
12602                                // If gids changed for this user, kill all affected packages.
12603                                mHandler.post(new Runnable() {
12604                                    @Override
12605                                    public void run() {
12606                                        // This has to happen with no lock held.
12607                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12608                                                KILL_APP_REASON_GIDS_CHANGED);
12609                                    }
12610                                });
12611                            break;
12612                            }
12613                        }
12614                    }
12615                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12616                }
12617                // make sure to preserve per-user disabled state if this removal was just
12618                // a downgrade of a system app to the factory package
12619                if (allUserHandles != null && perUserInstalled != null) {
12620                    if (DEBUG_REMOVE) {
12621                        Slog.d(TAG, "Propagating install state across downgrade");
12622                    }
12623                    for (int i = 0; i < allUserHandles.length; i++) {
12624                        if (DEBUG_REMOVE) {
12625                            Slog.d(TAG, "    user " + allUserHandles[i]
12626                                    + " => " + perUserInstalled[i]);
12627                        }
12628                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12629                    }
12630                }
12631            }
12632            // can downgrade to reader
12633            if (writeSettings) {
12634                // Save settings now
12635                mSettings.writeLPr();
12636            }
12637        }
12638        if (outInfo != null) {
12639            // A user ID was deleted here. Go through all users and remove it
12640            // from KeyStore.
12641            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12642        }
12643    }
12644
12645    static boolean locationIsPrivileged(File path) {
12646        try {
12647            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12648                    .getCanonicalPath();
12649            return path.getCanonicalPath().startsWith(privilegedAppDir);
12650        } catch (IOException e) {
12651            Slog.e(TAG, "Unable to access code path " + path);
12652        }
12653        return false;
12654    }
12655
12656    /*
12657     * Tries to delete system package.
12658     */
12659    private boolean deleteSystemPackageLI(PackageSetting newPs,
12660            int[] allUserHandles, boolean[] perUserInstalled,
12661            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12662        final boolean applyUserRestrictions
12663                = (allUserHandles != null) && (perUserInstalled != null);
12664        PackageSetting disabledPs = null;
12665        // Confirm if the system package has been updated
12666        // An updated system app can be deleted. This will also have to restore
12667        // the system pkg from system partition
12668        // reader
12669        synchronized (mPackages) {
12670            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12671        }
12672        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12673                + " disabledPs=" + disabledPs);
12674        if (disabledPs == null) {
12675            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12676            return false;
12677        } else if (DEBUG_REMOVE) {
12678            Slog.d(TAG, "Deleting system pkg from data partition");
12679        }
12680        if (DEBUG_REMOVE) {
12681            if (applyUserRestrictions) {
12682                Slog.d(TAG, "Remembering install states:");
12683                for (int i = 0; i < allUserHandles.length; i++) {
12684                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12685                }
12686            }
12687        }
12688        // Delete the updated package
12689        outInfo.isRemovedPackageSystemUpdate = true;
12690        if (disabledPs.versionCode < newPs.versionCode) {
12691            // Delete data for downgrades
12692            flags &= ~PackageManager.DELETE_KEEP_DATA;
12693        } else {
12694            // Preserve data by setting flag
12695            flags |= PackageManager.DELETE_KEEP_DATA;
12696        }
12697        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12698                allUserHandles, perUserInstalled, outInfo, writeSettings);
12699        if (!ret) {
12700            return false;
12701        }
12702        // writer
12703        synchronized (mPackages) {
12704            // Reinstate the old system package
12705            mSettings.enableSystemPackageLPw(newPs.name);
12706            // Remove any native libraries from the upgraded package.
12707            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12708        }
12709        // Install the system package
12710        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12711        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12712        if (locationIsPrivileged(disabledPs.codePath)) {
12713            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12714        }
12715
12716        final PackageParser.Package newPkg;
12717        try {
12718            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12719        } catch (PackageManagerException e) {
12720            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12721            return false;
12722        }
12723
12724        // writer
12725        synchronized (mPackages) {
12726            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12727            updatePermissionsLPw(newPkg.packageName, newPkg,
12728                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12729            if (applyUserRestrictions) {
12730                if (DEBUG_REMOVE) {
12731                    Slog.d(TAG, "Propagating install state across reinstall");
12732                }
12733                for (int i = 0; i < allUserHandles.length; i++) {
12734                    if (DEBUG_REMOVE) {
12735                        Slog.d(TAG, "    user " + allUserHandles[i]
12736                                + " => " + perUserInstalled[i]);
12737                    }
12738                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12739                }
12740                // Regardless of writeSettings we need to ensure that this restriction
12741                // state propagation is persisted
12742                mSettings.writeAllUsersPackageRestrictionsLPr();
12743            }
12744            // can downgrade to reader here
12745            if (writeSettings) {
12746                mSettings.writeLPr();
12747            }
12748        }
12749        return true;
12750    }
12751
12752    private boolean deleteInstalledPackageLI(PackageSetting ps,
12753            boolean deleteCodeAndResources, int flags,
12754            int[] allUserHandles, boolean[] perUserInstalled,
12755            PackageRemovedInfo outInfo, boolean writeSettings) {
12756        if (outInfo != null) {
12757            outInfo.uid = ps.appId;
12758        }
12759
12760        // Delete package data from internal structures and also remove data if flag is set
12761        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12762
12763        // Delete application code and resources
12764        if (deleteCodeAndResources && (outInfo != null)) {
12765            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12766                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12767            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12768        }
12769        return true;
12770    }
12771
12772    @Override
12773    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12774            int userId) {
12775        mContext.enforceCallingOrSelfPermission(
12776                android.Manifest.permission.DELETE_PACKAGES, null);
12777        synchronized (mPackages) {
12778            PackageSetting ps = mSettings.mPackages.get(packageName);
12779            if (ps == null) {
12780                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12781                return false;
12782            }
12783            if (!ps.getInstalled(userId)) {
12784                // Can't block uninstall for an app that is not installed or enabled.
12785                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12786                return false;
12787            }
12788            ps.setBlockUninstall(blockUninstall, userId);
12789            mSettings.writePackageRestrictionsLPr(userId);
12790        }
12791        return true;
12792    }
12793
12794    @Override
12795    public boolean getBlockUninstallForUser(String packageName, int userId) {
12796        synchronized (mPackages) {
12797            PackageSetting ps = mSettings.mPackages.get(packageName);
12798            if (ps == null) {
12799                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12800                return false;
12801            }
12802            return ps.getBlockUninstall(userId);
12803        }
12804    }
12805
12806    /*
12807     * This method handles package deletion in general
12808     */
12809    private boolean deletePackageLI(String packageName, UserHandle user,
12810            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12811            int flags, PackageRemovedInfo outInfo,
12812            boolean writeSettings) {
12813        if (packageName == null) {
12814            Slog.w(TAG, "Attempt to delete null packageName.");
12815            return false;
12816        }
12817        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12818        PackageSetting ps;
12819        boolean dataOnly = false;
12820        int removeUser = -1;
12821        int appId = -1;
12822        synchronized (mPackages) {
12823            ps = mSettings.mPackages.get(packageName);
12824            if (ps == null) {
12825                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12826                return false;
12827            }
12828            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12829                    && user.getIdentifier() != UserHandle.USER_ALL) {
12830                // The caller is asking that the package only be deleted for a single
12831                // user.  To do this, we just mark its uninstalled state and delete
12832                // its data.  If this is a system app, we only allow this to happen if
12833                // they have set the special DELETE_SYSTEM_APP which requests different
12834                // semantics than normal for uninstalling system apps.
12835                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12836                ps.setUserState(user.getIdentifier(),
12837                        COMPONENT_ENABLED_STATE_DEFAULT,
12838                        false, //installed
12839                        true,  //stopped
12840                        true,  //notLaunched
12841                        false, //hidden
12842                        null, null, null,
12843                        false, // blockUninstall
12844                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12845                if (!isSystemApp(ps)) {
12846                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12847                        // Other user still have this package installed, so all
12848                        // we need to do is clear this user's data and save that
12849                        // it is uninstalled.
12850                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12851                        removeUser = user.getIdentifier();
12852                        appId = ps.appId;
12853                        scheduleWritePackageRestrictionsLocked(removeUser);
12854                    } else {
12855                        // We need to set it back to 'installed' so the uninstall
12856                        // broadcasts will be sent correctly.
12857                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12858                        ps.setInstalled(true, user.getIdentifier());
12859                    }
12860                } else {
12861                    // This is a system app, so we assume that the
12862                    // other users still have this package installed, so all
12863                    // we need to do is clear this user's data and save that
12864                    // it is uninstalled.
12865                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12866                    removeUser = user.getIdentifier();
12867                    appId = ps.appId;
12868                    scheduleWritePackageRestrictionsLocked(removeUser);
12869                }
12870            }
12871        }
12872
12873        if (removeUser >= 0) {
12874            // From above, we determined that we are deleting this only
12875            // for a single user.  Continue the work here.
12876            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12877            if (outInfo != null) {
12878                outInfo.removedPackage = packageName;
12879                outInfo.removedAppId = appId;
12880                outInfo.removedUsers = new int[] {removeUser};
12881            }
12882            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12883            removeKeystoreDataIfNeeded(removeUser, appId);
12884            schedulePackageCleaning(packageName, removeUser, false);
12885            synchronized (mPackages) {
12886                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12887                    scheduleWritePackageRestrictionsLocked(removeUser);
12888                }
12889                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12890                        removeUser);
12891            }
12892            return true;
12893        }
12894
12895        if (dataOnly) {
12896            // Delete application data first
12897            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12898            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12899            return true;
12900        }
12901
12902        boolean ret = false;
12903        if (isSystemApp(ps)) {
12904            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12905            // When an updated system application is deleted we delete the existing resources as well and
12906            // fall back to existing code in system partition
12907            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12908                    flags, outInfo, writeSettings);
12909        } else {
12910            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12911            // Kill application pre-emptively especially for apps on sd.
12912            killApplication(packageName, ps.appId, "uninstall pkg");
12913            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12914                    allUserHandles, perUserInstalled,
12915                    outInfo, writeSettings);
12916        }
12917
12918        return ret;
12919    }
12920
12921    private final class ClearStorageConnection implements ServiceConnection {
12922        IMediaContainerService mContainerService;
12923
12924        @Override
12925        public void onServiceConnected(ComponentName name, IBinder service) {
12926            synchronized (this) {
12927                mContainerService = IMediaContainerService.Stub.asInterface(service);
12928                notifyAll();
12929            }
12930        }
12931
12932        @Override
12933        public void onServiceDisconnected(ComponentName name) {
12934        }
12935    }
12936
12937    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12938        final boolean mounted;
12939        if (Environment.isExternalStorageEmulated()) {
12940            mounted = true;
12941        } else {
12942            final String status = Environment.getExternalStorageState();
12943
12944            mounted = status.equals(Environment.MEDIA_MOUNTED)
12945                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12946        }
12947
12948        if (!mounted) {
12949            return;
12950        }
12951
12952        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12953        int[] users;
12954        if (userId == UserHandle.USER_ALL) {
12955            users = sUserManager.getUserIds();
12956        } else {
12957            users = new int[] { userId };
12958        }
12959        final ClearStorageConnection conn = new ClearStorageConnection();
12960        if (mContext.bindServiceAsUser(
12961                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12962            try {
12963                for (int curUser : users) {
12964                    long timeout = SystemClock.uptimeMillis() + 5000;
12965                    synchronized (conn) {
12966                        long now = SystemClock.uptimeMillis();
12967                        while (conn.mContainerService == null && now < timeout) {
12968                            try {
12969                                conn.wait(timeout - now);
12970                            } catch (InterruptedException e) {
12971                            }
12972                        }
12973                    }
12974                    if (conn.mContainerService == null) {
12975                        return;
12976                    }
12977
12978                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12979                    clearDirectory(conn.mContainerService,
12980                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12981                    if (allData) {
12982                        clearDirectory(conn.mContainerService,
12983                                userEnv.buildExternalStorageAppDataDirs(packageName));
12984                        clearDirectory(conn.mContainerService,
12985                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12986                    }
12987                }
12988            } finally {
12989                mContext.unbindService(conn);
12990            }
12991        }
12992    }
12993
12994    @Override
12995    public void clearApplicationUserData(final String packageName,
12996            final IPackageDataObserver observer, final int userId) {
12997        mContext.enforceCallingOrSelfPermission(
12998                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12999        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13000        // Queue up an async operation since the package deletion may take a little while.
13001        mHandler.post(new Runnable() {
13002            public void run() {
13003                mHandler.removeCallbacks(this);
13004                final boolean succeeded;
13005                synchronized (mInstallLock) {
13006                    succeeded = clearApplicationUserDataLI(packageName, userId);
13007                }
13008                clearExternalStorageDataSync(packageName, userId, true);
13009                if (succeeded) {
13010                    // invoke DeviceStorageMonitor's update method to clear any notifications
13011                    DeviceStorageMonitorInternal
13012                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13013                    if (dsm != null) {
13014                        dsm.checkMemory();
13015                    }
13016                }
13017                if(observer != null) {
13018                    try {
13019                        observer.onRemoveCompleted(packageName, succeeded);
13020                    } catch (RemoteException e) {
13021                        Log.i(TAG, "Observer no longer exists.");
13022                    }
13023                } //end if observer
13024            } //end run
13025        });
13026    }
13027
13028    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13029        if (packageName == null) {
13030            Slog.w(TAG, "Attempt to delete null packageName.");
13031            return false;
13032        }
13033
13034        // Try finding details about the requested package
13035        PackageParser.Package pkg;
13036        synchronized (mPackages) {
13037            pkg = mPackages.get(packageName);
13038            if (pkg == null) {
13039                final PackageSetting ps = mSettings.mPackages.get(packageName);
13040                if (ps != null) {
13041                    pkg = ps.pkg;
13042                }
13043            }
13044
13045            if (pkg == null) {
13046                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13047                return false;
13048            }
13049
13050            PackageSetting ps = (PackageSetting) pkg.mExtras;
13051            PermissionsState permissionsState = ps.getPermissionsState();
13052            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
13053        }
13054
13055        // Always delete data directories for package, even if we found no other
13056        // record of app. This helps users recover from UID mismatches without
13057        // resorting to a full data wipe.
13058        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13059        if (retCode < 0) {
13060            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13061            return false;
13062        }
13063
13064        final int appId = pkg.applicationInfo.uid;
13065        removeKeystoreDataIfNeeded(userId, appId);
13066
13067        // Create a native library symlink only if we have native libraries
13068        // and if the native libraries are 32 bit libraries. We do not provide
13069        // this symlink for 64 bit libraries.
13070        if (pkg.applicationInfo.primaryCpuAbi != null &&
13071                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13072            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13073            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13074                    nativeLibPath, userId) < 0) {
13075                Slog.w(TAG, "Failed linking native library dir");
13076                return false;
13077            }
13078        }
13079
13080        return true;
13081    }
13082
13083
13084    /**
13085     * Revokes granted runtime permissions and clears resettable flags
13086     * which are flags that can be set by a user interaction.
13087     *
13088     * @param permissionsState The permission state to reset.
13089     * @param userId The device user for which to do a reset.
13090     */
13091    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13092            PermissionsState permissionsState, int userId) {
13093        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13094                | PackageManager.FLAG_PERMISSION_USER_FIXED
13095                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13096
13097        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13098    }
13099
13100    /**
13101     * Revokes granted runtime permissions and clears all flags.
13102     *
13103     * @param permissionsState The permission state to reset.
13104     * @param userId The device user for which to do a reset.
13105     */
13106    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13107            PermissionsState permissionsState, int userId) {
13108        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13109                PackageManager.MASK_PERMISSION_FLAGS);
13110    }
13111
13112    /**
13113     * Revokes granted runtime permissions and clears certain flags.
13114     *
13115     * @param permissionsState The permission state to reset.
13116     * @param userId The device user for which to do a reset.
13117     * @param flags The flags that is going to be reset.
13118     */
13119    private void revokeRuntimePermissionsAndClearFlagsLocked(
13120            PermissionsState permissionsState, final int userId, int flags) {
13121        boolean needsWrite = false;
13122
13123        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13124            BasePermission bp = mSettings.mPermissions.get(state.getName());
13125            if (bp != null) {
13126                permissionsState.revokeRuntimePermission(bp, userId);
13127                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13128                needsWrite = true;
13129            }
13130        }
13131
13132        // Ensure default permissions are never cleared.
13133        mHandler.post(new Runnable() {
13134            @Override
13135            public void run() {
13136                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13137            }
13138        });
13139
13140        if (needsWrite) {
13141            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13142        }
13143    }
13144
13145    /**
13146     * Remove entries from the keystore daemon. Will only remove it if the
13147     * {@code appId} is valid.
13148     */
13149    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13150        if (appId < 0) {
13151            return;
13152        }
13153
13154        final KeyStore keyStore = KeyStore.getInstance();
13155        if (keyStore != null) {
13156            if (userId == UserHandle.USER_ALL) {
13157                for (final int individual : sUserManager.getUserIds()) {
13158                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13159                }
13160            } else {
13161                keyStore.clearUid(UserHandle.getUid(userId, appId));
13162            }
13163        } else {
13164            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13165        }
13166    }
13167
13168    @Override
13169    public void deleteApplicationCacheFiles(final String packageName,
13170            final IPackageDataObserver observer) {
13171        mContext.enforceCallingOrSelfPermission(
13172                android.Manifest.permission.DELETE_CACHE_FILES, null);
13173        // Queue up an async operation since the package deletion may take a little while.
13174        final int userId = UserHandle.getCallingUserId();
13175        mHandler.post(new Runnable() {
13176            public void run() {
13177                mHandler.removeCallbacks(this);
13178                final boolean succeded;
13179                synchronized (mInstallLock) {
13180                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13181                }
13182                clearExternalStorageDataSync(packageName, userId, false);
13183                if (observer != null) {
13184                    try {
13185                        observer.onRemoveCompleted(packageName, succeded);
13186                    } catch (RemoteException e) {
13187                        Log.i(TAG, "Observer no longer exists.");
13188                    }
13189                } //end if observer
13190            } //end run
13191        });
13192    }
13193
13194    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13195        if (packageName == null) {
13196            Slog.w(TAG, "Attempt to delete null packageName.");
13197            return false;
13198        }
13199        PackageParser.Package p;
13200        synchronized (mPackages) {
13201            p = mPackages.get(packageName);
13202        }
13203        if (p == null) {
13204            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13205            return false;
13206        }
13207        final ApplicationInfo applicationInfo = p.applicationInfo;
13208        if (applicationInfo == null) {
13209            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13210            return false;
13211        }
13212        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13213        if (retCode < 0) {
13214            Slog.w(TAG, "Couldn't remove cache files for package: "
13215                       + packageName + " u" + userId);
13216            return false;
13217        }
13218        return true;
13219    }
13220
13221    @Override
13222    public void getPackageSizeInfo(final String packageName, int userHandle,
13223            final IPackageStatsObserver observer) {
13224        mContext.enforceCallingOrSelfPermission(
13225                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13226        if (packageName == null) {
13227            throw new IllegalArgumentException("Attempt to get size of null packageName");
13228        }
13229
13230        PackageStats stats = new PackageStats(packageName, userHandle);
13231
13232        /*
13233         * Queue up an async operation since the package measurement may take a
13234         * little while.
13235         */
13236        Message msg = mHandler.obtainMessage(INIT_COPY);
13237        msg.obj = new MeasureParams(stats, observer);
13238        mHandler.sendMessage(msg);
13239    }
13240
13241    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13242            PackageStats pStats) {
13243        if (packageName == null) {
13244            Slog.w(TAG, "Attempt to get size of null packageName.");
13245            return false;
13246        }
13247        PackageParser.Package p;
13248        boolean dataOnly = false;
13249        String libDirRoot = null;
13250        String asecPath = null;
13251        PackageSetting ps = null;
13252        synchronized (mPackages) {
13253            p = mPackages.get(packageName);
13254            ps = mSettings.mPackages.get(packageName);
13255            if(p == null) {
13256                dataOnly = true;
13257                if((ps == null) || (ps.pkg == null)) {
13258                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13259                    return false;
13260                }
13261                p = ps.pkg;
13262            }
13263            if (ps != null) {
13264                libDirRoot = ps.legacyNativeLibraryPathString;
13265            }
13266            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13267                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13268                if (secureContainerId != null) {
13269                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13270                }
13271            }
13272        }
13273        String publicSrcDir = null;
13274        if(!dataOnly) {
13275            final ApplicationInfo applicationInfo = p.applicationInfo;
13276            if (applicationInfo == null) {
13277                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13278                return false;
13279            }
13280            if (p.isForwardLocked()) {
13281                publicSrcDir = applicationInfo.getBaseResourcePath();
13282            }
13283        }
13284        // TODO: extend to measure size of split APKs
13285        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13286        // not just the first level.
13287        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13288        // just the primary.
13289        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13290        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13291                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13292        if (res < 0) {
13293            return false;
13294        }
13295
13296        // Fix-up for forward-locked applications in ASEC containers.
13297        if (!isExternal(p)) {
13298            pStats.codeSize += pStats.externalCodeSize;
13299            pStats.externalCodeSize = 0L;
13300        }
13301
13302        return true;
13303    }
13304
13305
13306    @Override
13307    public void addPackageToPreferred(String packageName) {
13308        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13309    }
13310
13311    @Override
13312    public void removePackageFromPreferred(String packageName) {
13313        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13314    }
13315
13316    @Override
13317    public List<PackageInfo> getPreferredPackages(int flags) {
13318        return new ArrayList<PackageInfo>();
13319    }
13320
13321    private int getUidTargetSdkVersionLockedLPr(int uid) {
13322        Object obj = mSettings.getUserIdLPr(uid);
13323        if (obj instanceof SharedUserSetting) {
13324            final SharedUserSetting sus = (SharedUserSetting) obj;
13325            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13326            final Iterator<PackageSetting> it = sus.packages.iterator();
13327            while (it.hasNext()) {
13328                final PackageSetting ps = it.next();
13329                if (ps.pkg != null) {
13330                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13331                    if (v < vers) vers = v;
13332                }
13333            }
13334            return vers;
13335        } else if (obj instanceof PackageSetting) {
13336            final PackageSetting ps = (PackageSetting) obj;
13337            if (ps.pkg != null) {
13338                return ps.pkg.applicationInfo.targetSdkVersion;
13339            }
13340        }
13341        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13342    }
13343
13344    @Override
13345    public void addPreferredActivity(IntentFilter filter, int match,
13346            ComponentName[] set, ComponentName activity, int userId) {
13347        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13348                "Adding preferred");
13349    }
13350
13351    private void addPreferredActivityInternal(IntentFilter filter, int match,
13352            ComponentName[] set, ComponentName activity, boolean always, int userId,
13353            String opname) {
13354        // writer
13355        int callingUid = Binder.getCallingUid();
13356        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13357        if (filter.countActions() == 0) {
13358            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13359            return;
13360        }
13361        synchronized (mPackages) {
13362            if (mContext.checkCallingOrSelfPermission(
13363                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13364                    != PackageManager.PERMISSION_GRANTED) {
13365                if (getUidTargetSdkVersionLockedLPr(callingUid)
13366                        < Build.VERSION_CODES.FROYO) {
13367                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13368                            + callingUid);
13369                    return;
13370                }
13371                mContext.enforceCallingOrSelfPermission(
13372                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13373            }
13374
13375            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13376            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13377                    + userId + ":");
13378            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13379            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13380            scheduleWritePackageRestrictionsLocked(userId);
13381        }
13382    }
13383
13384    @Override
13385    public void replacePreferredActivity(IntentFilter filter, int match,
13386            ComponentName[] set, ComponentName activity, int userId) {
13387        if (filter.countActions() != 1) {
13388            throw new IllegalArgumentException(
13389                    "replacePreferredActivity expects filter to have only 1 action.");
13390        }
13391        if (filter.countDataAuthorities() != 0
13392                || filter.countDataPaths() != 0
13393                || filter.countDataSchemes() > 1
13394                || filter.countDataTypes() != 0) {
13395            throw new IllegalArgumentException(
13396                    "replacePreferredActivity expects filter to have no data authorities, " +
13397                    "paths, or types; and at most one scheme.");
13398        }
13399
13400        final int callingUid = Binder.getCallingUid();
13401        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13402        synchronized (mPackages) {
13403            if (mContext.checkCallingOrSelfPermission(
13404                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13405                    != PackageManager.PERMISSION_GRANTED) {
13406                if (getUidTargetSdkVersionLockedLPr(callingUid)
13407                        < Build.VERSION_CODES.FROYO) {
13408                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13409                            + Binder.getCallingUid());
13410                    return;
13411                }
13412                mContext.enforceCallingOrSelfPermission(
13413                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13414            }
13415
13416            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13417            if (pir != null) {
13418                // Get all of the existing entries that exactly match this filter.
13419                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13420                if (existing != null && existing.size() == 1) {
13421                    PreferredActivity cur = existing.get(0);
13422                    if (DEBUG_PREFERRED) {
13423                        Slog.i(TAG, "Checking replace of preferred:");
13424                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13425                        if (!cur.mPref.mAlways) {
13426                            Slog.i(TAG, "  -- CUR; not mAlways!");
13427                        } else {
13428                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13429                            Slog.i(TAG, "  -- CUR: mSet="
13430                                    + Arrays.toString(cur.mPref.mSetComponents));
13431                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13432                            Slog.i(TAG, "  -- NEW: mMatch="
13433                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13434                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13435                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13436                        }
13437                    }
13438                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13439                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13440                            && cur.mPref.sameSet(set)) {
13441                        // Setting the preferred activity to what it happens to be already
13442                        if (DEBUG_PREFERRED) {
13443                            Slog.i(TAG, "Replacing with same preferred activity "
13444                                    + cur.mPref.mShortComponent + " for user "
13445                                    + userId + ":");
13446                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13447                        }
13448                        return;
13449                    }
13450                }
13451
13452                if (existing != null) {
13453                    if (DEBUG_PREFERRED) {
13454                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13455                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13456                    }
13457                    for (int i = 0; i < existing.size(); i++) {
13458                        PreferredActivity pa = existing.get(i);
13459                        if (DEBUG_PREFERRED) {
13460                            Slog.i(TAG, "Removing existing preferred activity "
13461                                    + pa.mPref.mComponent + ":");
13462                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13463                        }
13464                        pir.removeFilter(pa);
13465                    }
13466                }
13467            }
13468            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13469                    "Replacing preferred");
13470        }
13471    }
13472
13473    @Override
13474    public void clearPackagePreferredActivities(String packageName) {
13475        final int uid = Binder.getCallingUid();
13476        // writer
13477        synchronized (mPackages) {
13478            PackageParser.Package pkg = mPackages.get(packageName);
13479            if (pkg == null || pkg.applicationInfo.uid != uid) {
13480                if (mContext.checkCallingOrSelfPermission(
13481                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13482                        != PackageManager.PERMISSION_GRANTED) {
13483                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13484                            < Build.VERSION_CODES.FROYO) {
13485                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13486                                + Binder.getCallingUid());
13487                        return;
13488                    }
13489                    mContext.enforceCallingOrSelfPermission(
13490                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13491                }
13492            }
13493
13494            int user = UserHandle.getCallingUserId();
13495            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13496                scheduleWritePackageRestrictionsLocked(user);
13497            }
13498        }
13499    }
13500
13501    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13502    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13503        ArrayList<PreferredActivity> removed = null;
13504        boolean changed = false;
13505        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13506            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13507            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13508            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13509                continue;
13510            }
13511            Iterator<PreferredActivity> it = pir.filterIterator();
13512            while (it.hasNext()) {
13513                PreferredActivity pa = it.next();
13514                // Mark entry for removal only if it matches the package name
13515                // and the entry is of type "always".
13516                if (packageName == null ||
13517                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13518                                && pa.mPref.mAlways)) {
13519                    if (removed == null) {
13520                        removed = new ArrayList<PreferredActivity>();
13521                    }
13522                    removed.add(pa);
13523                }
13524            }
13525            if (removed != null) {
13526                for (int j=0; j<removed.size(); j++) {
13527                    PreferredActivity pa = removed.get(j);
13528                    pir.removeFilter(pa);
13529                }
13530                changed = true;
13531            }
13532        }
13533        return changed;
13534    }
13535
13536    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13537    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13538        if (userId == UserHandle.USER_ALL) {
13539            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13540                    sUserManager.getUserIds())) {
13541                for (int oneUserId : sUserManager.getUserIds()) {
13542                    scheduleWritePackageRestrictionsLocked(oneUserId);
13543                }
13544            }
13545        } else {
13546            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13547                scheduleWritePackageRestrictionsLocked(userId);
13548            }
13549        }
13550    }
13551
13552
13553    void clearDefaultBrowserIfNeeded(String packageName) {
13554        for (int oneUserId : sUserManager.getUserIds()) {
13555            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13556            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13557            if (packageName.equals(defaultBrowserPackageName)) {
13558                setDefaultBrowserPackageName(null, oneUserId);
13559            }
13560        }
13561    }
13562
13563    @Override
13564    public void resetPreferredActivities(int userId) {
13565        mContext.enforceCallingOrSelfPermission(
13566                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13567        // writer
13568        synchronized (mPackages) {
13569            clearPackagePreferredActivitiesLPw(null, userId);
13570            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13571            applyFactoryDefaultBrowserLPw(userId);
13572
13573            scheduleWritePackageRestrictionsLocked(userId);
13574        }
13575    }
13576
13577    @Override
13578    public int getPreferredActivities(List<IntentFilter> outFilters,
13579            List<ComponentName> outActivities, String packageName) {
13580
13581        int num = 0;
13582        final int userId = UserHandle.getCallingUserId();
13583        // reader
13584        synchronized (mPackages) {
13585            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13586            if (pir != null) {
13587                final Iterator<PreferredActivity> it = pir.filterIterator();
13588                while (it.hasNext()) {
13589                    final PreferredActivity pa = it.next();
13590                    if (packageName == null
13591                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13592                                    && pa.mPref.mAlways)) {
13593                        if (outFilters != null) {
13594                            outFilters.add(new IntentFilter(pa));
13595                        }
13596                        if (outActivities != null) {
13597                            outActivities.add(pa.mPref.mComponent);
13598                        }
13599                    }
13600                }
13601            }
13602        }
13603
13604        return num;
13605    }
13606
13607    @Override
13608    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13609            int userId) {
13610        int callingUid = Binder.getCallingUid();
13611        if (callingUid != Process.SYSTEM_UID) {
13612            throw new SecurityException(
13613                    "addPersistentPreferredActivity can only be run by the system");
13614        }
13615        if (filter.countActions() == 0) {
13616            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13617            return;
13618        }
13619        synchronized (mPackages) {
13620            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13621                    " :");
13622            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13623            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13624                    new PersistentPreferredActivity(filter, activity));
13625            scheduleWritePackageRestrictionsLocked(userId);
13626        }
13627    }
13628
13629    @Override
13630    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13631        int callingUid = Binder.getCallingUid();
13632        if (callingUid != Process.SYSTEM_UID) {
13633            throw new SecurityException(
13634                    "clearPackagePersistentPreferredActivities can only be run by the system");
13635        }
13636        ArrayList<PersistentPreferredActivity> removed = null;
13637        boolean changed = false;
13638        synchronized (mPackages) {
13639            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13640                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13641                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13642                        .valueAt(i);
13643                if (userId != thisUserId) {
13644                    continue;
13645                }
13646                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13647                while (it.hasNext()) {
13648                    PersistentPreferredActivity ppa = it.next();
13649                    // Mark entry for removal only if it matches the package name.
13650                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13651                        if (removed == null) {
13652                            removed = new ArrayList<PersistentPreferredActivity>();
13653                        }
13654                        removed.add(ppa);
13655                    }
13656                }
13657                if (removed != null) {
13658                    for (int j=0; j<removed.size(); j++) {
13659                        PersistentPreferredActivity ppa = removed.get(j);
13660                        ppir.removeFilter(ppa);
13661                    }
13662                    changed = true;
13663                }
13664            }
13665
13666            if (changed) {
13667                scheduleWritePackageRestrictionsLocked(userId);
13668            }
13669        }
13670    }
13671
13672    /**
13673     * Common machinery for picking apart a restored XML blob and passing
13674     * it to a caller-supplied functor to be applied to the running system.
13675     */
13676    private void restoreFromXml(XmlPullParser parser, int userId,
13677            String expectedStartTag, BlobXmlRestorer functor)
13678            throws IOException, XmlPullParserException {
13679        int type;
13680        while ((type = parser.next()) != XmlPullParser.START_TAG
13681                && type != XmlPullParser.END_DOCUMENT) {
13682        }
13683        if (type != XmlPullParser.START_TAG) {
13684            // oops didn't find a start tag?!
13685            if (DEBUG_BACKUP) {
13686                Slog.e(TAG, "Didn't find start tag during restore");
13687            }
13688            return;
13689        }
13690
13691        // this is supposed to be TAG_PREFERRED_BACKUP
13692        if (!expectedStartTag.equals(parser.getName())) {
13693            if (DEBUG_BACKUP) {
13694                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13695            }
13696            return;
13697        }
13698
13699        // skip interfering stuff, then we're aligned with the backing implementation
13700        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13701        functor.apply(parser, userId);
13702    }
13703
13704    private interface BlobXmlRestorer {
13705        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13706    }
13707
13708    /**
13709     * Non-Binder method, support for the backup/restore mechanism: write the
13710     * full set of preferred activities in its canonical XML format.  Returns the
13711     * XML output as a byte array, or null if there is none.
13712     */
13713    @Override
13714    public byte[] getPreferredActivityBackup(int userId) {
13715        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13716            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13717        }
13718
13719        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13720        try {
13721            final XmlSerializer serializer = new FastXmlSerializer();
13722            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13723            serializer.startDocument(null, true);
13724            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13725
13726            synchronized (mPackages) {
13727                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13728            }
13729
13730            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13731            serializer.endDocument();
13732            serializer.flush();
13733        } catch (Exception e) {
13734            if (DEBUG_BACKUP) {
13735                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13736            }
13737            return null;
13738        }
13739
13740        return dataStream.toByteArray();
13741    }
13742
13743    @Override
13744    public void restorePreferredActivities(byte[] backup, int userId) {
13745        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13746            throw new SecurityException("Only the system may call restorePreferredActivities()");
13747        }
13748
13749        try {
13750            final XmlPullParser parser = Xml.newPullParser();
13751            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13752            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13753                    new BlobXmlRestorer() {
13754                        @Override
13755                        public void apply(XmlPullParser parser, int userId)
13756                                throws XmlPullParserException, IOException {
13757                            synchronized (mPackages) {
13758                                mSettings.readPreferredActivitiesLPw(parser, userId);
13759                            }
13760                        }
13761                    } );
13762        } catch (Exception e) {
13763            if (DEBUG_BACKUP) {
13764                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13765            }
13766        }
13767    }
13768
13769    /**
13770     * Non-Binder method, support for the backup/restore mechanism: write the
13771     * default browser (etc) settings in its canonical XML format.  Returns the default
13772     * browser XML representation as a byte array, or null if there is none.
13773     */
13774    @Override
13775    public byte[] getDefaultAppsBackup(int userId) {
13776        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13777            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13778        }
13779
13780        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13781        try {
13782            final XmlSerializer serializer = new FastXmlSerializer();
13783            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13784            serializer.startDocument(null, true);
13785            serializer.startTag(null, TAG_DEFAULT_APPS);
13786
13787            synchronized (mPackages) {
13788                mSettings.writeDefaultAppsLPr(serializer, userId);
13789            }
13790
13791            serializer.endTag(null, TAG_DEFAULT_APPS);
13792            serializer.endDocument();
13793            serializer.flush();
13794        } catch (Exception e) {
13795            if (DEBUG_BACKUP) {
13796                Slog.e(TAG, "Unable to write default apps for backup", e);
13797            }
13798            return null;
13799        }
13800
13801        return dataStream.toByteArray();
13802    }
13803
13804    @Override
13805    public void restoreDefaultApps(byte[] backup, int userId) {
13806        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13807            throw new SecurityException("Only the system may call restoreDefaultApps()");
13808        }
13809
13810        try {
13811            final XmlPullParser parser = Xml.newPullParser();
13812            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13813            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13814                    new BlobXmlRestorer() {
13815                        @Override
13816                        public void apply(XmlPullParser parser, int userId)
13817                                throws XmlPullParserException, IOException {
13818                            synchronized (mPackages) {
13819                                mSettings.readDefaultAppsLPw(parser, userId);
13820                            }
13821                        }
13822                    } );
13823        } catch (Exception e) {
13824            if (DEBUG_BACKUP) {
13825                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13826            }
13827        }
13828    }
13829
13830    @Override
13831    public byte[] getIntentFilterVerificationBackup(int userId) {
13832        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13833            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13834        }
13835
13836        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13837        try {
13838            final XmlSerializer serializer = new FastXmlSerializer();
13839            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13840            serializer.startDocument(null, true);
13841            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13842
13843            synchronized (mPackages) {
13844                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13845            }
13846
13847            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13848            serializer.endDocument();
13849            serializer.flush();
13850        } catch (Exception e) {
13851            if (DEBUG_BACKUP) {
13852                Slog.e(TAG, "Unable to write default apps for backup", e);
13853            }
13854            return null;
13855        }
13856
13857        return dataStream.toByteArray();
13858    }
13859
13860    @Override
13861    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13862        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13863            throw new SecurityException("Only the system may call restorePreferredActivities()");
13864        }
13865
13866        try {
13867            final XmlPullParser parser = Xml.newPullParser();
13868            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13869            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13870                    new BlobXmlRestorer() {
13871                        @Override
13872                        public void apply(XmlPullParser parser, int userId)
13873                                throws XmlPullParserException, IOException {
13874                            synchronized (mPackages) {
13875                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13876                                mSettings.writeLPr();
13877                            }
13878                        }
13879                    } );
13880        } catch (Exception e) {
13881            if (DEBUG_BACKUP) {
13882                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13883            }
13884        }
13885    }
13886
13887    @Override
13888    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13889            int sourceUserId, int targetUserId, int flags) {
13890        mContext.enforceCallingOrSelfPermission(
13891                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13892        int callingUid = Binder.getCallingUid();
13893        enforceOwnerRights(ownerPackage, callingUid);
13894        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13895        if (intentFilter.countActions() == 0) {
13896            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13897            return;
13898        }
13899        synchronized (mPackages) {
13900            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13901                    ownerPackage, targetUserId, flags);
13902            CrossProfileIntentResolver resolver =
13903                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13904            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13905            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13906            if (existing != null) {
13907                int size = existing.size();
13908                for (int i = 0; i < size; i++) {
13909                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13910                        return;
13911                    }
13912                }
13913            }
13914            resolver.addFilter(newFilter);
13915            scheduleWritePackageRestrictionsLocked(sourceUserId);
13916        }
13917    }
13918
13919    @Override
13920    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13921        mContext.enforceCallingOrSelfPermission(
13922                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13923        int callingUid = Binder.getCallingUid();
13924        enforceOwnerRights(ownerPackage, callingUid);
13925        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13926        synchronized (mPackages) {
13927            CrossProfileIntentResolver resolver =
13928                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13929            ArraySet<CrossProfileIntentFilter> set =
13930                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13931            for (CrossProfileIntentFilter filter : set) {
13932                if (filter.getOwnerPackage().equals(ownerPackage)) {
13933                    resolver.removeFilter(filter);
13934                }
13935            }
13936            scheduleWritePackageRestrictionsLocked(sourceUserId);
13937        }
13938    }
13939
13940    // Enforcing that callingUid is owning pkg on userId
13941    private void enforceOwnerRights(String pkg, int callingUid) {
13942        // The system owns everything.
13943        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13944            return;
13945        }
13946        int callingUserId = UserHandle.getUserId(callingUid);
13947        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13948        if (pi == null) {
13949            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13950                    + callingUserId);
13951        }
13952        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13953            throw new SecurityException("Calling uid " + callingUid
13954                    + " does not own package " + pkg);
13955        }
13956    }
13957
13958    @Override
13959    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13960        Intent intent = new Intent(Intent.ACTION_MAIN);
13961        intent.addCategory(Intent.CATEGORY_HOME);
13962
13963        final int callingUserId = UserHandle.getCallingUserId();
13964        List<ResolveInfo> list = queryIntentActivities(intent, null,
13965                PackageManager.GET_META_DATA, callingUserId);
13966        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13967                true, false, false, callingUserId);
13968
13969        allHomeCandidates.clear();
13970        if (list != null) {
13971            for (ResolveInfo ri : list) {
13972                allHomeCandidates.add(ri);
13973            }
13974        }
13975        return (preferred == null || preferred.activityInfo == null)
13976                ? null
13977                : new ComponentName(preferred.activityInfo.packageName,
13978                        preferred.activityInfo.name);
13979    }
13980
13981    @Override
13982    public void setApplicationEnabledSetting(String appPackageName,
13983            int newState, int flags, int userId, String callingPackage) {
13984        if (!sUserManager.exists(userId)) return;
13985        if (callingPackage == null) {
13986            callingPackage = Integer.toString(Binder.getCallingUid());
13987        }
13988        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13989    }
13990
13991    @Override
13992    public void setComponentEnabledSetting(ComponentName componentName,
13993            int newState, int flags, int userId) {
13994        if (!sUserManager.exists(userId)) return;
13995        setEnabledSetting(componentName.getPackageName(),
13996                componentName.getClassName(), newState, flags, userId, null);
13997    }
13998
13999    private void setEnabledSetting(final String packageName, String className, int newState,
14000            final int flags, int userId, String callingPackage) {
14001        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14002              || newState == COMPONENT_ENABLED_STATE_ENABLED
14003              || newState == COMPONENT_ENABLED_STATE_DISABLED
14004              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14005              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14006            throw new IllegalArgumentException("Invalid new component state: "
14007                    + newState);
14008        }
14009        PackageSetting pkgSetting;
14010        final int uid = Binder.getCallingUid();
14011        final int permission = mContext.checkCallingOrSelfPermission(
14012                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14013        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14014        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14015        boolean sendNow = false;
14016        boolean isApp = (className == null);
14017        String componentName = isApp ? packageName : className;
14018        int packageUid = -1;
14019        ArrayList<String> components;
14020
14021        // writer
14022        synchronized (mPackages) {
14023            pkgSetting = mSettings.mPackages.get(packageName);
14024            if (pkgSetting == null) {
14025                if (className == null) {
14026                    throw new IllegalArgumentException(
14027                            "Unknown package: " + packageName);
14028                }
14029                throw new IllegalArgumentException(
14030                        "Unknown component: " + packageName
14031                        + "/" + className);
14032            }
14033            // Allow root and verify that userId is not being specified by a different user
14034            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14035                throw new SecurityException(
14036                        "Permission Denial: attempt to change component state from pid="
14037                        + Binder.getCallingPid()
14038                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14039            }
14040            if (className == null) {
14041                // We're dealing with an application/package level state change
14042                if (pkgSetting.getEnabled(userId) == newState) {
14043                    // Nothing to do
14044                    return;
14045                }
14046                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14047                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14048                    // Don't care about who enables an app.
14049                    callingPackage = null;
14050                }
14051                pkgSetting.setEnabled(newState, userId, callingPackage);
14052                // pkgSetting.pkg.mSetEnabled = newState;
14053            } else {
14054                // We're dealing with a component level state change
14055                // First, verify that this is a valid class name.
14056                PackageParser.Package pkg = pkgSetting.pkg;
14057                if (pkg == null || !pkg.hasComponentClassName(className)) {
14058                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14059                        throw new IllegalArgumentException("Component class " + className
14060                                + " does not exist in " + packageName);
14061                    } else {
14062                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14063                                + className + " does not exist in " + packageName);
14064                    }
14065                }
14066                switch (newState) {
14067                case COMPONENT_ENABLED_STATE_ENABLED:
14068                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14069                        return;
14070                    }
14071                    break;
14072                case COMPONENT_ENABLED_STATE_DISABLED:
14073                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14074                        return;
14075                    }
14076                    break;
14077                case COMPONENT_ENABLED_STATE_DEFAULT:
14078                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14079                        return;
14080                    }
14081                    break;
14082                default:
14083                    Slog.e(TAG, "Invalid new component state: " + newState);
14084                    return;
14085                }
14086            }
14087            scheduleWritePackageRestrictionsLocked(userId);
14088            components = mPendingBroadcasts.get(userId, packageName);
14089            final boolean newPackage = components == null;
14090            if (newPackage) {
14091                components = new ArrayList<String>();
14092            }
14093            if (!components.contains(componentName)) {
14094                components.add(componentName);
14095            }
14096            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14097                sendNow = true;
14098                // Purge entry from pending broadcast list if another one exists already
14099                // since we are sending one right away.
14100                mPendingBroadcasts.remove(userId, packageName);
14101            } else {
14102                if (newPackage) {
14103                    mPendingBroadcasts.put(userId, packageName, components);
14104                }
14105                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14106                    // Schedule a message
14107                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14108                }
14109            }
14110        }
14111
14112        long callingId = Binder.clearCallingIdentity();
14113        try {
14114            if (sendNow) {
14115                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14116                sendPackageChangedBroadcast(packageName,
14117                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14118            }
14119        } finally {
14120            Binder.restoreCallingIdentity(callingId);
14121        }
14122    }
14123
14124    private void sendPackageChangedBroadcast(String packageName,
14125            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14126        if (DEBUG_INSTALL)
14127            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14128                    + componentNames);
14129        Bundle extras = new Bundle(4);
14130        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14131        String nameList[] = new String[componentNames.size()];
14132        componentNames.toArray(nameList);
14133        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14134        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14135        extras.putInt(Intent.EXTRA_UID, packageUid);
14136        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14137                new int[] {UserHandle.getUserId(packageUid)});
14138    }
14139
14140    @Override
14141    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14142        if (!sUserManager.exists(userId)) return;
14143        final int uid = Binder.getCallingUid();
14144        final int permission = mContext.checkCallingOrSelfPermission(
14145                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14146        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14147        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14148        // writer
14149        synchronized (mPackages) {
14150            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14151                    allowedByPermission, uid, userId)) {
14152                scheduleWritePackageRestrictionsLocked(userId);
14153            }
14154        }
14155    }
14156
14157    @Override
14158    public String getInstallerPackageName(String packageName) {
14159        // reader
14160        synchronized (mPackages) {
14161            return mSettings.getInstallerPackageNameLPr(packageName);
14162        }
14163    }
14164
14165    @Override
14166    public int getApplicationEnabledSetting(String packageName, int userId) {
14167        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14168        int uid = Binder.getCallingUid();
14169        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14170        // reader
14171        synchronized (mPackages) {
14172            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14173        }
14174    }
14175
14176    @Override
14177    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14178        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14179        int uid = Binder.getCallingUid();
14180        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14181        // reader
14182        synchronized (mPackages) {
14183            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14184        }
14185    }
14186
14187    @Override
14188    public void enterSafeMode() {
14189        enforceSystemOrRoot("Only the system can request entering safe mode");
14190
14191        if (!mSystemReady) {
14192            mSafeMode = true;
14193        }
14194    }
14195
14196    @Override
14197    public void systemReady() {
14198        mSystemReady = true;
14199
14200        // Read the compatibilty setting when the system is ready.
14201        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14202                mContext.getContentResolver(),
14203                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14204        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14205        if (DEBUG_SETTINGS) {
14206            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14207        }
14208
14209        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14210
14211        synchronized (mPackages) {
14212            // Verify that all of the preferred activity components actually
14213            // exist.  It is possible for applications to be updated and at
14214            // that point remove a previously declared activity component that
14215            // had been set as a preferred activity.  We try to clean this up
14216            // the next time we encounter that preferred activity, but it is
14217            // possible for the user flow to never be able to return to that
14218            // situation so here we do a sanity check to make sure we haven't
14219            // left any junk around.
14220            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14221            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14222                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14223                removed.clear();
14224                for (PreferredActivity pa : pir.filterSet()) {
14225                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14226                        removed.add(pa);
14227                    }
14228                }
14229                if (removed.size() > 0) {
14230                    for (int r=0; r<removed.size(); r++) {
14231                        PreferredActivity pa = removed.get(r);
14232                        Slog.w(TAG, "Removing dangling preferred activity: "
14233                                + pa.mPref.mComponent);
14234                        pir.removeFilter(pa);
14235                    }
14236                    mSettings.writePackageRestrictionsLPr(
14237                            mSettings.mPreferredActivities.keyAt(i));
14238                }
14239            }
14240
14241            for (int userId : UserManagerService.getInstance().getUserIds()) {
14242                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14243                    grantPermissionsUserIds = ArrayUtils.appendInt(
14244                            grantPermissionsUserIds, userId);
14245                }
14246            }
14247        }
14248        sUserManager.systemReady();
14249
14250        // If we upgraded grant all default permissions before kicking off.
14251        for (int userId : grantPermissionsUserIds) {
14252            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14253        }
14254
14255        // Kick off any messages waiting for system ready
14256        if (mPostSystemReadyMessages != null) {
14257            for (Message msg : mPostSystemReadyMessages) {
14258                msg.sendToTarget();
14259            }
14260            mPostSystemReadyMessages = null;
14261        }
14262
14263        // Watch for external volumes that come and go over time
14264        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14265        storage.registerListener(mStorageListener);
14266
14267        mInstallerService.systemReady();
14268        mPackageDexOptimizer.systemReady();
14269    }
14270
14271    @Override
14272    public boolean isSafeMode() {
14273        return mSafeMode;
14274    }
14275
14276    @Override
14277    public boolean hasSystemUidErrors() {
14278        return mHasSystemUidErrors;
14279    }
14280
14281    static String arrayToString(int[] array) {
14282        StringBuffer buf = new StringBuffer(128);
14283        buf.append('[');
14284        if (array != null) {
14285            for (int i=0; i<array.length; i++) {
14286                if (i > 0) buf.append(", ");
14287                buf.append(array[i]);
14288            }
14289        }
14290        buf.append(']');
14291        return buf.toString();
14292    }
14293
14294    static class DumpState {
14295        public static final int DUMP_LIBS = 1 << 0;
14296        public static final int DUMP_FEATURES = 1 << 1;
14297        public static final int DUMP_RESOLVERS = 1 << 2;
14298        public static final int DUMP_PERMISSIONS = 1 << 3;
14299        public static final int DUMP_PACKAGES = 1 << 4;
14300        public static final int DUMP_SHARED_USERS = 1 << 5;
14301        public static final int DUMP_MESSAGES = 1 << 6;
14302        public static final int DUMP_PROVIDERS = 1 << 7;
14303        public static final int DUMP_VERIFIERS = 1 << 8;
14304        public static final int DUMP_PREFERRED = 1 << 9;
14305        public static final int DUMP_PREFERRED_XML = 1 << 10;
14306        public static final int DUMP_KEYSETS = 1 << 11;
14307        public static final int DUMP_VERSION = 1 << 12;
14308        public static final int DUMP_INSTALLS = 1 << 13;
14309        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14310        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14311
14312        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14313
14314        private int mTypes;
14315
14316        private int mOptions;
14317
14318        private boolean mTitlePrinted;
14319
14320        private SharedUserSetting mSharedUser;
14321
14322        public boolean isDumping(int type) {
14323            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14324                return true;
14325            }
14326
14327            return (mTypes & type) != 0;
14328        }
14329
14330        public void setDump(int type) {
14331            mTypes |= type;
14332        }
14333
14334        public boolean isOptionEnabled(int option) {
14335            return (mOptions & option) != 0;
14336        }
14337
14338        public void setOptionEnabled(int option) {
14339            mOptions |= option;
14340        }
14341
14342        public boolean onTitlePrinted() {
14343            final boolean printed = mTitlePrinted;
14344            mTitlePrinted = true;
14345            return printed;
14346        }
14347
14348        public boolean getTitlePrinted() {
14349            return mTitlePrinted;
14350        }
14351
14352        public void setTitlePrinted(boolean enabled) {
14353            mTitlePrinted = enabled;
14354        }
14355
14356        public SharedUserSetting getSharedUser() {
14357            return mSharedUser;
14358        }
14359
14360        public void setSharedUser(SharedUserSetting user) {
14361            mSharedUser = user;
14362        }
14363    }
14364
14365    @Override
14366    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14367        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14368                != PackageManager.PERMISSION_GRANTED) {
14369            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14370                    + Binder.getCallingPid()
14371                    + ", uid=" + Binder.getCallingUid()
14372                    + " without permission "
14373                    + android.Manifest.permission.DUMP);
14374            return;
14375        }
14376
14377        DumpState dumpState = new DumpState();
14378        boolean fullPreferred = false;
14379        boolean checkin = false;
14380
14381        String packageName = null;
14382        ArraySet<String> permissionNames = null;
14383
14384        int opti = 0;
14385        while (opti < args.length) {
14386            String opt = args[opti];
14387            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14388                break;
14389            }
14390            opti++;
14391
14392            if ("-a".equals(opt)) {
14393                // Right now we only know how to print all.
14394            } else if ("-h".equals(opt)) {
14395                pw.println("Package manager dump options:");
14396                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14397                pw.println("    --checkin: dump for a checkin");
14398                pw.println("    -f: print details of intent filters");
14399                pw.println("    -h: print this help");
14400                pw.println("  cmd may be one of:");
14401                pw.println("    l[ibraries]: list known shared libraries");
14402                pw.println("    f[ibraries]: list device features");
14403                pw.println("    k[eysets]: print known keysets");
14404                pw.println("    r[esolvers]: dump intent resolvers");
14405                pw.println("    perm[issions]: dump permissions");
14406                pw.println("    permission [name ...]: dump declaration and use of given permission");
14407                pw.println("    pref[erred]: print preferred package settings");
14408                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14409                pw.println("    prov[iders]: dump content providers");
14410                pw.println("    p[ackages]: dump installed packages");
14411                pw.println("    s[hared-users]: dump shared user IDs");
14412                pw.println("    m[essages]: print collected runtime messages");
14413                pw.println("    v[erifiers]: print package verifier info");
14414                pw.println("    version: print database version info");
14415                pw.println("    write: write current settings now");
14416                pw.println("    <package.name>: info about given package");
14417                pw.println("    installs: details about install sessions");
14418                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14419                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14420                return;
14421            } else if ("--checkin".equals(opt)) {
14422                checkin = true;
14423            } else if ("-f".equals(opt)) {
14424                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14425            } else {
14426                pw.println("Unknown argument: " + opt + "; use -h for help");
14427            }
14428        }
14429
14430        // Is the caller requesting to dump a particular piece of data?
14431        if (opti < args.length) {
14432            String cmd = args[opti];
14433            opti++;
14434            // Is this a package name?
14435            if ("android".equals(cmd) || cmd.contains(".")) {
14436                packageName = cmd;
14437                // When dumping a single package, we always dump all of its
14438                // filter information since the amount of data will be reasonable.
14439                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14440            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14441                dumpState.setDump(DumpState.DUMP_LIBS);
14442            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14443                dumpState.setDump(DumpState.DUMP_FEATURES);
14444            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14445                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14446            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14447                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14448            } else if ("permission".equals(cmd)) {
14449                if (opti >= args.length) {
14450                    pw.println("Error: permission requires permission name");
14451                    return;
14452                }
14453                permissionNames = new ArraySet<>();
14454                while (opti < args.length) {
14455                    permissionNames.add(args[opti]);
14456                    opti++;
14457                }
14458                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14459                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14460            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14461                dumpState.setDump(DumpState.DUMP_PREFERRED);
14462            } else if ("preferred-xml".equals(cmd)) {
14463                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14464                if (opti < args.length && "--full".equals(args[opti])) {
14465                    fullPreferred = true;
14466                    opti++;
14467                }
14468            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14469                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14470            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14471                dumpState.setDump(DumpState.DUMP_PACKAGES);
14472            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14473                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14474            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14475                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14476            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14477                dumpState.setDump(DumpState.DUMP_MESSAGES);
14478            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14479                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14480            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14481                    || "intent-filter-verifiers".equals(cmd)) {
14482                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14483            } else if ("version".equals(cmd)) {
14484                dumpState.setDump(DumpState.DUMP_VERSION);
14485            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14486                dumpState.setDump(DumpState.DUMP_KEYSETS);
14487            } else if ("installs".equals(cmd)) {
14488                dumpState.setDump(DumpState.DUMP_INSTALLS);
14489            } else if ("write".equals(cmd)) {
14490                synchronized (mPackages) {
14491                    mSettings.writeLPr();
14492                    pw.println("Settings written.");
14493                    return;
14494                }
14495            }
14496        }
14497
14498        if (checkin) {
14499            pw.println("vers,1");
14500        }
14501
14502        // reader
14503        synchronized (mPackages) {
14504            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14505                if (!checkin) {
14506                    if (dumpState.onTitlePrinted())
14507                        pw.println();
14508                    pw.println("Database versions:");
14509                    pw.print("  SDK Version:");
14510                    pw.print(" internal=");
14511                    pw.print(mSettings.mInternalSdkPlatform);
14512                    pw.print(" external=");
14513                    pw.println(mSettings.mExternalSdkPlatform);
14514                    pw.print("  DB Version:");
14515                    pw.print(" internal=");
14516                    pw.print(mSettings.mInternalDatabaseVersion);
14517                    pw.print(" external=");
14518                    pw.println(mSettings.mExternalDatabaseVersion);
14519                }
14520            }
14521
14522            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14523                if (!checkin) {
14524                    if (dumpState.onTitlePrinted())
14525                        pw.println();
14526                    pw.println("Verifiers:");
14527                    pw.print("  Required: ");
14528                    pw.print(mRequiredVerifierPackage);
14529                    pw.print(" (uid=");
14530                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14531                    pw.println(")");
14532                } else if (mRequiredVerifierPackage != null) {
14533                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14534                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14535                }
14536            }
14537
14538            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14539                    packageName == null) {
14540                if (mIntentFilterVerifierComponent != null) {
14541                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14542                    if (!checkin) {
14543                        if (dumpState.onTitlePrinted())
14544                            pw.println();
14545                        pw.println("Intent Filter Verifier:");
14546                        pw.print("  Using: ");
14547                        pw.print(verifierPackageName);
14548                        pw.print(" (uid=");
14549                        pw.print(getPackageUid(verifierPackageName, 0));
14550                        pw.println(")");
14551                    } else if (verifierPackageName != null) {
14552                        pw.print("ifv,"); pw.print(verifierPackageName);
14553                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14554                    }
14555                } else {
14556                    pw.println();
14557                    pw.println("No Intent Filter Verifier available!");
14558                }
14559            }
14560
14561            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14562                boolean printedHeader = false;
14563                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14564                while (it.hasNext()) {
14565                    String name = it.next();
14566                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14567                    if (!checkin) {
14568                        if (!printedHeader) {
14569                            if (dumpState.onTitlePrinted())
14570                                pw.println();
14571                            pw.println("Libraries:");
14572                            printedHeader = true;
14573                        }
14574                        pw.print("  ");
14575                    } else {
14576                        pw.print("lib,");
14577                    }
14578                    pw.print(name);
14579                    if (!checkin) {
14580                        pw.print(" -> ");
14581                    }
14582                    if (ent.path != null) {
14583                        if (!checkin) {
14584                            pw.print("(jar) ");
14585                            pw.print(ent.path);
14586                        } else {
14587                            pw.print(",jar,");
14588                            pw.print(ent.path);
14589                        }
14590                    } else {
14591                        if (!checkin) {
14592                            pw.print("(apk) ");
14593                            pw.print(ent.apk);
14594                        } else {
14595                            pw.print(",apk,");
14596                            pw.print(ent.apk);
14597                        }
14598                    }
14599                    pw.println();
14600                }
14601            }
14602
14603            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14604                if (dumpState.onTitlePrinted())
14605                    pw.println();
14606                if (!checkin) {
14607                    pw.println("Features:");
14608                }
14609                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14610                while (it.hasNext()) {
14611                    String name = it.next();
14612                    if (!checkin) {
14613                        pw.print("  ");
14614                    } else {
14615                        pw.print("feat,");
14616                    }
14617                    pw.println(name);
14618                }
14619            }
14620
14621            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14622                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14623                        : "Activity Resolver Table:", "  ", packageName,
14624                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14625                    dumpState.setTitlePrinted(true);
14626                }
14627                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14628                        : "Receiver Resolver Table:", "  ", packageName,
14629                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14630                    dumpState.setTitlePrinted(true);
14631                }
14632                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14633                        : "Service Resolver Table:", "  ", packageName,
14634                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14635                    dumpState.setTitlePrinted(true);
14636                }
14637                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14638                        : "Provider Resolver Table:", "  ", packageName,
14639                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14640                    dumpState.setTitlePrinted(true);
14641                }
14642            }
14643
14644            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14645                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14646                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14647                    int user = mSettings.mPreferredActivities.keyAt(i);
14648                    if (pir.dump(pw,
14649                            dumpState.getTitlePrinted()
14650                                ? "\nPreferred Activities User " + user + ":"
14651                                : "Preferred Activities User " + user + ":", "  ",
14652                            packageName, true, false)) {
14653                        dumpState.setTitlePrinted(true);
14654                    }
14655                }
14656            }
14657
14658            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14659                pw.flush();
14660                FileOutputStream fout = new FileOutputStream(fd);
14661                BufferedOutputStream str = new BufferedOutputStream(fout);
14662                XmlSerializer serializer = new FastXmlSerializer();
14663                try {
14664                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14665                    serializer.startDocument(null, true);
14666                    serializer.setFeature(
14667                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14668                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14669                    serializer.endDocument();
14670                    serializer.flush();
14671                } catch (IllegalArgumentException e) {
14672                    pw.println("Failed writing: " + e);
14673                } catch (IllegalStateException e) {
14674                    pw.println("Failed writing: " + e);
14675                } catch (IOException e) {
14676                    pw.println("Failed writing: " + e);
14677                }
14678            }
14679
14680            if (!checkin
14681                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14682                    && packageName == null) {
14683                pw.println();
14684                int count = mSettings.mPackages.size();
14685                if (count == 0) {
14686                    pw.println("No domain preferred apps!");
14687                    pw.println();
14688                } else {
14689                    final String prefix = "  ";
14690                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14691                    if (allPackageSettings.size() == 0) {
14692                        pw.println("No domain preferred apps!");
14693                        pw.println();
14694                    } else {
14695                        pw.println("Domain preferred apps status:");
14696                        pw.println();
14697                        count = 0;
14698                        for (PackageSetting ps : allPackageSettings) {
14699                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14700                            if (ivi == null || ivi.getPackageName() == null) continue;
14701                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14702                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14703                            pw.println(prefix + "Status: " + ivi.getStatusString());
14704                            pw.println();
14705                            count++;
14706                        }
14707                        if (count == 0) {
14708                            pw.println(prefix + "No domain preferred app status!");
14709                            pw.println();
14710                        }
14711                        for (int userId : sUserManager.getUserIds()) {
14712                            pw.println("Domain preferred apps for User " + userId + ":");
14713                            pw.println();
14714                            count = 0;
14715                            for (PackageSetting ps : allPackageSettings) {
14716                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14717                                if (ivi == null || ivi.getPackageName() == null) {
14718                                    continue;
14719                                }
14720                                final int status = ps.getDomainVerificationStatusForUser(userId);
14721                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14722                                    continue;
14723                                }
14724                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14725                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14726                                String statusStr = IntentFilterVerificationInfo.
14727                                        getStatusStringFromValue(status);
14728                                pw.println(prefix + "Status: " + statusStr);
14729                                pw.println();
14730                                count++;
14731                            }
14732                            if (count == 0) {
14733                                pw.println(prefix + "No domain preferred apps!");
14734                                pw.println();
14735                            }
14736                        }
14737                    }
14738                }
14739            }
14740
14741            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14742                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14743                if (packageName == null && permissionNames == null) {
14744                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14745                        if (iperm == 0) {
14746                            if (dumpState.onTitlePrinted())
14747                                pw.println();
14748                            pw.println("AppOp Permissions:");
14749                        }
14750                        pw.print("  AppOp Permission ");
14751                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14752                        pw.println(":");
14753                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14754                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14755                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14756                        }
14757                    }
14758                }
14759            }
14760
14761            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14762                boolean printedSomething = false;
14763                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14764                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14765                        continue;
14766                    }
14767                    if (!printedSomething) {
14768                        if (dumpState.onTitlePrinted())
14769                            pw.println();
14770                        pw.println("Registered ContentProviders:");
14771                        printedSomething = true;
14772                    }
14773                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14774                    pw.print("    "); pw.println(p.toString());
14775                }
14776                printedSomething = false;
14777                for (Map.Entry<String, PackageParser.Provider> entry :
14778                        mProvidersByAuthority.entrySet()) {
14779                    PackageParser.Provider p = entry.getValue();
14780                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14781                        continue;
14782                    }
14783                    if (!printedSomething) {
14784                        if (dumpState.onTitlePrinted())
14785                            pw.println();
14786                        pw.println("ContentProvider Authorities:");
14787                        printedSomething = true;
14788                    }
14789                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14790                    pw.print("    "); pw.println(p.toString());
14791                    if (p.info != null && p.info.applicationInfo != null) {
14792                        final String appInfo = p.info.applicationInfo.toString();
14793                        pw.print("      applicationInfo="); pw.println(appInfo);
14794                    }
14795                }
14796            }
14797
14798            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14799                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14800            }
14801
14802            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14803                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14804            }
14805
14806            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14807                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14808            }
14809
14810            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14811                // XXX should handle packageName != null by dumping only install data that
14812                // the given package is involved with.
14813                if (dumpState.onTitlePrinted()) pw.println();
14814                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14815            }
14816
14817            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14818                if (dumpState.onTitlePrinted()) pw.println();
14819                mSettings.dumpReadMessagesLPr(pw, dumpState);
14820
14821                pw.println();
14822                pw.println("Package warning messages:");
14823                BufferedReader in = null;
14824                String line = null;
14825                try {
14826                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14827                    while ((line = in.readLine()) != null) {
14828                        if (line.contains("ignored: updated version")) continue;
14829                        pw.println(line);
14830                    }
14831                } catch (IOException ignored) {
14832                } finally {
14833                    IoUtils.closeQuietly(in);
14834                }
14835            }
14836
14837            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14838                BufferedReader in = null;
14839                String line = null;
14840                try {
14841                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14842                    while ((line = in.readLine()) != null) {
14843                        if (line.contains("ignored: updated version")) continue;
14844                        pw.print("msg,");
14845                        pw.println(line);
14846                    }
14847                } catch (IOException ignored) {
14848                } finally {
14849                    IoUtils.closeQuietly(in);
14850                }
14851            }
14852        }
14853    }
14854
14855    // ------- apps on sdcard specific code -------
14856    static final boolean DEBUG_SD_INSTALL = false;
14857
14858    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14859
14860    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14861
14862    private boolean mMediaMounted = false;
14863
14864    static String getEncryptKey() {
14865        try {
14866            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14867                    SD_ENCRYPTION_KEYSTORE_NAME);
14868            if (sdEncKey == null) {
14869                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14870                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14871                if (sdEncKey == null) {
14872                    Slog.e(TAG, "Failed to create encryption keys");
14873                    return null;
14874                }
14875            }
14876            return sdEncKey;
14877        } catch (NoSuchAlgorithmException nsae) {
14878            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14879            return null;
14880        } catch (IOException ioe) {
14881            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14882            return null;
14883        }
14884    }
14885
14886    /*
14887     * Update media status on PackageManager.
14888     */
14889    @Override
14890    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14891        int callingUid = Binder.getCallingUid();
14892        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14893            throw new SecurityException("Media status can only be updated by the system");
14894        }
14895        // reader; this apparently protects mMediaMounted, but should probably
14896        // be a different lock in that case.
14897        synchronized (mPackages) {
14898            Log.i(TAG, "Updating external media status from "
14899                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14900                    + (mediaStatus ? "mounted" : "unmounted"));
14901            if (DEBUG_SD_INSTALL)
14902                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14903                        + ", mMediaMounted=" + mMediaMounted);
14904            if (mediaStatus == mMediaMounted) {
14905                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14906                        : 0, -1);
14907                mHandler.sendMessage(msg);
14908                return;
14909            }
14910            mMediaMounted = mediaStatus;
14911        }
14912        // Queue up an async operation since the package installation may take a
14913        // little while.
14914        mHandler.post(new Runnable() {
14915            public void run() {
14916                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14917            }
14918        });
14919    }
14920
14921    /**
14922     * Called by MountService when the initial ASECs to scan are available.
14923     * Should block until all the ASEC containers are finished being scanned.
14924     */
14925    public void scanAvailableAsecs() {
14926        updateExternalMediaStatusInner(true, false, false);
14927        if (mShouldRestoreconData) {
14928            SELinuxMMAC.setRestoreconDone();
14929            mShouldRestoreconData = false;
14930        }
14931    }
14932
14933    /*
14934     * Collect information of applications on external media, map them against
14935     * existing containers and update information based on current mount status.
14936     * Please note that we always have to report status if reportStatus has been
14937     * set to true especially when unloading packages.
14938     */
14939    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14940            boolean externalStorage) {
14941        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14942        int[] uidArr = EmptyArray.INT;
14943
14944        final String[] list = PackageHelper.getSecureContainerList();
14945        if (ArrayUtils.isEmpty(list)) {
14946            Log.i(TAG, "No secure containers found");
14947        } else {
14948            // Process list of secure containers and categorize them
14949            // as active or stale based on their package internal state.
14950
14951            // reader
14952            synchronized (mPackages) {
14953                for (String cid : list) {
14954                    // Leave stages untouched for now; installer service owns them
14955                    if (PackageInstallerService.isStageName(cid)) continue;
14956
14957                    if (DEBUG_SD_INSTALL)
14958                        Log.i(TAG, "Processing container " + cid);
14959                    String pkgName = getAsecPackageName(cid);
14960                    if (pkgName == null) {
14961                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14962                        continue;
14963                    }
14964                    if (DEBUG_SD_INSTALL)
14965                        Log.i(TAG, "Looking for pkg : " + pkgName);
14966
14967                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14968                    if (ps == null) {
14969                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14970                        continue;
14971                    }
14972
14973                    /*
14974                     * Skip packages that are not external if we're unmounting
14975                     * external storage.
14976                     */
14977                    if (externalStorage && !isMounted && !isExternal(ps)) {
14978                        continue;
14979                    }
14980
14981                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14982                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14983                    // The package status is changed only if the code path
14984                    // matches between settings and the container id.
14985                    if (ps.codePathString != null
14986                            && ps.codePathString.startsWith(args.getCodePath())) {
14987                        if (DEBUG_SD_INSTALL) {
14988                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14989                                    + " at code path: " + ps.codePathString);
14990                        }
14991
14992                        // We do have a valid package installed on sdcard
14993                        processCids.put(args, ps.codePathString);
14994                        final int uid = ps.appId;
14995                        if (uid != -1) {
14996                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14997                        }
14998                    } else {
14999                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15000                                + ps.codePathString);
15001                    }
15002                }
15003            }
15004
15005            Arrays.sort(uidArr);
15006        }
15007
15008        // Process packages with valid entries.
15009        if (isMounted) {
15010            if (DEBUG_SD_INSTALL)
15011                Log.i(TAG, "Loading packages");
15012            loadMediaPackages(processCids, uidArr);
15013            startCleaningPackages();
15014            mInstallerService.onSecureContainersAvailable();
15015        } else {
15016            if (DEBUG_SD_INSTALL)
15017                Log.i(TAG, "Unloading packages");
15018            unloadMediaPackages(processCids, uidArr, reportStatus);
15019        }
15020    }
15021
15022    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15023            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15024        final int size = infos.size();
15025        final String[] packageNames = new String[size];
15026        final int[] packageUids = new int[size];
15027        for (int i = 0; i < size; i++) {
15028            final ApplicationInfo info = infos.get(i);
15029            packageNames[i] = info.packageName;
15030            packageUids[i] = info.uid;
15031        }
15032        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15033                finishedReceiver);
15034    }
15035
15036    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15037            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15038        sendResourcesChangedBroadcast(mediaStatus, replacing,
15039                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15040    }
15041
15042    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15043            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15044        int size = pkgList.length;
15045        if (size > 0) {
15046            // Send broadcasts here
15047            Bundle extras = new Bundle();
15048            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15049            if (uidArr != null) {
15050                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15051            }
15052            if (replacing) {
15053                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15054            }
15055            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15056                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15057            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15058        }
15059    }
15060
15061   /*
15062     * Look at potentially valid container ids from processCids If package
15063     * information doesn't match the one on record or package scanning fails,
15064     * the cid is added to list of removeCids. We currently don't delete stale
15065     * containers.
15066     */
15067    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15068        ArrayList<String> pkgList = new ArrayList<String>();
15069        Set<AsecInstallArgs> keys = processCids.keySet();
15070
15071        for (AsecInstallArgs args : keys) {
15072            String codePath = processCids.get(args);
15073            if (DEBUG_SD_INSTALL)
15074                Log.i(TAG, "Loading container : " + args.cid);
15075            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15076            try {
15077                // Make sure there are no container errors first.
15078                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15079                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15080                            + " when installing from sdcard");
15081                    continue;
15082                }
15083                // Check code path here.
15084                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15085                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15086                            + " does not match one in settings " + codePath);
15087                    continue;
15088                }
15089                // Parse package
15090                int parseFlags = mDefParseFlags;
15091                if (args.isExternalAsec()) {
15092                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15093                }
15094                if (args.isFwdLocked()) {
15095                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15096                }
15097
15098                synchronized (mInstallLock) {
15099                    PackageParser.Package pkg = null;
15100                    try {
15101                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15102                    } catch (PackageManagerException e) {
15103                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15104                    }
15105                    // Scan the package
15106                    if (pkg != null) {
15107                        /*
15108                         * TODO why is the lock being held? doPostInstall is
15109                         * called in other places without the lock. This needs
15110                         * to be straightened out.
15111                         */
15112                        // writer
15113                        synchronized (mPackages) {
15114                            retCode = PackageManager.INSTALL_SUCCEEDED;
15115                            pkgList.add(pkg.packageName);
15116                            // Post process args
15117                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15118                                    pkg.applicationInfo.uid);
15119                        }
15120                    } else {
15121                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15122                    }
15123                }
15124
15125            } finally {
15126                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15127                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15128                }
15129            }
15130        }
15131        // writer
15132        synchronized (mPackages) {
15133            // If the platform SDK has changed since the last time we booted,
15134            // we need to re-grant app permission to catch any new ones that
15135            // appear. This is really a hack, and means that apps can in some
15136            // cases get permissions that the user didn't initially explicitly
15137            // allow... it would be nice to have some better way to handle
15138            // this situation.
15139            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15140            if (regrantPermissions)
15141                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15142                        + mSdkVersion + "; regranting permissions for external storage");
15143            mSettings.mExternalSdkPlatform = mSdkVersion;
15144
15145            // Make sure group IDs have been assigned, and any permission
15146            // changes in other apps are accounted for
15147            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15148                    | (regrantPermissions
15149                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15150                            : 0));
15151
15152            mSettings.updateExternalDatabaseVersion();
15153
15154            // can downgrade to reader
15155            // Persist settings
15156            mSettings.writeLPr();
15157        }
15158        // Send a broadcast to let everyone know we are done processing
15159        if (pkgList.size() > 0) {
15160            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15161        }
15162    }
15163
15164   /*
15165     * Utility method to unload a list of specified containers
15166     */
15167    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15168        // Just unmount all valid containers.
15169        for (AsecInstallArgs arg : cidArgs) {
15170            synchronized (mInstallLock) {
15171                arg.doPostDeleteLI(false);
15172           }
15173       }
15174   }
15175
15176    /*
15177     * Unload packages mounted on external media. This involves deleting package
15178     * data from internal structures, sending broadcasts about diabled packages,
15179     * gc'ing to free up references, unmounting all secure containers
15180     * corresponding to packages on external media, and posting a
15181     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15182     * that we always have to post this message if status has been requested no
15183     * matter what.
15184     */
15185    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15186            final boolean reportStatus) {
15187        if (DEBUG_SD_INSTALL)
15188            Log.i(TAG, "unloading media packages");
15189        ArrayList<String> pkgList = new ArrayList<String>();
15190        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15191        final Set<AsecInstallArgs> keys = processCids.keySet();
15192        for (AsecInstallArgs args : keys) {
15193            String pkgName = args.getPackageName();
15194            if (DEBUG_SD_INSTALL)
15195                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15196            // Delete package internally
15197            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15198            synchronized (mInstallLock) {
15199                boolean res = deletePackageLI(pkgName, null, false, null, null,
15200                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15201                if (res) {
15202                    pkgList.add(pkgName);
15203                } else {
15204                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15205                    failedList.add(args);
15206                }
15207            }
15208        }
15209
15210        // reader
15211        synchronized (mPackages) {
15212            // We didn't update the settings after removing each package;
15213            // write them now for all packages.
15214            mSettings.writeLPr();
15215        }
15216
15217        // We have to absolutely send UPDATED_MEDIA_STATUS only
15218        // after confirming that all the receivers processed the ordered
15219        // broadcast when packages get disabled, force a gc to clean things up.
15220        // and unload all the containers.
15221        if (pkgList.size() > 0) {
15222            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15223                    new IIntentReceiver.Stub() {
15224                public void performReceive(Intent intent, int resultCode, String data,
15225                        Bundle extras, boolean ordered, boolean sticky,
15226                        int sendingUser) throws RemoteException {
15227                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15228                            reportStatus ? 1 : 0, 1, keys);
15229                    mHandler.sendMessage(msg);
15230                }
15231            });
15232        } else {
15233            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15234                    keys);
15235            mHandler.sendMessage(msg);
15236        }
15237    }
15238
15239    private void loadPrivatePackages(VolumeInfo vol) {
15240        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15241        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15242        synchronized (mInstallLock) {
15243        synchronized (mPackages) {
15244            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15245            for (PackageSetting ps : packages) {
15246                final PackageParser.Package pkg;
15247                try {
15248                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15249                    loaded.add(pkg.applicationInfo);
15250                } catch (PackageManagerException e) {
15251                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15252                }
15253            }
15254
15255            // TODO: regrant any permissions that changed based since original install
15256
15257            mSettings.writeLPr();
15258        }
15259        }
15260
15261        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15262        sendResourcesChangedBroadcast(true, false, loaded, null);
15263    }
15264
15265    private void unloadPrivatePackages(VolumeInfo vol) {
15266        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15267        synchronized (mInstallLock) {
15268        synchronized (mPackages) {
15269            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15270            for (PackageSetting ps : packages) {
15271                if (ps.pkg == null) continue;
15272
15273                final ApplicationInfo info = ps.pkg.applicationInfo;
15274                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15275                if (deletePackageLI(ps.name, null, false, null, null,
15276                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15277                    unloaded.add(info);
15278                } else {
15279                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15280                }
15281            }
15282
15283            mSettings.writeLPr();
15284        }
15285        }
15286
15287        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15288        sendResourcesChangedBroadcast(false, false, unloaded, null);
15289    }
15290
15291    /**
15292     * Examine all users present on given mounted volume, and destroy data
15293     * belonging to users that are no longer valid, or whose user ID has been
15294     * recycled.
15295     */
15296    private void reconcileUsers(String volumeUuid) {
15297        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15298        if (ArrayUtils.isEmpty(files)) {
15299            Slog.d(TAG, "No users found on " + volumeUuid);
15300            return;
15301        }
15302
15303        for (File file : files) {
15304            if (!file.isDirectory()) continue;
15305
15306            final int userId;
15307            final UserInfo info;
15308            try {
15309                userId = Integer.parseInt(file.getName());
15310                info = sUserManager.getUserInfo(userId);
15311            } catch (NumberFormatException e) {
15312                Slog.w(TAG, "Invalid user directory " + file);
15313                continue;
15314            }
15315
15316            boolean destroyUser = false;
15317            if (info == null) {
15318                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15319                        + " because no matching user was found");
15320                destroyUser = true;
15321            } else {
15322                try {
15323                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15324                } catch (IOException e) {
15325                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15326                            + " because we failed to enforce serial number: " + e);
15327                    destroyUser = true;
15328                }
15329            }
15330
15331            if (destroyUser) {
15332                synchronized (mInstallLock) {
15333                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15334                }
15335            }
15336        }
15337
15338        final UserManager um = mContext.getSystemService(UserManager.class);
15339        for (UserInfo user : um.getUsers()) {
15340            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15341            if (userDir.exists()) continue;
15342
15343            try {
15344                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15345                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15346            } catch (IOException e) {
15347                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15348            }
15349        }
15350    }
15351
15352    /**
15353     * Examine all apps present on given mounted volume, and destroy apps that
15354     * aren't expected, either due to uninstallation or reinstallation on
15355     * another volume.
15356     */
15357    private void reconcileApps(String volumeUuid) {
15358        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15359        if (ArrayUtils.isEmpty(files)) {
15360            Slog.d(TAG, "No apps found on " + volumeUuid);
15361            return;
15362        }
15363
15364        for (File file : files) {
15365            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15366                    && !PackageInstallerService.isStageName(file.getName());
15367            if (!isPackage) {
15368                // Ignore entries which are not packages
15369                continue;
15370            }
15371
15372            boolean destroyApp = false;
15373            String packageName = null;
15374            try {
15375                final PackageLite pkg = PackageParser.parsePackageLite(file,
15376                        PackageParser.PARSE_MUST_BE_APK);
15377                packageName = pkg.packageName;
15378
15379                synchronized (mPackages) {
15380                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15381                    if (ps == null) {
15382                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15383                                + volumeUuid + " because we found no install record");
15384                        destroyApp = true;
15385                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15386                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15387                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15388                        destroyApp = true;
15389                    }
15390                }
15391
15392            } catch (PackageParserException e) {
15393                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15394                destroyApp = true;
15395            }
15396
15397            if (destroyApp) {
15398                synchronized (mInstallLock) {
15399                    if (packageName != null) {
15400                        removeDataDirsLI(volumeUuid, packageName);
15401                    }
15402                    if (file.isDirectory()) {
15403                        mInstaller.rmPackageDir(file.getAbsolutePath());
15404                    } else {
15405                        file.delete();
15406                    }
15407                }
15408            }
15409        }
15410    }
15411
15412    private void unfreezePackage(String packageName) {
15413        synchronized (mPackages) {
15414            final PackageSetting ps = mSettings.mPackages.get(packageName);
15415            if (ps != null) {
15416                ps.frozen = false;
15417            }
15418        }
15419    }
15420
15421    @Override
15422    public int movePackage(final String packageName, final String volumeUuid) {
15423        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15424
15425        final int moveId = mNextMoveId.getAndIncrement();
15426        try {
15427            movePackageInternal(packageName, volumeUuid, moveId);
15428        } catch (PackageManagerException e) {
15429            Slog.w(TAG, "Failed to move " + packageName, e);
15430            mMoveCallbacks.notifyStatusChanged(moveId,
15431                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15432        }
15433        return moveId;
15434    }
15435
15436    private void movePackageInternal(final String packageName, final String volumeUuid,
15437            final int moveId) throws PackageManagerException {
15438        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15439        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15440        final PackageManager pm = mContext.getPackageManager();
15441
15442        final boolean currentAsec;
15443        final String currentVolumeUuid;
15444        final File codeFile;
15445        final String installerPackageName;
15446        final String packageAbiOverride;
15447        final int appId;
15448        final String seinfo;
15449        final String label;
15450
15451        // reader
15452        synchronized (mPackages) {
15453            final PackageParser.Package pkg = mPackages.get(packageName);
15454            final PackageSetting ps = mSettings.mPackages.get(packageName);
15455            if (pkg == null || ps == null) {
15456                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15457            }
15458
15459            if (pkg.applicationInfo.isSystemApp()) {
15460                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15461                        "Cannot move system application");
15462            }
15463
15464            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15465                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15466                        "Package already moved to " + volumeUuid);
15467            }
15468
15469            final File probe = new File(pkg.codePath);
15470            final File probeOat = new File(probe, "oat");
15471            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15472                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15473                        "Move only supported for modern cluster style installs");
15474            }
15475
15476            if (ps.frozen) {
15477                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15478                        "Failed to move already frozen package");
15479            }
15480            ps.frozen = true;
15481
15482            currentAsec = pkg.applicationInfo.isForwardLocked()
15483                    || pkg.applicationInfo.isExternalAsec();
15484            currentVolumeUuid = ps.volumeUuid;
15485            codeFile = new File(pkg.codePath);
15486            installerPackageName = ps.installerPackageName;
15487            packageAbiOverride = ps.cpuAbiOverrideString;
15488            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15489            seinfo = pkg.applicationInfo.seinfo;
15490            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15491        }
15492
15493        // Now that we're guarded by frozen state, kill app during move
15494        killApplication(packageName, appId, "move pkg");
15495
15496        final Bundle extras = new Bundle();
15497        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15498        extras.putString(Intent.EXTRA_TITLE, label);
15499        mMoveCallbacks.notifyCreated(moveId, extras);
15500
15501        int installFlags;
15502        final boolean moveCompleteApp;
15503        final File measurePath;
15504
15505        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15506            installFlags = INSTALL_INTERNAL;
15507            moveCompleteApp = !currentAsec;
15508            measurePath = Environment.getDataAppDirectory(volumeUuid);
15509        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15510            installFlags = INSTALL_EXTERNAL;
15511            moveCompleteApp = false;
15512            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15513        } else {
15514            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15515            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15516                    || !volume.isMountedWritable()) {
15517                unfreezePackage(packageName);
15518                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15519                        "Move location not mounted private volume");
15520            }
15521
15522            Preconditions.checkState(!currentAsec);
15523
15524            installFlags = INSTALL_INTERNAL;
15525            moveCompleteApp = true;
15526            measurePath = Environment.getDataAppDirectory(volumeUuid);
15527        }
15528
15529        final PackageStats stats = new PackageStats(null, -1);
15530        synchronized (mInstaller) {
15531            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15532                unfreezePackage(packageName);
15533                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15534                        "Failed to measure package size");
15535            }
15536        }
15537
15538        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15539                + stats.dataSize);
15540
15541        final long startFreeBytes = measurePath.getFreeSpace();
15542        final long sizeBytes;
15543        if (moveCompleteApp) {
15544            sizeBytes = stats.codeSize + stats.dataSize;
15545        } else {
15546            sizeBytes = stats.codeSize;
15547        }
15548
15549        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15550            unfreezePackage(packageName);
15551            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15552                    "Not enough free space to move");
15553        }
15554
15555        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15556
15557        final CountDownLatch installedLatch = new CountDownLatch(1);
15558        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15559            @Override
15560            public void onUserActionRequired(Intent intent) throws RemoteException {
15561                throw new IllegalStateException();
15562            }
15563
15564            @Override
15565            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15566                    Bundle extras) throws RemoteException {
15567                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15568                        + PackageManager.installStatusToString(returnCode, msg));
15569
15570                installedLatch.countDown();
15571
15572                // Regardless of success or failure of the move operation,
15573                // always unfreeze the package
15574                unfreezePackage(packageName);
15575
15576                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15577                switch (status) {
15578                    case PackageInstaller.STATUS_SUCCESS:
15579                        mMoveCallbacks.notifyStatusChanged(moveId,
15580                                PackageManager.MOVE_SUCCEEDED);
15581                        break;
15582                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15583                        mMoveCallbacks.notifyStatusChanged(moveId,
15584                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15585                        break;
15586                    default:
15587                        mMoveCallbacks.notifyStatusChanged(moveId,
15588                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15589                        break;
15590                }
15591            }
15592        };
15593
15594        final MoveInfo move;
15595        if (moveCompleteApp) {
15596            // Kick off a thread to report progress estimates
15597            new Thread() {
15598                @Override
15599                public void run() {
15600                    while (true) {
15601                        try {
15602                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15603                                break;
15604                            }
15605                        } catch (InterruptedException ignored) {
15606                        }
15607
15608                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15609                        final int progress = 10 + (int) MathUtils.constrain(
15610                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15611                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15612                    }
15613                }
15614            }.start();
15615
15616            final String dataAppName = codeFile.getName();
15617            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15618                    dataAppName, appId, seinfo);
15619        } else {
15620            move = null;
15621        }
15622
15623        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15624
15625        final Message msg = mHandler.obtainMessage(INIT_COPY);
15626        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15627        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15628                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15629        mHandler.sendMessage(msg);
15630    }
15631
15632    @Override
15633    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15634        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15635
15636        final int realMoveId = mNextMoveId.getAndIncrement();
15637        final Bundle extras = new Bundle();
15638        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15639        mMoveCallbacks.notifyCreated(realMoveId, extras);
15640
15641        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15642            @Override
15643            public void onCreated(int moveId, Bundle extras) {
15644                // Ignored
15645            }
15646
15647            @Override
15648            public void onStatusChanged(int moveId, int status, long estMillis) {
15649                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15650            }
15651        };
15652
15653        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15654        storage.setPrimaryStorageUuid(volumeUuid, callback);
15655        return realMoveId;
15656    }
15657
15658    @Override
15659    public int getMoveStatus(int moveId) {
15660        mContext.enforceCallingOrSelfPermission(
15661                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15662        return mMoveCallbacks.mLastStatus.get(moveId);
15663    }
15664
15665    @Override
15666    public void registerMoveCallback(IPackageMoveObserver callback) {
15667        mContext.enforceCallingOrSelfPermission(
15668                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15669        mMoveCallbacks.register(callback);
15670    }
15671
15672    @Override
15673    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15674        mContext.enforceCallingOrSelfPermission(
15675                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15676        mMoveCallbacks.unregister(callback);
15677    }
15678
15679    @Override
15680    public boolean setInstallLocation(int loc) {
15681        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15682                null);
15683        if (getInstallLocation() == loc) {
15684            return true;
15685        }
15686        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15687                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15688            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15689                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15690            return true;
15691        }
15692        return false;
15693   }
15694
15695    @Override
15696    public int getInstallLocation() {
15697        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15698                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15699                PackageHelper.APP_INSTALL_AUTO);
15700    }
15701
15702    /** Called by UserManagerService */
15703    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15704        mDirtyUsers.remove(userHandle);
15705        mSettings.removeUserLPw(userHandle);
15706        mPendingBroadcasts.remove(userHandle);
15707        if (mInstaller != null) {
15708            // Technically, we shouldn't be doing this with the package lock
15709            // held.  However, this is very rare, and there is already so much
15710            // other disk I/O going on, that we'll let it slide for now.
15711            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15712            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15713                final String volumeUuid = vol.getFsUuid();
15714                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15715                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15716            }
15717        }
15718        mUserNeedsBadging.delete(userHandle);
15719        removeUnusedPackagesLILPw(userManager, userHandle);
15720    }
15721
15722    /**
15723     * We're removing userHandle and would like to remove any downloaded packages
15724     * that are no longer in use by any other user.
15725     * @param userHandle the user being removed
15726     */
15727    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15728        final boolean DEBUG_CLEAN_APKS = false;
15729        int [] users = userManager.getUserIdsLPr();
15730        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15731        while (psit.hasNext()) {
15732            PackageSetting ps = psit.next();
15733            if (ps.pkg == null) {
15734                continue;
15735            }
15736            final String packageName = ps.pkg.packageName;
15737            // Skip over if system app
15738            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15739                continue;
15740            }
15741            if (DEBUG_CLEAN_APKS) {
15742                Slog.i(TAG, "Checking package " + packageName);
15743            }
15744            boolean keep = false;
15745            for (int i = 0; i < users.length; i++) {
15746                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15747                    keep = true;
15748                    if (DEBUG_CLEAN_APKS) {
15749                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15750                                + users[i]);
15751                    }
15752                    break;
15753                }
15754            }
15755            if (!keep) {
15756                if (DEBUG_CLEAN_APKS) {
15757                    Slog.i(TAG, "  Removing package " + packageName);
15758                }
15759                mHandler.post(new Runnable() {
15760                    public void run() {
15761                        deletePackageX(packageName, userHandle, 0);
15762                    } //end run
15763                });
15764            }
15765        }
15766    }
15767
15768    /** Called by UserManagerService */
15769    void createNewUserLILPw(int userHandle) {
15770        if (mInstaller != null) {
15771            mInstaller.createUserConfig(userHandle);
15772            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15773            applyFactoryDefaultBrowserLPw(userHandle);
15774        }
15775    }
15776
15777    void newUserCreatedLILPw(final int userHandle) {
15778        // We cannot grant the default permissions with a lock held as
15779        // we query providers from other components for default handlers
15780        // such as enabled IMEs, etc.
15781        mHandler.post(new Runnable() {
15782            @Override
15783            public void run() {
15784                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15785            }
15786        });
15787    }
15788
15789    @Override
15790    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15791        mContext.enforceCallingOrSelfPermission(
15792                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15793                "Only package verification agents can read the verifier device identity");
15794
15795        synchronized (mPackages) {
15796            return mSettings.getVerifierDeviceIdentityLPw();
15797        }
15798    }
15799
15800    @Override
15801    public void setPermissionEnforced(String permission, boolean enforced) {
15802        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15803        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15804            synchronized (mPackages) {
15805                if (mSettings.mReadExternalStorageEnforced == null
15806                        || mSettings.mReadExternalStorageEnforced != enforced) {
15807                    mSettings.mReadExternalStorageEnforced = enforced;
15808                    mSettings.writeLPr();
15809                }
15810            }
15811            // kill any non-foreground processes so we restart them and
15812            // grant/revoke the GID.
15813            final IActivityManager am = ActivityManagerNative.getDefault();
15814            if (am != null) {
15815                final long token = Binder.clearCallingIdentity();
15816                try {
15817                    am.killProcessesBelowForeground("setPermissionEnforcement");
15818                } catch (RemoteException e) {
15819                } finally {
15820                    Binder.restoreCallingIdentity(token);
15821                }
15822            }
15823        } else {
15824            throw new IllegalArgumentException("No selective enforcement for " + permission);
15825        }
15826    }
15827
15828    @Override
15829    @Deprecated
15830    public boolean isPermissionEnforced(String permission) {
15831        return true;
15832    }
15833
15834    @Override
15835    public boolean isStorageLow() {
15836        final long token = Binder.clearCallingIdentity();
15837        try {
15838            final DeviceStorageMonitorInternal
15839                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15840            if (dsm != null) {
15841                return dsm.isMemoryLow();
15842            } else {
15843                return false;
15844            }
15845        } finally {
15846            Binder.restoreCallingIdentity(token);
15847        }
15848    }
15849
15850    @Override
15851    public IPackageInstaller getPackageInstaller() {
15852        return mInstallerService;
15853    }
15854
15855    private boolean userNeedsBadging(int userId) {
15856        int index = mUserNeedsBadging.indexOfKey(userId);
15857        if (index < 0) {
15858            final UserInfo userInfo;
15859            final long token = Binder.clearCallingIdentity();
15860            try {
15861                userInfo = sUserManager.getUserInfo(userId);
15862            } finally {
15863                Binder.restoreCallingIdentity(token);
15864            }
15865            final boolean b;
15866            if (userInfo != null && userInfo.isManagedProfile()) {
15867                b = true;
15868            } else {
15869                b = false;
15870            }
15871            mUserNeedsBadging.put(userId, b);
15872            return b;
15873        }
15874        return mUserNeedsBadging.valueAt(index);
15875    }
15876
15877    @Override
15878    public KeySet getKeySetByAlias(String packageName, String alias) {
15879        if (packageName == null || alias == null) {
15880            return null;
15881        }
15882        synchronized(mPackages) {
15883            final PackageParser.Package pkg = mPackages.get(packageName);
15884            if (pkg == null) {
15885                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15886                throw new IllegalArgumentException("Unknown package: " + packageName);
15887            }
15888            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15889            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15890        }
15891    }
15892
15893    @Override
15894    public KeySet getSigningKeySet(String packageName) {
15895        if (packageName == null) {
15896            return null;
15897        }
15898        synchronized(mPackages) {
15899            final PackageParser.Package pkg = mPackages.get(packageName);
15900            if (pkg == null) {
15901                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15902                throw new IllegalArgumentException("Unknown package: " + packageName);
15903            }
15904            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15905                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15906                throw new SecurityException("May not access signing KeySet of other apps.");
15907            }
15908            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15909            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15910        }
15911    }
15912
15913    @Override
15914    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15915        if (packageName == null || ks == null) {
15916            return false;
15917        }
15918        synchronized(mPackages) {
15919            final PackageParser.Package pkg = mPackages.get(packageName);
15920            if (pkg == null) {
15921                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15922                throw new IllegalArgumentException("Unknown package: " + packageName);
15923            }
15924            IBinder ksh = ks.getToken();
15925            if (ksh instanceof KeySetHandle) {
15926                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15927                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15928            }
15929            return false;
15930        }
15931    }
15932
15933    @Override
15934    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15935        if (packageName == null || ks == null) {
15936            return false;
15937        }
15938        synchronized(mPackages) {
15939            final PackageParser.Package pkg = mPackages.get(packageName);
15940            if (pkg == null) {
15941                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15942                throw new IllegalArgumentException("Unknown package: " + packageName);
15943            }
15944            IBinder ksh = ks.getToken();
15945            if (ksh instanceof KeySetHandle) {
15946                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15947                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
15948            }
15949            return false;
15950        }
15951    }
15952
15953    public void getUsageStatsIfNoPackageUsageInfo() {
15954        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
15955            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
15956            if (usm == null) {
15957                throw new IllegalStateException("UsageStatsManager must be initialized");
15958            }
15959            long now = System.currentTimeMillis();
15960            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
15961            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
15962                String packageName = entry.getKey();
15963                PackageParser.Package pkg = mPackages.get(packageName);
15964                if (pkg == null) {
15965                    continue;
15966                }
15967                UsageStats usage = entry.getValue();
15968                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15969                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15970            }
15971        }
15972    }
15973
15974    /**
15975     * Check and throw if the given before/after packages would be considered a
15976     * downgrade.
15977     */
15978    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15979            throws PackageManagerException {
15980        if (after.versionCode < before.mVersionCode) {
15981            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15982                    "Update version code " + after.versionCode + " is older than current "
15983                    + before.mVersionCode);
15984        } else if (after.versionCode == before.mVersionCode) {
15985            if (after.baseRevisionCode < before.baseRevisionCode) {
15986                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15987                        "Update base revision code " + after.baseRevisionCode
15988                        + " is older than current " + before.baseRevisionCode);
15989            }
15990
15991            if (!ArrayUtils.isEmpty(after.splitNames)) {
15992                for (int i = 0; i < after.splitNames.length; i++) {
15993                    final String splitName = after.splitNames[i];
15994                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15995                    if (j != -1) {
15996                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15997                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15998                                    "Update split " + splitName + " revision code "
15999                                    + after.splitRevisionCodes[i] + " is older than current "
16000                                    + before.splitRevisionCodes[j]);
16001                        }
16002                    }
16003                }
16004            }
16005        }
16006    }
16007
16008    private static class MoveCallbacks extends Handler {
16009        private static final int MSG_CREATED = 1;
16010        private static final int MSG_STATUS_CHANGED = 2;
16011
16012        private final RemoteCallbackList<IPackageMoveObserver>
16013                mCallbacks = new RemoteCallbackList<>();
16014
16015        private final SparseIntArray mLastStatus = new SparseIntArray();
16016
16017        public MoveCallbacks(Looper looper) {
16018            super(looper);
16019        }
16020
16021        public void register(IPackageMoveObserver callback) {
16022            mCallbacks.register(callback);
16023        }
16024
16025        public void unregister(IPackageMoveObserver callback) {
16026            mCallbacks.unregister(callback);
16027        }
16028
16029        @Override
16030        public void handleMessage(Message msg) {
16031            final SomeArgs args = (SomeArgs) msg.obj;
16032            final int n = mCallbacks.beginBroadcast();
16033            for (int i = 0; i < n; i++) {
16034                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16035                try {
16036                    invokeCallback(callback, msg.what, args);
16037                } catch (RemoteException ignored) {
16038                }
16039            }
16040            mCallbacks.finishBroadcast();
16041            args.recycle();
16042        }
16043
16044        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16045                throws RemoteException {
16046            switch (what) {
16047                case MSG_CREATED: {
16048                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16049                    break;
16050                }
16051                case MSG_STATUS_CHANGED: {
16052                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16053                    break;
16054                }
16055            }
16056        }
16057
16058        private void notifyCreated(int moveId, Bundle extras) {
16059            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16060
16061            final SomeArgs args = SomeArgs.obtain();
16062            args.argi1 = moveId;
16063            args.arg2 = extras;
16064            obtainMessage(MSG_CREATED, args).sendToTarget();
16065        }
16066
16067        private void notifyStatusChanged(int moveId, int status) {
16068            notifyStatusChanged(moveId, status, -1);
16069        }
16070
16071        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16072            Slog.v(TAG, "Move " + moveId + " status " + status);
16073
16074            final SomeArgs args = SomeArgs.obtain();
16075            args.argi1 = moveId;
16076            args.argi2 = status;
16077            args.arg3 = estMillis;
16078            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16079
16080            synchronized (mLastStatus) {
16081                mLastStatus.put(moveId, status);
16082            }
16083        }
16084    }
16085
16086    private final class OnPermissionChangeListeners extends Handler {
16087        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16088
16089        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16090                new RemoteCallbackList<>();
16091
16092        public OnPermissionChangeListeners(Looper looper) {
16093            super(looper);
16094        }
16095
16096        @Override
16097        public void handleMessage(Message msg) {
16098            switch (msg.what) {
16099                case MSG_ON_PERMISSIONS_CHANGED: {
16100                    final int uid = msg.arg1;
16101                    handleOnPermissionsChanged(uid);
16102                } break;
16103            }
16104        }
16105
16106        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16107            mPermissionListeners.register(listener);
16108
16109        }
16110
16111        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16112            mPermissionListeners.unregister(listener);
16113        }
16114
16115        public void onPermissionsChanged(int uid) {
16116            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16117                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16118            }
16119        }
16120
16121        private void handleOnPermissionsChanged(int uid) {
16122            final int count = mPermissionListeners.beginBroadcast();
16123            try {
16124                for (int i = 0; i < count; i++) {
16125                    IOnPermissionsChangeListener callback = mPermissionListeners
16126                            .getBroadcastItem(i);
16127                    try {
16128                        callback.onPermissionsChanged(uid);
16129                    } catch (RemoteException e) {
16130                        Log.e(TAG, "Permission listener is dead", e);
16131                    }
16132                }
16133            } finally {
16134                mPermissionListeners.finishBroadcast();
16135            }
16136        }
16137    }
16138
16139    private class PackageManagerInternalImpl extends PackageManagerInternal {
16140        @Override
16141        public void setLocationPackagesProvider(PackagesProvider provider) {
16142            synchronized (mPackages) {
16143                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16144            }
16145        }
16146
16147        @Override
16148        public void setImePackagesProvider(PackagesProvider provider) {
16149            synchronized (mPackages) {
16150                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16151            }
16152        }
16153
16154        @Override
16155        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16156            synchronized (mPackages) {
16157                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16158            }
16159        }
16160
16161        @Override
16162        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16163            synchronized (mPackages) {
16164                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16165            }
16166        }
16167
16168        @Override
16169        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16170            synchronized (mPackages) {
16171                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16172            }
16173        }
16174
16175        @Override
16176        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16177            synchronized (mPackages) {
16178                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16179            }
16180        }
16181
16182        @Override
16183        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16184            synchronized (mPackages) {
16185                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16186                        packageName, userId);
16187            }
16188        }
16189
16190        @Override
16191        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16192            synchronized (mPackages) {
16193                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16194                        packageName, userId);
16195            }
16196        }
16197    }
16198
16199    @Override
16200    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16201        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16202        synchronized (mPackages) {
16203            final long identity = Binder.clearCallingIdentity();
16204            try {
16205                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16206                        packageNames, userId);
16207            } finally {
16208                Binder.restoreCallingIdentity(identity);
16209            }
16210        }
16211    }
16212
16213    private static void enforceSystemOrPhoneCaller(String tag) {
16214        int callingUid = Binder.getCallingUid();
16215        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16216            throw new SecurityException(
16217                    "Cannot call " + tag + " from UID " + callingUid);
16218        }
16219    }
16220}
16221