PackageManagerService.java revision 7acd33bb3ce840a2588567d6feae71bb8b24b35a
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    final String mRequiredVerifierPackage;
930    final String mRequiredInstallerPackage;
931
932    private final PackageUsage mPackageUsage = new PackageUsage();
933
934    private class PackageUsage {
935        private static final int WRITE_INTERVAL
936            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
937
938        private final Object mFileLock = new Object();
939        private final AtomicLong mLastWritten = new AtomicLong(0);
940        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
941
942        private boolean mIsHistoricalPackageUsageAvailable = true;
943
944        boolean isHistoricalPackageUsageAvailable() {
945            return mIsHistoricalPackageUsageAvailable;
946        }
947
948        void write(boolean force) {
949            if (force) {
950                writeInternal();
951                return;
952            }
953            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
954                && !DEBUG_DEXOPT) {
955                return;
956            }
957            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
958                new Thread("PackageUsage_DiskWriter") {
959                    @Override
960                    public void run() {
961                        try {
962                            writeInternal();
963                        } finally {
964                            mBackgroundWriteRunning.set(false);
965                        }
966                    }
967                }.start();
968            }
969        }
970
971        private void writeInternal() {
972            synchronized (mPackages) {
973                synchronized (mFileLock) {
974                    AtomicFile file = getFile();
975                    FileOutputStream f = null;
976                    try {
977                        f = file.startWrite();
978                        BufferedOutputStream out = new BufferedOutputStream(f);
979                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
980                        StringBuilder sb = new StringBuilder();
981                        for (PackageParser.Package pkg : mPackages.values()) {
982                            if (pkg.mLastPackageUsageTimeInMills == 0) {
983                                continue;
984                            }
985                            sb.setLength(0);
986                            sb.append(pkg.packageName);
987                            sb.append(' ');
988                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
989                            sb.append('\n');
990                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
991                        }
992                        out.flush();
993                        file.finishWrite(f);
994                    } catch (IOException e) {
995                        if (f != null) {
996                            file.failWrite(f);
997                        }
998                        Log.e(TAG, "Failed to write package usage times", e);
999                    }
1000                }
1001            }
1002            mLastWritten.set(SystemClock.elapsedRealtime());
1003        }
1004
1005        void readLP() {
1006            synchronized (mFileLock) {
1007                AtomicFile file = getFile();
1008                BufferedInputStream in = null;
1009                try {
1010                    in = new BufferedInputStream(file.openRead());
1011                    StringBuffer sb = new StringBuffer();
1012                    while (true) {
1013                        String packageName = readToken(in, sb, ' ');
1014                        if (packageName == null) {
1015                            break;
1016                        }
1017                        String timeInMillisString = readToken(in, sb, '\n');
1018                        if (timeInMillisString == null) {
1019                            throw new IOException("Failed to find last usage time for package "
1020                                                  + packageName);
1021                        }
1022                        PackageParser.Package pkg = mPackages.get(packageName);
1023                        if (pkg == null) {
1024                            continue;
1025                        }
1026                        long timeInMillis;
1027                        try {
1028                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1029                        } catch (NumberFormatException e) {
1030                            throw new IOException("Failed to parse " + timeInMillisString
1031                                                  + " as a long.", e);
1032                        }
1033                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1034                    }
1035                } catch (FileNotFoundException expected) {
1036                    mIsHistoricalPackageUsageAvailable = false;
1037                } catch (IOException e) {
1038                    Log.w(TAG, "Failed to read package usage times", e);
1039                } finally {
1040                    IoUtils.closeQuietly(in);
1041                }
1042            }
1043            mLastWritten.set(SystemClock.elapsedRealtime());
1044        }
1045
1046        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1047                throws IOException {
1048            sb.setLength(0);
1049            while (true) {
1050                int ch = in.read();
1051                if (ch == -1) {
1052                    if (sb.length() == 0) {
1053                        return null;
1054                    }
1055                    throw new IOException("Unexpected EOF");
1056                }
1057                if (ch == endOfToken) {
1058                    return sb.toString();
1059                }
1060                sb.append((char)ch);
1061            }
1062        }
1063
1064        private AtomicFile getFile() {
1065            File dataDir = Environment.getDataDirectory();
1066            File systemDir = new File(dataDir, "system");
1067            File fname = new File(systemDir, "package-usage.list");
1068            return new AtomicFile(fname);
1069        }
1070    }
1071
1072    class PackageHandler extends Handler {
1073        private boolean mBound = false;
1074        final ArrayList<HandlerParams> mPendingInstalls =
1075            new ArrayList<HandlerParams>();
1076
1077        private boolean connectToService() {
1078            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1079                    " DefaultContainerService");
1080            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1081            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1082            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1083                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1084                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1085                mBound = true;
1086                return true;
1087            }
1088            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1089            return false;
1090        }
1091
1092        private void disconnectService() {
1093            mContainerService = null;
1094            mBound = false;
1095            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1096            mContext.unbindService(mDefContainerConn);
1097            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1098        }
1099
1100        PackageHandler(Looper looper) {
1101            super(looper);
1102        }
1103
1104        public void handleMessage(Message msg) {
1105            try {
1106                doHandleMessage(msg);
1107            } finally {
1108                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1109            }
1110        }
1111
1112        void doHandleMessage(Message msg) {
1113            switch (msg.what) {
1114                case INIT_COPY: {
1115                    HandlerParams params = (HandlerParams) msg.obj;
1116                    int idx = mPendingInstalls.size();
1117                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1118                    // If a bind was already initiated we dont really
1119                    // need to do anything. The pending install
1120                    // will be processed later on.
1121                    if (!mBound) {
1122                        // If this is the only one pending we might
1123                        // have to bind to the service again.
1124                        if (!connectToService()) {
1125                            Slog.e(TAG, "Failed to bind to media container service");
1126                            params.serviceError();
1127                            return;
1128                        } else {
1129                            // Once we bind to the service, the first
1130                            // pending request will be processed.
1131                            mPendingInstalls.add(idx, params);
1132                        }
1133                    } else {
1134                        mPendingInstalls.add(idx, params);
1135                        // Already bound to the service. Just make
1136                        // sure we trigger off processing the first request.
1137                        if (idx == 0) {
1138                            mHandler.sendEmptyMessage(MCS_BOUND);
1139                        }
1140                    }
1141                    break;
1142                }
1143                case MCS_BOUND: {
1144                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1145                    if (msg.obj != null) {
1146                        mContainerService = (IMediaContainerService) msg.obj;
1147                    }
1148                    if (mContainerService == null) {
1149                        if (!mBound) {
1150                            // Something seriously wrong since we are not bound and we are not
1151                            // waiting for connection. Bail out.
1152                            Slog.e(TAG, "Cannot bind to media container service");
1153                            for (HandlerParams params : mPendingInstalls) {
1154                                // Indicate service bind error
1155                                params.serviceError();
1156                            }
1157                            mPendingInstalls.clear();
1158                        } else {
1159                            Slog.w(TAG, "Waiting to connect to media container service");
1160                        }
1161                    } else if (mPendingInstalls.size() > 0) {
1162                        HandlerParams params = mPendingInstalls.get(0);
1163                        if (params != null) {
1164                            if (params.startCopy()) {
1165                                // We are done...  look for more work or to
1166                                // go idle.
1167                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1168                                        "Checking for more work or unbind...");
1169                                // Delete pending install
1170                                if (mPendingInstalls.size() > 0) {
1171                                    mPendingInstalls.remove(0);
1172                                }
1173                                if (mPendingInstalls.size() == 0) {
1174                                    if (mBound) {
1175                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1176                                                "Posting delayed MCS_UNBIND");
1177                                        removeMessages(MCS_UNBIND);
1178                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1179                                        // Unbind after a little delay, to avoid
1180                                        // continual thrashing.
1181                                        sendMessageDelayed(ubmsg, 10000);
1182                                    }
1183                                } else {
1184                                    // There are more pending requests in queue.
1185                                    // Just post MCS_BOUND message to trigger processing
1186                                    // of next pending install.
1187                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1188                                            "Posting MCS_BOUND for next work");
1189                                    mHandler.sendEmptyMessage(MCS_BOUND);
1190                                }
1191                            }
1192                        }
1193                    } else {
1194                        // Should never happen ideally.
1195                        Slog.w(TAG, "Empty queue");
1196                    }
1197                    break;
1198                }
1199                case MCS_RECONNECT: {
1200                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1201                    if (mPendingInstalls.size() > 0) {
1202                        if (mBound) {
1203                            disconnectService();
1204                        }
1205                        if (!connectToService()) {
1206                            Slog.e(TAG, "Failed to bind to media container service");
1207                            for (HandlerParams params : mPendingInstalls) {
1208                                // Indicate service bind error
1209                                params.serviceError();
1210                            }
1211                            mPendingInstalls.clear();
1212                        }
1213                    }
1214                    break;
1215                }
1216                case MCS_UNBIND: {
1217                    // If there is no actual work left, then time to unbind.
1218                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1219
1220                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1221                        if (mBound) {
1222                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1223
1224                            disconnectService();
1225                        }
1226                    } else if (mPendingInstalls.size() > 0) {
1227                        // There are more pending requests in queue.
1228                        // Just post MCS_BOUND message to trigger processing
1229                        // of next pending install.
1230                        mHandler.sendEmptyMessage(MCS_BOUND);
1231                    }
1232
1233                    break;
1234                }
1235                case MCS_GIVE_UP: {
1236                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1237                    mPendingInstalls.remove(0);
1238                    break;
1239                }
1240                case SEND_PENDING_BROADCAST: {
1241                    String packages[];
1242                    ArrayList<String> components[];
1243                    int size = 0;
1244                    int uids[];
1245                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1246                    synchronized (mPackages) {
1247                        if (mPendingBroadcasts == null) {
1248                            return;
1249                        }
1250                        size = mPendingBroadcasts.size();
1251                        if (size <= 0) {
1252                            // Nothing to be done. Just return
1253                            return;
1254                        }
1255                        packages = new String[size];
1256                        components = new ArrayList[size];
1257                        uids = new int[size];
1258                        int i = 0;  // filling out the above arrays
1259
1260                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1261                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1262                            Iterator<Map.Entry<String, ArrayList<String>>> it
1263                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1264                                            .entrySet().iterator();
1265                            while (it.hasNext() && i < size) {
1266                                Map.Entry<String, ArrayList<String>> ent = it.next();
1267                                packages[i] = ent.getKey();
1268                                components[i] = ent.getValue();
1269                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1270                                uids[i] = (ps != null)
1271                                        ? UserHandle.getUid(packageUserId, ps.appId)
1272                                        : -1;
1273                                i++;
1274                            }
1275                        }
1276                        size = i;
1277                        mPendingBroadcasts.clear();
1278                    }
1279                    // Send broadcasts
1280                    for (int i = 0; i < size; i++) {
1281                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1282                    }
1283                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1284                    break;
1285                }
1286                case START_CLEANING_PACKAGE: {
1287                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1288                    final String packageName = (String)msg.obj;
1289                    final int userId = msg.arg1;
1290                    final boolean andCode = msg.arg2 != 0;
1291                    synchronized (mPackages) {
1292                        if (userId == UserHandle.USER_ALL) {
1293                            int[] users = sUserManager.getUserIds();
1294                            for (int user : users) {
1295                                mSettings.addPackageToCleanLPw(
1296                                        new PackageCleanItem(user, packageName, andCode));
1297                            }
1298                        } else {
1299                            mSettings.addPackageToCleanLPw(
1300                                    new PackageCleanItem(userId, packageName, andCode));
1301                        }
1302                    }
1303                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1304                    startCleaningPackages();
1305                } break;
1306                case POST_INSTALL: {
1307                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1308                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1309                    mRunningInstalls.delete(msg.arg1);
1310                    boolean deleteOld = false;
1311
1312                    if (data != null) {
1313                        InstallArgs args = data.args;
1314                        PackageInstalledInfo res = data.res;
1315
1316                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1317                            final String packageName = res.pkg.applicationInfo.packageName;
1318                            res.removedInfo.sendBroadcast(false, true, false);
1319                            Bundle extras = new Bundle(1);
1320                            extras.putInt(Intent.EXTRA_UID, res.uid);
1321
1322                            // Now that we successfully installed the package, grant runtime
1323                            // permissions if requested before broadcasting the install.
1324                            if ((args.installFlags
1325                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1326                                grantRequestedRuntimePermissions(res.pkg,
1327                                        args.user.getIdentifier());
1328                            }
1329
1330                            // Determine the set of users who are adding this
1331                            // package for the first time vs. those who are seeing
1332                            // an update.
1333                            int[] firstUsers;
1334                            int[] updateUsers = new int[0];
1335                            if (res.origUsers == null || res.origUsers.length == 0) {
1336                                firstUsers = res.newUsers;
1337                            } else {
1338                                firstUsers = new int[0];
1339                                for (int i=0; i<res.newUsers.length; i++) {
1340                                    int user = res.newUsers[i];
1341                                    boolean isNew = true;
1342                                    for (int j=0; j<res.origUsers.length; j++) {
1343                                        if (res.origUsers[j] == user) {
1344                                            isNew = false;
1345                                            break;
1346                                        }
1347                                    }
1348                                    if (isNew) {
1349                                        int[] newFirst = new int[firstUsers.length+1];
1350                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1351                                                firstUsers.length);
1352                                        newFirst[firstUsers.length] = user;
1353                                        firstUsers = newFirst;
1354                                    } else {
1355                                        int[] newUpdate = new int[updateUsers.length+1];
1356                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1357                                                updateUsers.length);
1358                                        newUpdate[updateUsers.length] = user;
1359                                        updateUsers = newUpdate;
1360                                    }
1361                                }
1362                            }
1363                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1364                                    packageName, extras, null, null, firstUsers);
1365                            final boolean update = res.removedInfo.removedPackage != null;
1366                            if (update) {
1367                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1368                            }
1369                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1370                                    packageName, extras, null, null, updateUsers);
1371                            if (update) {
1372                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1373                                        packageName, extras, null, null, updateUsers);
1374                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1375                                        null, null, packageName, null, updateUsers);
1376
1377                                // treat asec-hosted packages like removable media on upgrade
1378                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1379                                    if (DEBUG_INSTALL) {
1380                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1381                                                + " is ASEC-hosted -> AVAILABLE");
1382                                    }
1383                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1384                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1385                                    pkgList.add(packageName);
1386                                    sendResourcesChangedBroadcast(true, true,
1387                                            pkgList,uidArray, null);
1388                                }
1389                            }
1390                            if (res.removedInfo.args != null) {
1391                                // Remove the replaced package's older resources safely now
1392                                deleteOld = true;
1393                            }
1394
1395                            // If this app is a browser and it's newly-installed for some
1396                            // users, clear any default-browser state in those users
1397                            if (firstUsers.length > 0) {
1398                                // the app's nature doesn't depend on the user, so we can just
1399                                // check its browser nature in any user and generalize.
1400                                if (packageIsBrowser(packageName, firstUsers[0])) {
1401                                    synchronized (mPackages) {
1402                                        for (int userId : firstUsers) {
1403                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1404                                        }
1405                                    }
1406                                }
1407                            }
1408                            // Log current value of "unknown sources" setting
1409                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1410                                getUnknownSourcesSettings());
1411                        }
1412                        // Force a gc to clear up things
1413                        Runtime.getRuntime().gc();
1414                        // We delete after a gc for applications  on sdcard.
1415                        if (deleteOld) {
1416                            synchronized (mInstallLock) {
1417                                res.removedInfo.args.doPostDeleteLI(true);
1418                            }
1419                        }
1420                        if (args.observer != null) {
1421                            try {
1422                                Bundle extras = extrasForInstallResult(res);
1423                                args.observer.onPackageInstalled(res.name, res.returnCode,
1424                                        res.returnMsg, extras);
1425                            } catch (RemoteException e) {
1426                                Slog.i(TAG, "Observer no longer exists.");
1427                            }
1428                        }
1429                    } else {
1430                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1431                    }
1432                } break;
1433                case UPDATED_MEDIA_STATUS: {
1434                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1435                    boolean reportStatus = msg.arg1 == 1;
1436                    boolean doGc = msg.arg2 == 1;
1437                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1438                    if (doGc) {
1439                        // Force a gc to clear up stale containers.
1440                        Runtime.getRuntime().gc();
1441                    }
1442                    if (msg.obj != null) {
1443                        @SuppressWarnings("unchecked")
1444                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1445                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1446                        // Unload containers
1447                        unloadAllContainers(args);
1448                    }
1449                    if (reportStatus) {
1450                        try {
1451                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1452                            PackageHelper.getMountService().finishMediaUpdate();
1453                        } catch (RemoteException e) {
1454                            Log.e(TAG, "MountService not running?");
1455                        }
1456                    }
1457                } break;
1458                case WRITE_SETTINGS: {
1459                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1460                    synchronized (mPackages) {
1461                        removeMessages(WRITE_SETTINGS);
1462                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1463                        mSettings.writeLPr();
1464                        mDirtyUsers.clear();
1465                    }
1466                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1467                } break;
1468                case WRITE_PACKAGE_RESTRICTIONS: {
1469                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1470                    synchronized (mPackages) {
1471                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1472                        for (int userId : mDirtyUsers) {
1473                            mSettings.writePackageRestrictionsLPr(userId);
1474                        }
1475                        mDirtyUsers.clear();
1476                    }
1477                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1478                } break;
1479                case CHECK_PENDING_VERIFICATION: {
1480                    final int verificationId = msg.arg1;
1481                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1482
1483                    if ((state != null) && !state.timeoutExtended()) {
1484                        final InstallArgs args = state.getInstallArgs();
1485                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1486
1487                        Slog.i(TAG, "Verification timed out for " + originUri);
1488                        mPendingVerification.remove(verificationId);
1489
1490                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1491
1492                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1493                            Slog.i(TAG, "Continuing with installation of " + originUri);
1494                            state.setVerifierResponse(Binder.getCallingUid(),
1495                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1496                            broadcastPackageVerified(verificationId, originUri,
1497                                    PackageManager.VERIFICATION_ALLOW,
1498                                    state.getInstallArgs().getUser());
1499                            try {
1500                                ret = args.copyApk(mContainerService, true);
1501                            } catch (RemoteException e) {
1502                                Slog.e(TAG, "Could not contact the ContainerService");
1503                            }
1504                        } else {
1505                            broadcastPackageVerified(verificationId, originUri,
1506                                    PackageManager.VERIFICATION_REJECT,
1507                                    state.getInstallArgs().getUser());
1508                        }
1509
1510                        processPendingInstall(args, ret);
1511                        mHandler.sendEmptyMessage(MCS_UNBIND);
1512                    }
1513                    break;
1514                }
1515                case PACKAGE_VERIFIED: {
1516                    final int verificationId = msg.arg1;
1517
1518                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1519                    if (state == null) {
1520                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1521                        break;
1522                    }
1523
1524                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1525
1526                    state.setVerifierResponse(response.callerUid, response.code);
1527
1528                    if (state.isVerificationComplete()) {
1529                        mPendingVerification.remove(verificationId);
1530
1531                        final InstallArgs args = state.getInstallArgs();
1532                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1533
1534                        int ret;
1535                        if (state.isInstallAllowed()) {
1536                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1537                            broadcastPackageVerified(verificationId, originUri,
1538                                    response.code, state.getInstallArgs().getUser());
1539                            try {
1540                                ret = args.copyApk(mContainerService, true);
1541                            } catch (RemoteException e) {
1542                                Slog.e(TAG, "Could not contact the ContainerService");
1543                            }
1544                        } else {
1545                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1546                        }
1547
1548                        processPendingInstall(args, ret);
1549
1550                        mHandler.sendEmptyMessage(MCS_UNBIND);
1551                    }
1552
1553                    break;
1554                }
1555                case START_INTENT_FILTER_VERIFICATIONS: {
1556                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1557                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1558                            params.replacing, params.pkg);
1559                    break;
1560                }
1561                case INTENT_FILTER_VERIFIED: {
1562                    final int verificationId = msg.arg1;
1563
1564                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1565                            verificationId);
1566                    if (state == null) {
1567                        Slog.w(TAG, "Invalid IntentFilter verification token "
1568                                + verificationId + " received");
1569                        break;
1570                    }
1571
1572                    final int userId = state.getUserId();
1573
1574                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1575                            "Processing IntentFilter verification with token:"
1576                            + verificationId + " and userId:" + userId);
1577
1578                    final IntentFilterVerificationResponse response =
1579                            (IntentFilterVerificationResponse) msg.obj;
1580
1581                    state.setVerifierResponse(response.callerUid, response.code);
1582
1583                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1584                            "IntentFilter verification with token:" + verificationId
1585                            + " and userId:" + userId
1586                            + " is settings verifier response with response code:"
1587                            + response.code);
1588
1589                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1590                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1591                                + response.getFailedDomainsString());
1592                    }
1593
1594                    if (state.isVerificationComplete()) {
1595                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1596                    } else {
1597                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1598                                "IntentFilter verification with token:" + verificationId
1599                                + " was not said to be complete");
1600                    }
1601
1602                    break;
1603                }
1604            }
1605        }
1606    }
1607
1608    private StorageEventListener mStorageListener = new StorageEventListener() {
1609        @Override
1610        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1611            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1612                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1613                    final String volumeUuid = vol.getFsUuid();
1614
1615                    // Clean up any users or apps that were removed or recreated
1616                    // while this volume was missing
1617                    reconcileUsers(volumeUuid);
1618                    reconcileApps(volumeUuid);
1619
1620                    // Clean up any install sessions that expired or were
1621                    // cancelled while this volume was missing
1622                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1623
1624                    loadPrivatePackages(vol);
1625
1626                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1627                    unloadPrivatePackages(vol);
1628                }
1629            }
1630
1631            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1632                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1633                    updateExternalMediaStatus(true, false);
1634                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1635                    updateExternalMediaStatus(false, false);
1636                }
1637            }
1638        }
1639
1640        @Override
1641        public void onVolumeForgotten(String fsUuid) {
1642            // Remove any apps installed on the forgotten volume
1643            synchronized (mPackages) {
1644                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1645                for (PackageSetting ps : packages) {
1646                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1647                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1648                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1649                }
1650
1651                mSettings.writeLPr();
1652            }
1653        }
1654    };
1655
1656    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1657        if (userId >= UserHandle.USER_OWNER) {
1658            grantRequestedRuntimePermissionsForUser(pkg, userId);
1659        } else if (userId == UserHandle.USER_ALL) {
1660            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1661                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1662            }
1663        }
1664
1665        // We could have touched GID membership, so flush out packages.list
1666        synchronized (mPackages) {
1667            mSettings.writePackageListLPr();
1668        }
1669    }
1670
1671    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1672        SettingBase sb = (SettingBase) pkg.mExtras;
1673        if (sb == null) {
1674            return;
1675        }
1676
1677        PermissionsState permissionsState = sb.getPermissionsState();
1678
1679        for (String permission : pkg.requestedPermissions) {
1680            BasePermission bp = mSettings.mPermissions.get(permission);
1681            if (bp != null && bp.isRuntime()) {
1682                permissionsState.grantRuntimePermission(bp, userId);
1683            }
1684        }
1685    }
1686
1687    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1688        Bundle extras = null;
1689        switch (res.returnCode) {
1690            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1691                extras = new Bundle();
1692                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1693                        res.origPermission);
1694                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1695                        res.origPackage);
1696                break;
1697            }
1698            case PackageManager.INSTALL_SUCCEEDED: {
1699                extras = new Bundle();
1700                extras.putBoolean(Intent.EXTRA_REPLACING,
1701                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1702                break;
1703            }
1704        }
1705        return extras;
1706    }
1707
1708    void scheduleWriteSettingsLocked() {
1709        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1710            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1711        }
1712    }
1713
1714    void scheduleWritePackageRestrictionsLocked(int userId) {
1715        if (!sUserManager.exists(userId)) return;
1716        mDirtyUsers.add(userId);
1717        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1718            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1719        }
1720    }
1721
1722    public static PackageManagerService main(Context context, Installer installer,
1723            boolean factoryTest, boolean onlyCore) {
1724        PackageManagerService m = new PackageManagerService(context, installer,
1725                factoryTest, onlyCore);
1726        ServiceManager.addService("package", m);
1727        return m;
1728    }
1729
1730    static String[] splitString(String str, char sep) {
1731        int count = 1;
1732        int i = 0;
1733        while ((i=str.indexOf(sep, i)) >= 0) {
1734            count++;
1735            i++;
1736        }
1737
1738        String[] res = new String[count];
1739        i=0;
1740        count = 0;
1741        int lastI=0;
1742        while ((i=str.indexOf(sep, i)) >= 0) {
1743            res[count] = str.substring(lastI, i);
1744            count++;
1745            i++;
1746            lastI = i;
1747        }
1748        res[count] = str.substring(lastI, str.length());
1749        return res;
1750    }
1751
1752    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1753        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1754                Context.DISPLAY_SERVICE);
1755        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1756    }
1757
1758    public PackageManagerService(Context context, Installer installer,
1759            boolean factoryTest, boolean onlyCore) {
1760        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1761                SystemClock.uptimeMillis());
1762
1763        if (mSdkVersion <= 0) {
1764            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1765        }
1766
1767        mContext = context;
1768        mFactoryTest = factoryTest;
1769        mOnlyCore = onlyCore;
1770        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1771        mMetrics = new DisplayMetrics();
1772        mSettings = new Settings(mPackages);
1773        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1774                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1775        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1776                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1777        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1778                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1779        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1780                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1781        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1782                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1783        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1784                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1785
1786        // TODO: add a property to control this?
1787        long dexOptLRUThresholdInMinutes;
1788        if (mLazyDexOpt) {
1789            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1790        } else {
1791            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1792        }
1793        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1794
1795        String separateProcesses = SystemProperties.get("debug.separate_processes");
1796        if (separateProcesses != null && separateProcesses.length() > 0) {
1797            if ("*".equals(separateProcesses)) {
1798                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1799                mSeparateProcesses = null;
1800                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1801            } else {
1802                mDefParseFlags = 0;
1803                mSeparateProcesses = separateProcesses.split(",");
1804                Slog.w(TAG, "Running with debug.separate_processes: "
1805                        + separateProcesses);
1806            }
1807        } else {
1808            mDefParseFlags = 0;
1809            mSeparateProcesses = null;
1810        }
1811
1812        mInstaller = installer;
1813        mPackageDexOptimizer = new PackageDexOptimizer(this);
1814        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1815
1816        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1817                FgThread.get().getLooper());
1818
1819        getDefaultDisplayMetrics(context, mMetrics);
1820
1821        SystemConfig systemConfig = SystemConfig.getInstance();
1822        mGlobalGids = systemConfig.getGlobalGids();
1823        mSystemPermissions = systemConfig.getSystemPermissions();
1824        mAvailableFeatures = systemConfig.getAvailableFeatures();
1825
1826        synchronized (mInstallLock) {
1827        // writer
1828        synchronized (mPackages) {
1829            mHandlerThread = new ServiceThread(TAG,
1830                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1831            mHandlerThread.start();
1832            mHandler = new PackageHandler(mHandlerThread.getLooper());
1833            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1834
1835            File dataDir = Environment.getDataDirectory();
1836            mAppDataDir = new File(dataDir, "data");
1837            mAppInstallDir = new File(dataDir, "app");
1838            mAppLib32InstallDir = new File(dataDir, "app-lib");
1839            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1840            mUserAppDataDir = new File(dataDir, "user");
1841            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1842
1843            sUserManager = new UserManagerService(context, this,
1844                    mInstallLock, mPackages);
1845
1846            // Propagate permission configuration in to package manager.
1847            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1848                    = systemConfig.getPermissions();
1849            for (int i=0; i<permConfig.size(); i++) {
1850                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1851                BasePermission bp = mSettings.mPermissions.get(perm.name);
1852                if (bp == null) {
1853                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1854                    mSettings.mPermissions.put(perm.name, bp);
1855                }
1856                if (perm.gids != null) {
1857                    bp.setGids(perm.gids, perm.perUser);
1858                }
1859            }
1860
1861            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1862            for (int i=0; i<libConfig.size(); i++) {
1863                mSharedLibraries.put(libConfig.keyAt(i),
1864                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1865            }
1866
1867            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1868
1869            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1870                    mSdkVersion, mOnlyCore);
1871
1872            String customResolverActivity = Resources.getSystem().getString(
1873                    R.string.config_customResolverActivity);
1874            if (TextUtils.isEmpty(customResolverActivity)) {
1875                customResolverActivity = null;
1876            } else {
1877                mCustomResolverComponentName = ComponentName.unflattenFromString(
1878                        customResolverActivity);
1879            }
1880
1881            long startTime = SystemClock.uptimeMillis();
1882
1883            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1884                    startTime);
1885
1886            // Set flag to monitor and not change apk file paths when
1887            // scanning install directories.
1888            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1889
1890            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1891
1892            /**
1893             * Add everything in the in the boot class path to the
1894             * list of process files because dexopt will have been run
1895             * if necessary during zygote startup.
1896             */
1897            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1898            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1899
1900            if (bootClassPath != null) {
1901                String[] bootClassPathElements = splitString(bootClassPath, ':');
1902                for (String element : bootClassPathElements) {
1903                    alreadyDexOpted.add(element);
1904                }
1905            } else {
1906                Slog.w(TAG, "No BOOTCLASSPATH found!");
1907            }
1908
1909            if (systemServerClassPath != null) {
1910                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1911                for (String element : systemServerClassPathElements) {
1912                    alreadyDexOpted.add(element);
1913                }
1914            } else {
1915                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1916            }
1917
1918            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1919            final String[] dexCodeInstructionSets =
1920                    getDexCodeInstructionSets(
1921                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1922
1923            /**
1924             * Ensure all external libraries have had dexopt run on them.
1925             */
1926            if (mSharedLibraries.size() > 0) {
1927                // NOTE: For now, we're compiling these system "shared libraries"
1928                // (and framework jars) into all available architectures. It's possible
1929                // to compile them only when we come across an app that uses them (there's
1930                // already logic for that in scanPackageLI) but that adds some complexity.
1931                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1932                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1933                        final String lib = libEntry.path;
1934                        if (lib == null) {
1935                            continue;
1936                        }
1937
1938                        try {
1939                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1940                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1941                                alreadyDexOpted.add(lib);
1942                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1943                            }
1944                        } catch (FileNotFoundException e) {
1945                            Slog.w(TAG, "Library not found: " + lib);
1946                        } catch (IOException e) {
1947                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1948                                    + e.getMessage());
1949                        }
1950                    }
1951                }
1952            }
1953
1954            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1955
1956            // Gross hack for now: we know this file doesn't contain any
1957            // code, so don't dexopt it to avoid the resulting log spew.
1958            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1959
1960            // Gross hack for now: we know this file is only part of
1961            // the boot class path for art, so don't dexopt it to
1962            // avoid the resulting log spew.
1963            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1964
1965            /**
1966             * There are a number of commands implemented in Java, which
1967             * we currently need to do the dexopt on so that they can be
1968             * run from a non-root shell.
1969             */
1970            String[] frameworkFiles = frameworkDir.list();
1971            if (frameworkFiles != null) {
1972                // TODO: We could compile these only for the most preferred ABI. We should
1973                // first double check that the dex files for these commands are not referenced
1974                // by other system apps.
1975                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1976                    for (int i=0; i<frameworkFiles.length; i++) {
1977                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1978                        String path = libPath.getPath();
1979                        // Skip the file if we already did it.
1980                        if (alreadyDexOpted.contains(path)) {
1981                            continue;
1982                        }
1983                        // Skip the file if it is not a type we want to dexopt.
1984                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1985                            continue;
1986                        }
1987                        try {
1988                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1989                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1990                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1991                            }
1992                        } catch (FileNotFoundException e) {
1993                            Slog.w(TAG, "Jar not found: " + path);
1994                        } catch (IOException e) {
1995                            Slog.w(TAG, "Exception reading jar: " + path, e);
1996                        }
1997                    }
1998                }
1999            }
2000
2001            // Collect vendor overlay packages.
2002            // (Do this before scanning any apps.)
2003            // For security and version matching reason, only consider
2004            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2005            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2006            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2007                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2008
2009            // Find base frameworks (resource packages without code).
2010            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2011                    | PackageParser.PARSE_IS_SYSTEM_DIR
2012                    | PackageParser.PARSE_IS_PRIVILEGED,
2013                    scanFlags | SCAN_NO_DEX, 0);
2014
2015            // Collected privileged system packages.
2016            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2017            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2018                    | PackageParser.PARSE_IS_SYSTEM_DIR
2019                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2020
2021            // Collect ordinary system packages.
2022            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2023            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2024                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2025
2026            // Collect all vendor packages.
2027            File vendorAppDir = new File("/vendor/app");
2028            try {
2029                vendorAppDir = vendorAppDir.getCanonicalFile();
2030            } catch (IOException e) {
2031                // failed to look up canonical path, continue with original one
2032            }
2033            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2034                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2035
2036            // Collect all OEM packages.
2037            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2038            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2039                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2040
2041            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2042            mInstaller.moveFiles();
2043
2044            // Prune any system packages that no longer exist.
2045            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2046            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
2047            if (!mOnlyCore) {
2048                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2049                while (psit.hasNext()) {
2050                    PackageSetting ps = psit.next();
2051
2052                    /*
2053                     * If this is not a system app, it can't be a
2054                     * disable system app.
2055                     */
2056                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2057                        continue;
2058                    }
2059
2060                    /*
2061                     * If the package is scanned, it's not erased.
2062                     */
2063                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2064                    if (scannedPkg != null) {
2065                        /*
2066                         * If the system app is both scanned and in the
2067                         * disabled packages list, then it must have been
2068                         * added via OTA. Remove it from the currently
2069                         * scanned package so the previously user-installed
2070                         * application can be scanned.
2071                         */
2072                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2073                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2074                                    + ps.name + "; removing system app.  Last known codePath="
2075                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2076                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2077                                    + scannedPkg.mVersionCode);
2078                            removePackageLI(ps, true);
2079                            expectingBetter.put(ps.name, ps.codePath);
2080                        }
2081
2082                        continue;
2083                    }
2084
2085                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2086                        psit.remove();
2087                        logCriticalInfo(Log.WARN, "System package " + ps.name
2088                                + " no longer exists; wiping its data");
2089                        removeDataDirsLI(null, ps.name);
2090                    } else {
2091                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2092                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2093                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2094                        }
2095                    }
2096                }
2097            }
2098
2099            //look for any incomplete package installations
2100            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2101            //clean up list
2102            for(int i = 0; i < deletePkgsList.size(); i++) {
2103                //clean up here
2104                cleanupInstallFailedPackage(deletePkgsList.get(i));
2105            }
2106            //delete tmp files
2107            deleteTempPackageFiles();
2108
2109            // Remove any shared userIDs that have no associated packages
2110            mSettings.pruneSharedUsersLPw();
2111
2112            if (!mOnlyCore) {
2113                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2114                        SystemClock.uptimeMillis());
2115                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2116
2117                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2118                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2119
2120                /**
2121                 * Remove disable package settings for any updated system
2122                 * apps that were removed via an OTA. If they're not a
2123                 * previously-updated app, remove them completely.
2124                 * Otherwise, just revoke their system-level permissions.
2125                 */
2126                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2127                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2128                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2129
2130                    String msg;
2131                    if (deletedPkg == null) {
2132                        msg = "Updated system package " + deletedAppName
2133                                + " no longer exists; wiping its data";
2134                        removeDataDirsLI(null, deletedAppName);
2135                    } else {
2136                        msg = "Updated system app + " + deletedAppName
2137                                + " no longer present; removing system privileges for "
2138                                + deletedAppName;
2139
2140                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2141
2142                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2143                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2144                    }
2145                    logCriticalInfo(Log.WARN, msg);
2146                }
2147
2148                /**
2149                 * Make sure all system apps that we expected to appear on
2150                 * the userdata partition actually showed up. If they never
2151                 * appeared, crawl back and revive the system version.
2152                 */
2153                for (int i = 0; i < expectingBetter.size(); i++) {
2154                    final String packageName = expectingBetter.keyAt(i);
2155                    if (!mPackages.containsKey(packageName)) {
2156                        final File scanFile = expectingBetter.valueAt(i);
2157
2158                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2159                                + " but never showed up; reverting to system");
2160
2161                        final int reparseFlags;
2162                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2163                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2164                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2165                                    | PackageParser.PARSE_IS_PRIVILEGED;
2166                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2167                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2168                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2169                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2170                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2171                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2172                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2173                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2174                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2175                        } else {
2176                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2177                            continue;
2178                        }
2179
2180                        mSettings.enableSystemPackageLPw(packageName);
2181
2182                        try {
2183                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2184                        } catch (PackageManagerException e) {
2185                            Slog.e(TAG, "Failed to parse original system package: "
2186                                    + e.getMessage());
2187                        }
2188                    }
2189                }
2190            }
2191
2192            // Now that we know all of the shared libraries, update all clients to have
2193            // the correct library paths.
2194            updateAllSharedLibrariesLPw();
2195
2196            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2197                // NOTE: We ignore potential failures here during a system scan (like
2198                // the rest of the commands above) because there's precious little we
2199                // can do about it. A settings error is reported, though.
2200                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2201                        false /* force dexopt */, false /* defer dexopt */);
2202            }
2203
2204            // Now that we know all the packages we are keeping,
2205            // read and update their last usage times.
2206            mPackageUsage.readLP();
2207
2208            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2209                    SystemClock.uptimeMillis());
2210            Slog.i(TAG, "Time to scan packages: "
2211                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2212                    + " seconds");
2213
2214            // If the platform SDK has changed since the last time we booted,
2215            // we need to re-grant app permission to catch any new ones that
2216            // appear.  This is really a hack, and means that apps can in some
2217            // cases get permissions that the user didn't initially explicitly
2218            // allow...  it would be nice to have some better way to handle
2219            // this situation.
2220            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2221                    != mSdkVersion;
2222            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2223                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2224                    + "; regranting permissions for internal storage");
2225            mSettings.mInternalSdkPlatform = mSdkVersion;
2226
2227            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2228                    | (regrantPermissions
2229                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2230                            : 0));
2231
2232            // If this is the first boot, and it is a normal boot, then
2233            // we need to initialize the default preferred apps.
2234            if (!mRestoredSettings && !onlyCore) {
2235                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2236                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2237            }
2238
2239            // If this is first boot after an OTA, and a normal boot, then
2240            // we need to clear code cache directories.
2241            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2242            if (mIsUpgrade && !onlyCore) {
2243                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2244                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2245                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2246                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2247                }
2248                mSettings.mFingerprint = Build.FINGERPRINT;
2249            }
2250
2251            primeDomainVerificationsLPw();
2252            checkDefaultBrowser();
2253
2254            // All the changes are done during package scanning.
2255            mSettings.updateInternalDatabaseVersion();
2256
2257            // can downgrade to reader
2258            mSettings.writeLPr();
2259
2260            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2261                    SystemClock.uptimeMillis());
2262
2263            mRequiredVerifierPackage = getRequiredVerifierLPr();
2264            mRequiredInstallerPackage = getRequiredInstallerLPr();
2265
2266            mInstallerService = new PackageInstallerService(context, this);
2267
2268            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2269            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2270                    mIntentFilterVerifierComponent);
2271
2272        } // synchronized (mPackages)
2273        } // synchronized (mInstallLock)
2274
2275        // Now after opening every single application zip, make sure they
2276        // are all flushed.  Not really needed, but keeps things nice and
2277        // tidy.
2278        Runtime.getRuntime().gc();
2279
2280        // Expose private service for system components to use.
2281        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2282    }
2283
2284    @Override
2285    public boolean isFirstBoot() {
2286        return !mRestoredSettings;
2287    }
2288
2289    @Override
2290    public boolean isOnlyCoreApps() {
2291        return mOnlyCore;
2292    }
2293
2294    @Override
2295    public boolean isUpgrade() {
2296        return mIsUpgrade;
2297    }
2298
2299    private String getRequiredVerifierLPr() {
2300        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2301        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2302                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2303
2304        String requiredVerifier = null;
2305
2306        final int N = receivers.size();
2307        for (int i = 0; i < N; i++) {
2308            final ResolveInfo info = receivers.get(i);
2309
2310            if (info.activityInfo == null) {
2311                continue;
2312            }
2313
2314            final String packageName = info.activityInfo.packageName;
2315
2316            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2317                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2318                continue;
2319            }
2320
2321            if (requiredVerifier != null) {
2322                throw new RuntimeException("There can be only one required verifier");
2323            }
2324
2325            requiredVerifier = packageName;
2326        }
2327
2328        return requiredVerifier;
2329    }
2330
2331    private String getRequiredInstallerLPr() {
2332        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2333        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2334        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2335
2336        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2337                PACKAGE_MIME_TYPE, 0, 0);
2338
2339        String requiredInstaller = null;
2340
2341        final int N = installers.size();
2342        for (int i = 0; i < N; i++) {
2343            final ResolveInfo info = installers.get(i);
2344            final String packageName = info.activityInfo.packageName;
2345
2346            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2347                continue;
2348            }
2349
2350            if (requiredInstaller != null) {
2351                throw new RuntimeException("There must be one required installer");
2352            }
2353
2354            requiredInstaller = packageName;
2355        }
2356
2357        if (requiredInstaller == null) {
2358            throw new RuntimeException("There must be one required installer");
2359        }
2360
2361        return requiredInstaller;
2362    }
2363
2364    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2365        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2366        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2367                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2368
2369        ComponentName verifierComponentName = null;
2370
2371        int priority = -1000;
2372        final int N = receivers.size();
2373        for (int i = 0; i < N; i++) {
2374            final ResolveInfo info = receivers.get(i);
2375
2376            if (info.activityInfo == null) {
2377                continue;
2378            }
2379
2380            final String packageName = info.activityInfo.packageName;
2381
2382            final PackageSetting ps = mSettings.mPackages.get(packageName);
2383            if (ps == null) {
2384                continue;
2385            }
2386
2387            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2388                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2389                continue;
2390            }
2391
2392            // Select the IntentFilterVerifier with the highest priority
2393            if (priority < info.priority) {
2394                priority = info.priority;
2395                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2396                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2397                        + verifierComponentName + " with priority: " + info.priority);
2398            }
2399        }
2400
2401        return verifierComponentName;
2402    }
2403
2404    private void primeDomainVerificationsLPw() {
2405        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Start priming domain verifications");
2406        boolean updated = false;
2407        ArraySet<String> allHostsSet = new ArraySet<>();
2408        for (PackageParser.Package pkg : mPackages.values()) {
2409            final String packageName = pkg.packageName;
2410            if (!hasDomainURLs(pkg)) {
2411                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "No priming domain verifications for " +
2412                            "package with no domain URLs: " + packageName);
2413                continue;
2414            }
2415            if (!pkg.isSystemApp()) {
2416                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2417                        "No priming domain verifications for a non system package : " +
2418                                packageName);
2419                continue;
2420            }
2421            for (PackageParser.Activity a : pkg.activities) {
2422                for (ActivityIntentInfo filter : a.intents) {
2423                    if (hasValidDomains(filter)) {
2424                        allHostsSet.addAll(filter.getHostsList());
2425                    }
2426                }
2427            }
2428            if (allHostsSet.size() == 0) {
2429                allHostsSet.add("*");
2430            }
2431            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2432            IntentFilterVerificationInfo ivi =
2433                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2434            if (ivi != null) {
2435                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2436                        "Priming domain verifications for package: " + packageName +
2437                        " with hosts:" + ivi.getDomainsString());
2438                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2439                updated = true;
2440            }
2441            else {
2442                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2443                        "No priming domain verifications for package: " + packageName);
2444            }
2445            allHostsSet.clear();
2446        }
2447        if (updated) {
2448            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
2449                    "Will need to write primed domain verifications");
2450        }
2451        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "End priming domain verifications");
2452    }
2453
2454    private void applyFactoryDefaultBrowserLPw(int userId) {
2455        // The default browser app's package name is stored in a string resource,
2456        // with a product-specific overlay used for vendor customization.
2457        String browserPkg = mContext.getResources().getString(
2458                com.android.internal.R.string.default_browser);
2459        if (browserPkg != null) {
2460            // non-empty string => required to be a known package
2461            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2462            if (ps == null) {
2463                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2464                browserPkg = null;
2465            } else {
2466                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2467            }
2468        }
2469
2470        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2471        // default.  If there's more than one, just leave everything alone.
2472        if (browserPkg == null) {
2473            calculateDefaultBrowserLPw(userId);
2474        }
2475    }
2476
2477    private void calculateDefaultBrowserLPw(int userId) {
2478        List<String> allBrowsers = resolveAllBrowserApps(userId);
2479        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2480        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2481    }
2482
2483    private List<String> resolveAllBrowserApps(int userId) {
2484        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2485        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2486                PackageManager.MATCH_ALL, userId);
2487
2488        final int count = list.size();
2489        List<String> result = new ArrayList<String>(count);
2490        for (int i=0; i<count; i++) {
2491            ResolveInfo info = list.get(i);
2492            if (info.activityInfo == null
2493                    || !info.handleAllWebDataURI
2494                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2495                    || result.contains(info.activityInfo.packageName)) {
2496                continue;
2497            }
2498            result.add(info.activityInfo.packageName);
2499        }
2500
2501        return result;
2502    }
2503
2504    private boolean packageIsBrowser(String packageName, int userId) {
2505        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2506                PackageManager.MATCH_ALL, userId);
2507        final int N = list.size();
2508        for (int i = 0; i < N; i++) {
2509            ResolveInfo info = list.get(i);
2510            if (packageName.equals(info.activityInfo.packageName)) {
2511                return true;
2512            }
2513        }
2514        return false;
2515    }
2516
2517    private void checkDefaultBrowser() {
2518        final int myUserId = UserHandle.myUserId();
2519        final String packageName = getDefaultBrowserPackageName(myUserId);
2520        if (packageName != null) {
2521            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2522            if (info == null) {
2523                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2524                synchronized (mPackages) {
2525                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2526                }
2527            }
2528        }
2529    }
2530
2531    @Override
2532    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2533            throws RemoteException {
2534        try {
2535            return super.onTransact(code, data, reply, flags);
2536        } catch (RuntimeException e) {
2537            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2538                Slog.wtf(TAG, "Package Manager Crash", e);
2539            }
2540            throw e;
2541        }
2542    }
2543
2544    void cleanupInstallFailedPackage(PackageSetting ps) {
2545        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2546
2547        removeDataDirsLI(ps.volumeUuid, ps.name);
2548        if (ps.codePath != null) {
2549            if (ps.codePath.isDirectory()) {
2550                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2551            } else {
2552                ps.codePath.delete();
2553            }
2554        }
2555        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2556            if (ps.resourcePath.isDirectory()) {
2557                FileUtils.deleteContents(ps.resourcePath);
2558            }
2559            ps.resourcePath.delete();
2560        }
2561        mSettings.removePackageLPw(ps.name);
2562    }
2563
2564    static int[] appendInts(int[] cur, int[] add) {
2565        if (add == null) return cur;
2566        if (cur == null) return add;
2567        final int N = add.length;
2568        for (int i=0; i<N; i++) {
2569            cur = appendInt(cur, add[i]);
2570        }
2571        return cur;
2572    }
2573
2574    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2575        if (!sUserManager.exists(userId)) return null;
2576        final PackageSetting ps = (PackageSetting) p.mExtras;
2577        if (ps == null) {
2578            return null;
2579        }
2580
2581        final PermissionsState permissionsState = ps.getPermissionsState();
2582
2583        final int[] gids = permissionsState.computeGids(userId);
2584        final Set<String> permissions = permissionsState.getPermissions(userId);
2585        final PackageUserState state = ps.readUserState(userId);
2586
2587        return PackageParser.generatePackageInfo(p, gids, flags,
2588                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2589    }
2590
2591    @Override
2592    public boolean isPackageFrozen(String packageName) {
2593        synchronized (mPackages) {
2594            final PackageSetting ps = mSettings.mPackages.get(packageName);
2595            if (ps != null) {
2596                return ps.frozen;
2597            }
2598        }
2599        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2600        return true;
2601    }
2602
2603    @Override
2604    public boolean isPackageAvailable(String packageName, int userId) {
2605        if (!sUserManager.exists(userId)) return false;
2606        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2607        synchronized (mPackages) {
2608            PackageParser.Package p = mPackages.get(packageName);
2609            if (p != null) {
2610                final PackageSetting ps = (PackageSetting) p.mExtras;
2611                if (ps != null) {
2612                    final PackageUserState state = ps.readUserState(userId);
2613                    if (state != null) {
2614                        return PackageParser.isAvailable(state);
2615                    }
2616                }
2617            }
2618        }
2619        return false;
2620    }
2621
2622    @Override
2623    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2624        if (!sUserManager.exists(userId)) return null;
2625        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2626        // reader
2627        synchronized (mPackages) {
2628            PackageParser.Package p = mPackages.get(packageName);
2629            if (DEBUG_PACKAGE_INFO)
2630                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2631            if (p != null) {
2632                return generatePackageInfo(p, flags, userId);
2633            }
2634            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2635                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2636            }
2637        }
2638        return null;
2639    }
2640
2641    @Override
2642    public String[] currentToCanonicalPackageNames(String[] names) {
2643        String[] out = new String[names.length];
2644        // reader
2645        synchronized (mPackages) {
2646            for (int i=names.length-1; i>=0; i--) {
2647                PackageSetting ps = mSettings.mPackages.get(names[i]);
2648                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2649            }
2650        }
2651        return out;
2652    }
2653
2654    @Override
2655    public String[] canonicalToCurrentPackageNames(String[] names) {
2656        String[] out = new String[names.length];
2657        // reader
2658        synchronized (mPackages) {
2659            for (int i=names.length-1; i>=0; i--) {
2660                String cur = mSettings.mRenamedPackages.get(names[i]);
2661                out[i] = cur != null ? cur : names[i];
2662            }
2663        }
2664        return out;
2665    }
2666
2667    @Override
2668    public int getPackageUid(String packageName, int userId) {
2669        if (!sUserManager.exists(userId)) return -1;
2670        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2671
2672        // reader
2673        synchronized (mPackages) {
2674            PackageParser.Package p = mPackages.get(packageName);
2675            if(p != null) {
2676                return UserHandle.getUid(userId, p.applicationInfo.uid);
2677            }
2678            PackageSetting ps = mSettings.mPackages.get(packageName);
2679            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2680                return -1;
2681            }
2682            p = ps.pkg;
2683            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2684        }
2685    }
2686
2687    @Override
2688    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2689        if (!sUserManager.exists(userId)) {
2690            return null;
2691        }
2692
2693        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2694                "getPackageGids");
2695
2696        // reader
2697        synchronized (mPackages) {
2698            PackageParser.Package p = mPackages.get(packageName);
2699            if (DEBUG_PACKAGE_INFO) {
2700                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2701            }
2702            if (p != null) {
2703                PackageSetting ps = (PackageSetting) p.mExtras;
2704                return ps.getPermissionsState().computeGids(userId);
2705            }
2706        }
2707
2708        return null;
2709    }
2710
2711    @Override
2712    public int getMountExternalMode(int uid) {
2713        if (Process.isIsolated(uid)) {
2714            return Zygote.MOUNT_EXTERNAL_NONE;
2715        } else {
2716            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2717                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2718            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2719                return Zygote.MOUNT_EXTERNAL_WRITE;
2720            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2721                return Zygote.MOUNT_EXTERNAL_READ;
2722            } else {
2723                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2724            }
2725        }
2726    }
2727
2728    static PermissionInfo generatePermissionInfo(
2729            BasePermission bp, int flags) {
2730        if (bp.perm != null) {
2731            return PackageParser.generatePermissionInfo(bp.perm, flags);
2732        }
2733        PermissionInfo pi = new PermissionInfo();
2734        pi.name = bp.name;
2735        pi.packageName = bp.sourcePackage;
2736        pi.nonLocalizedLabel = bp.name;
2737        pi.protectionLevel = bp.protectionLevel;
2738        return pi;
2739    }
2740
2741    @Override
2742    public PermissionInfo getPermissionInfo(String name, int flags) {
2743        // reader
2744        synchronized (mPackages) {
2745            final BasePermission p = mSettings.mPermissions.get(name);
2746            if (p != null) {
2747                return generatePermissionInfo(p, flags);
2748            }
2749            return null;
2750        }
2751    }
2752
2753    @Override
2754    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2755        // reader
2756        synchronized (mPackages) {
2757            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2758            for (BasePermission p : mSettings.mPermissions.values()) {
2759                if (group == null) {
2760                    if (p.perm == null || p.perm.info.group == null) {
2761                        out.add(generatePermissionInfo(p, flags));
2762                    }
2763                } else {
2764                    if (p.perm != null && group.equals(p.perm.info.group)) {
2765                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2766                    }
2767                }
2768            }
2769
2770            if (out.size() > 0) {
2771                return out;
2772            }
2773            return mPermissionGroups.containsKey(group) ? out : null;
2774        }
2775    }
2776
2777    @Override
2778    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2779        // reader
2780        synchronized (mPackages) {
2781            return PackageParser.generatePermissionGroupInfo(
2782                    mPermissionGroups.get(name), flags);
2783        }
2784    }
2785
2786    @Override
2787    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2788        // reader
2789        synchronized (mPackages) {
2790            final int N = mPermissionGroups.size();
2791            ArrayList<PermissionGroupInfo> out
2792                    = new ArrayList<PermissionGroupInfo>(N);
2793            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2794                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2795            }
2796            return out;
2797        }
2798    }
2799
2800    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2801            int userId) {
2802        if (!sUserManager.exists(userId)) return null;
2803        PackageSetting ps = mSettings.mPackages.get(packageName);
2804        if (ps != null) {
2805            if (ps.pkg == null) {
2806                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2807                        flags, userId);
2808                if (pInfo != null) {
2809                    return pInfo.applicationInfo;
2810                }
2811                return null;
2812            }
2813            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2814                    ps.readUserState(userId), userId);
2815        }
2816        return null;
2817    }
2818
2819    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2820            int userId) {
2821        if (!sUserManager.exists(userId)) return null;
2822        PackageSetting ps = mSettings.mPackages.get(packageName);
2823        if (ps != null) {
2824            PackageParser.Package pkg = ps.pkg;
2825            if (pkg == null) {
2826                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2827                    return null;
2828                }
2829                // Only data remains, so we aren't worried about code paths
2830                pkg = new PackageParser.Package(packageName);
2831                pkg.applicationInfo.packageName = packageName;
2832                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2833                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2834                pkg.applicationInfo.dataDir = Environment
2835                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2836                        .getAbsolutePath();
2837                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2838                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2839            }
2840            return generatePackageInfo(pkg, flags, userId);
2841        }
2842        return null;
2843    }
2844
2845    @Override
2846    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2847        if (!sUserManager.exists(userId)) return null;
2848        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2849        // writer
2850        synchronized (mPackages) {
2851            PackageParser.Package p = mPackages.get(packageName);
2852            if (DEBUG_PACKAGE_INFO) Log.v(
2853                    TAG, "getApplicationInfo " + packageName
2854                    + ": " + p);
2855            if (p != null) {
2856                PackageSetting ps = mSettings.mPackages.get(packageName);
2857                if (ps == null) return null;
2858                // Note: isEnabledLP() does not apply here - always return info
2859                return PackageParser.generateApplicationInfo(
2860                        p, flags, ps.readUserState(userId), userId);
2861            }
2862            if ("android".equals(packageName)||"system".equals(packageName)) {
2863                return mAndroidApplication;
2864            }
2865            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2866                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2867            }
2868        }
2869        return null;
2870    }
2871
2872    @Override
2873    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2874            final IPackageDataObserver observer) {
2875        mContext.enforceCallingOrSelfPermission(
2876                android.Manifest.permission.CLEAR_APP_CACHE, null);
2877        // Queue up an async operation since clearing cache may take a little while.
2878        mHandler.post(new Runnable() {
2879            public void run() {
2880                mHandler.removeCallbacks(this);
2881                int retCode = -1;
2882                synchronized (mInstallLock) {
2883                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2884                    if (retCode < 0) {
2885                        Slog.w(TAG, "Couldn't clear application caches");
2886                    }
2887                }
2888                if (observer != null) {
2889                    try {
2890                        observer.onRemoveCompleted(null, (retCode >= 0));
2891                    } catch (RemoteException e) {
2892                        Slog.w(TAG, "RemoveException when invoking call back");
2893                    }
2894                }
2895            }
2896        });
2897    }
2898
2899    @Override
2900    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2901            final IntentSender pi) {
2902        mContext.enforceCallingOrSelfPermission(
2903                android.Manifest.permission.CLEAR_APP_CACHE, null);
2904        // Queue up an async operation since clearing cache may take a little while.
2905        mHandler.post(new Runnable() {
2906            public void run() {
2907                mHandler.removeCallbacks(this);
2908                int retCode = -1;
2909                synchronized (mInstallLock) {
2910                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2911                    if (retCode < 0) {
2912                        Slog.w(TAG, "Couldn't clear application caches");
2913                    }
2914                }
2915                if(pi != null) {
2916                    try {
2917                        // Callback via pending intent
2918                        int code = (retCode >= 0) ? 1 : 0;
2919                        pi.sendIntent(null, code, null,
2920                                null, null);
2921                    } catch (SendIntentException e1) {
2922                        Slog.i(TAG, "Failed to send pending intent");
2923                    }
2924                }
2925            }
2926        });
2927    }
2928
2929    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2930        synchronized (mInstallLock) {
2931            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2932                throw new IOException("Failed to free enough space");
2933            }
2934        }
2935    }
2936
2937    @Override
2938    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2939        if (!sUserManager.exists(userId)) return null;
2940        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2941        synchronized (mPackages) {
2942            PackageParser.Activity a = mActivities.mActivities.get(component);
2943
2944            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2945            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2946                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2947                if (ps == null) return null;
2948                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2949                        userId);
2950            }
2951            if (mResolveComponentName.equals(component)) {
2952                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2953                        new PackageUserState(), userId);
2954            }
2955        }
2956        return null;
2957    }
2958
2959    @Override
2960    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2961            String resolvedType) {
2962        synchronized (mPackages) {
2963            PackageParser.Activity a = mActivities.mActivities.get(component);
2964            if (a == null) {
2965                return false;
2966            }
2967            for (int i=0; i<a.intents.size(); i++) {
2968                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2969                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2970                    return true;
2971                }
2972            }
2973            return false;
2974        }
2975    }
2976
2977    @Override
2978    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2979        if (!sUserManager.exists(userId)) return null;
2980        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2981        synchronized (mPackages) {
2982            PackageParser.Activity a = mReceivers.mActivities.get(component);
2983            if (DEBUG_PACKAGE_INFO) Log.v(
2984                TAG, "getReceiverInfo " + component + ": " + a);
2985            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2986                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2987                if (ps == null) return null;
2988                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2989                        userId);
2990            }
2991        }
2992        return null;
2993    }
2994
2995    @Override
2996    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2997        if (!sUserManager.exists(userId)) return null;
2998        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2999        synchronized (mPackages) {
3000            PackageParser.Service s = mServices.mServices.get(component);
3001            if (DEBUG_PACKAGE_INFO) Log.v(
3002                TAG, "getServiceInfo " + component + ": " + s);
3003            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3004                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3005                if (ps == null) return null;
3006                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3007                        userId);
3008            }
3009        }
3010        return null;
3011    }
3012
3013    @Override
3014    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3015        if (!sUserManager.exists(userId)) return null;
3016        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3017        synchronized (mPackages) {
3018            PackageParser.Provider p = mProviders.mProviders.get(component);
3019            if (DEBUG_PACKAGE_INFO) Log.v(
3020                TAG, "getProviderInfo " + component + ": " + p);
3021            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3022                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3023                if (ps == null) return null;
3024                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3025                        userId);
3026            }
3027        }
3028        return null;
3029    }
3030
3031    @Override
3032    public String[] getSystemSharedLibraryNames() {
3033        Set<String> libSet;
3034        synchronized (mPackages) {
3035            libSet = mSharedLibraries.keySet();
3036            int size = libSet.size();
3037            if (size > 0) {
3038                String[] libs = new String[size];
3039                libSet.toArray(libs);
3040                return libs;
3041            }
3042        }
3043        return null;
3044    }
3045
3046    /**
3047     * @hide
3048     */
3049    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3050        synchronized (mPackages) {
3051            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3052            if (lib != null && lib.apk != null) {
3053                return mPackages.get(lib.apk);
3054            }
3055        }
3056        return null;
3057    }
3058
3059    @Override
3060    public FeatureInfo[] getSystemAvailableFeatures() {
3061        Collection<FeatureInfo> featSet;
3062        synchronized (mPackages) {
3063            featSet = mAvailableFeatures.values();
3064            int size = featSet.size();
3065            if (size > 0) {
3066                FeatureInfo[] features = new FeatureInfo[size+1];
3067                featSet.toArray(features);
3068                FeatureInfo fi = new FeatureInfo();
3069                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3070                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3071                features[size] = fi;
3072                return features;
3073            }
3074        }
3075        return null;
3076    }
3077
3078    @Override
3079    public boolean hasSystemFeature(String name) {
3080        synchronized (mPackages) {
3081            return mAvailableFeatures.containsKey(name);
3082        }
3083    }
3084
3085    private void checkValidCaller(int uid, int userId) {
3086        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3087            return;
3088
3089        throw new SecurityException("Caller uid=" + uid
3090                + " is not privileged to communicate with user=" + userId);
3091    }
3092
3093    @Override
3094    public int checkPermission(String permName, String pkgName, int userId) {
3095        if (!sUserManager.exists(userId)) {
3096            return PackageManager.PERMISSION_DENIED;
3097        }
3098
3099        synchronized (mPackages) {
3100            final PackageParser.Package p = mPackages.get(pkgName);
3101            if (p != null && p.mExtras != null) {
3102                final PackageSetting ps = (PackageSetting) p.mExtras;
3103                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3104                    return PackageManager.PERMISSION_GRANTED;
3105                }
3106            }
3107        }
3108
3109        return PackageManager.PERMISSION_DENIED;
3110    }
3111
3112    @Override
3113    public int checkUidPermission(String permName, int uid) {
3114        final int userId = UserHandle.getUserId(uid);
3115
3116        if (!sUserManager.exists(userId)) {
3117            return PackageManager.PERMISSION_DENIED;
3118        }
3119
3120        synchronized (mPackages) {
3121            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3122            if (obj != null) {
3123                final SettingBase ps = (SettingBase) obj;
3124                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3125                    return PackageManager.PERMISSION_GRANTED;
3126                }
3127            } else {
3128                ArraySet<String> perms = mSystemPermissions.get(uid);
3129                if (perms != null && perms.contains(permName)) {
3130                    return PackageManager.PERMISSION_GRANTED;
3131                }
3132            }
3133        }
3134
3135        return PackageManager.PERMISSION_DENIED;
3136    }
3137
3138    /**
3139     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3140     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3141     * @param checkShell TODO(yamasani):
3142     * @param message the message to log on security exception
3143     */
3144    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3145            boolean checkShell, String message) {
3146        if (userId < 0) {
3147            throw new IllegalArgumentException("Invalid userId " + userId);
3148        }
3149        if (checkShell) {
3150            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3151        }
3152        if (userId == UserHandle.getUserId(callingUid)) return;
3153        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3154            if (requireFullPermission) {
3155                mContext.enforceCallingOrSelfPermission(
3156                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3157            } else {
3158                try {
3159                    mContext.enforceCallingOrSelfPermission(
3160                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3161                } catch (SecurityException se) {
3162                    mContext.enforceCallingOrSelfPermission(
3163                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3164                }
3165            }
3166        }
3167    }
3168
3169    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3170        if (callingUid == Process.SHELL_UID) {
3171            if (userHandle >= 0
3172                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3173                throw new SecurityException("Shell does not have permission to access user "
3174                        + userHandle);
3175            } else if (userHandle < 0) {
3176                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3177                        + Debug.getCallers(3));
3178            }
3179        }
3180    }
3181
3182    private BasePermission findPermissionTreeLP(String permName) {
3183        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3184            if (permName.startsWith(bp.name) &&
3185                    permName.length() > bp.name.length() &&
3186                    permName.charAt(bp.name.length()) == '.') {
3187                return bp;
3188            }
3189        }
3190        return null;
3191    }
3192
3193    private BasePermission checkPermissionTreeLP(String permName) {
3194        if (permName != null) {
3195            BasePermission bp = findPermissionTreeLP(permName);
3196            if (bp != null) {
3197                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3198                    return bp;
3199                }
3200                throw new SecurityException("Calling uid "
3201                        + Binder.getCallingUid()
3202                        + " is not allowed to add to permission tree "
3203                        + bp.name + " owned by uid " + bp.uid);
3204            }
3205        }
3206        throw new SecurityException("No permission tree found for " + permName);
3207    }
3208
3209    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3210        if (s1 == null) {
3211            return s2 == null;
3212        }
3213        if (s2 == null) {
3214            return false;
3215        }
3216        if (s1.getClass() != s2.getClass()) {
3217            return false;
3218        }
3219        return s1.equals(s2);
3220    }
3221
3222    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3223        if (pi1.icon != pi2.icon) return false;
3224        if (pi1.logo != pi2.logo) return false;
3225        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3226        if (!compareStrings(pi1.name, pi2.name)) return false;
3227        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3228        // We'll take care of setting this one.
3229        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3230        // These are not currently stored in settings.
3231        //if (!compareStrings(pi1.group, pi2.group)) return false;
3232        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3233        //if (pi1.labelRes != pi2.labelRes) return false;
3234        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3235        return true;
3236    }
3237
3238    int permissionInfoFootprint(PermissionInfo info) {
3239        int size = info.name.length();
3240        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3241        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3242        return size;
3243    }
3244
3245    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3246        int size = 0;
3247        for (BasePermission perm : mSettings.mPermissions.values()) {
3248            if (perm.uid == tree.uid) {
3249                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3250            }
3251        }
3252        return size;
3253    }
3254
3255    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3256        // We calculate the max size of permissions defined by this uid and throw
3257        // if that plus the size of 'info' would exceed our stated maximum.
3258        if (tree.uid != Process.SYSTEM_UID) {
3259            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3260            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3261                throw new SecurityException("Permission tree size cap exceeded");
3262            }
3263        }
3264    }
3265
3266    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3267        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3268            throw new SecurityException("Label must be specified in permission");
3269        }
3270        BasePermission tree = checkPermissionTreeLP(info.name);
3271        BasePermission bp = mSettings.mPermissions.get(info.name);
3272        boolean added = bp == null;
3273        boolean changed = true;
3274        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3275        if (added) {
3276            enforcePermissionCapLocked(info, tree);
3277            bp = new BasePermission(info.name, tree.sourcePackage,
3278                    BasePermission.TYPE_DYNAMIC);
3279        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3280            throw new SecurityException(
3281                    "Not allowed to modify non-dynamic permission "
3282                    + info.name);
3283        } else {
3284            if (bp.protectionLevel == fixedLevel
3285                    && bp.perm.owner.equals(tree.perm.owner)
3286                    && bp.uid == tree.uid
3287                    && comparePermissionInfos(bp.perm.info, info)) {
3288                changed = false;
3289            }
3290        }
3291        bp.protectionLevel = fixedLevel;
3292        info = new PermissionInfo(info);
3293        info.protectionLevel = fixedLevel;
3294        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3295        bp.perm.info.packageName = tree.perm.info.packageName;
3296        bp.uid = tree.uid;
3297        if (added) {
3298            mSettings.mPermissions.put(info.name, bp);
3299        }
3300        if (changed) {
3301            if (!async) {
3302                mSettings.writeLPr();
3303            } else {
3304                scheduleWriteSettingsLocked();
3305            }
3306        }
3307        return added;
3308    }
3309
3310    @Override
3311    public boolean addPermission(PermissionInfo info) {
3312        synchronized (mPackages) {
3313            return addPermissionLocked(info, false);
3314        }
3315    }
3316
3317    @Override
3318    public boolean addPermissionAsync(PermissionInfo info) {
3319        synchronized (mPackages) {
3320            return addPermissionLocked(info, true);
3321        }
3322    }
3323
3324    @Override
3325    public void removePermission(String name) {
3326        synchronized (mPackages) {
3327            checkPermissionTreeLP(name);
3328            BasePermission bp = mSettings.mPermissions.get(name);
3329            if (bp != null) {
3330                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3331                    throw new SecurityException(
3332                            "Not allowed to modify non-dynamic permission "
3333                            + name);
3334                }
3335                mSettings.mPermissions.remove(name);
3336                mSettings.writeLPr();
3337            }
3338        }
3339    }
3340
3341    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3342            BasePermission bp) {
3343        int index = pkg.requestedPermissions.indexOf(bp.name);
3344        if (index == -1) {
3345            throw new SecurityException("Package " + pkg.packageName
3346                    + " has not requested permission " + bp.name);
3347        }
3348        if (!bp.isRuntime()) {
3349            throw new SecurityException("Permission " + bp.name
3350                    + " is not a changeable permission type");
3351        }
3352    }
3353
3354    @Override
3355    public void grantRuntimePermission(String packageName, String name, final int userId) {
3356        if (!sUserManager.exists(userId)) {
3357            Log.e(TAG, "No such user:" + userId);
3358            return;
3359        }
3360
3361        mContext.enforceCallingOrSelfPermission(
3362                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3363                "grantRuntimePermission");
3364
3365        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3366                "grantRuntimePermission");
3367
3368        final int uid;
3369        final SettingBase sb;
3370
3371        synchronized (mPackages) {
3372            final PackageParser.Package pkg = mPackages.get(packageName);
3373            if (pkg == null) {
3374                throw new IllegalArgumentException("Unknown package: " + packageName);
3375            }
3376
3377            final BasePermission bp = mSettings.mPermissions.get(name);
3378            if (bp == null) {
3379                throw new IllegalArgumentException("Unknown permission: " + name);
3380            }
3381
3382            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3383
3384            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3385            sb = (SettingBase) pkg.mExtras;
3386            if (sb == null) {
3387                throw new IllegalArgumentException("Unknown package: " + packageName);
3388            }
3389
3390            final PermissionsState permissionsState = sb.getPermissionsState();
3391
3392            final int flags = permissionsState.getPermissionFlags(name, userId);
3393            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3394                throw new SecurityException("Cannot grant system fixed permission: "
3395                        + name + " for package: " + packageName);
3396            }
3397
3398            final int result = permissionsState.grantRuntimePermission(bp, userId);
3399            switch (result) {
3400                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3401                    return;
3402                }
3403
3404                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3405                    mHandler.post(new Runnable() {
3406                        @Override
3407                        public void run() {
3408                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3409                        }
3410                    });
3411                } break;
3412            }
3413
3414            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3415
3416            // Not critical if that is lost - app has to request again.
3417            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3418        }
3419
3420        if (READ_EXTERNAL_STORAGE.equals(name)
3421                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3422            final long token = Binder.clearCallingIdentity();
3423            try {
3424                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3425                storage.remountUid(uid);
3426            } finally {
3427                Binder.restoreCallingIdentity(token);
3428            }
3429        }
3430    }
3431
3432    @Override
3433    public void revokeRuntimePermission(String packageName, String name, int userId) {
3434        if (!sUserManager.exists(userId)) {
3435            Log.e(TAG, "No such user:" + userId);
3436            return;
3437        }
3438
3439        mContext.enforceCallingOrSelfPermission(
3440                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3441                "revokeRuntimePermission");
3442
3443        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3444                "revokeRuntimePermission");
3445
3446        final SettingBase sb;
3447
3448        synchronized (mPackages) {
3449            final PackageParser.Package pkg = mPackages.get(packageName);
3450            if (pkg == null) {
3451                throw new IllegalArgumentException("Unknown package: " + packageName);
3452            }
3453
3454            final BasePermission bp = mSettings.mPermissions.get(name);
3455            if (bp == null) {
3456                throw new IllegalArgumentException("Unknown permission: " + name);
3457            }
3458
3459            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3460
3461            sb = (SettingBase) pkg.mExtras;
3462            if (sb == null) {
3463                throw new IllegalArgumentException("Unknown package: " + packageName);
3464            }
3465
3466            final PermissionsState permissionsState = sb.getPermissionsState();
3467
3468            final int flags = permissionsState.getPermissionFlags(name, userId);
3469            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3470                throw new SecurityException("Cannot revoke system fixed permission: "
3471                        + name + " for package: " + packageName);
3472            }
3473
3474            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3475                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3476                return;
3477            }
3478
3479            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3480
3481            // Critical, after this call app should never have the permission.
3482            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3483        }
3484
3485        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3486    }
3487
3488    @Override
3489    public void resetRuntimePermissions() {
3490        mContext.enforceCallingOrSelfPermission(
3491                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3492                "revokeRuntimePermission");
3493
3494        int callingUid = Binder.getCallingUid();
3495        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3496            mContext.enforceCallingOrSelfPermission(
3497                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3498                    "resetRuntimePermissions");
3499        }
3500
3501        final int[] userIds;
3502
3503        synchronized (mPackages) {
3504            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3505            final int userCount = UserManagerService.getInstance().getUserIds().length;
3506            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3507        }
3508
3509        for (int userId : userIds) {
3510            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3511        }
3512    }
3513
3514    @Override
3515    public int getPermissionFlags(String name, String packageName, int userId) {
3516        if (!sUserManager.exists(userId)) {
3517            return 0;
3518        }
3519
3520        mContext.enforceCallingOrSelfPermission(
3521                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3522                "getPermissionFlags");
3523
3524        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3525                "getPermissionFlags");
3526
3527        synchronized (mPackages) {
3528            final PackageParser.Package pkg = mPackages.get(packageName);
3529            if (pkg == null) {
3530                throw new IllegalArgumentException("Unknown package: " + packageName);
3531            }
3532
3533            final BasePermission bp = mSettings.mPermissions.get(name);
3534            if (bp == null) {
3535                throw new IllegalArgumentException("Unknown permission: " + name);
3536            }
3537
3538            SettingBase sb = (SettingBase) pkg.mExtras;
3539            if (sb == null) {
3540                throw new IllegalArgumentException("Unknown package: " + packageName);
3541            }
3542
3543            PermissionsState permissionsState = sb.getPermissionsState();
3544            return permissionsState.getPermissionFlags(name, userId);
3545        }
3546    }
3547
3548    @Override
3549    public void updatePermissionFlags(String name, String packageName, int flagMask,
3550            int flagValues, int userId) {
3551        if (!sUserManager.exists(userId)) {
3552            return;
3553        }
3554
3555        mContext.enforceCallingOrSelfPermission(
3556                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3557                "updatePermissionFlags");
3558
3559        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3560                "updatePermissionFlags");
3561
3562        // Only the system can change system fixed flags.
3563        if (getCallingUid() != Process.SYSTEM_UID) {
3564            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3565            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3566        }
3567
3568        synchronized (mPackages) {
3569            final PackageParser.Package pkg = mPackages.get(packageName);
3570            if (pkg == null) {
3571                throw new IllegalArgumentException("Unknown package: " + packageName);
3572            }
3573
3574            final BasePermission bp = mSettings.mPermissions.get(name);
3575            if (bp == null) {
3576                throw new IllegalArgumentException("Unknown permission: " + name);
3577            }
3578
3579            SettingBase sb = (SettingBase) pkg.mExtras;
3580            if (sb == null) {
3581                throw new IllegalArgumentException("Unknown package: " + packageName);
3582            }
3583
3584            PermissionsState permissionsState = sb.getPermissionsState();
3585
3586            // Only the package manager can change flags for system component permissions.
3587            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3588            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3589                return;
3590            }
3591
3592            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3593
3594            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3595                // Install and runtime permissions are stored in different places,
3596                // so figure out what permission changed and persist the change.
3597                if (permissionsState.getInstallPermissionState(name) != null) {
3598                    scheduleWriteSettingsLocked();
3599                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3600                        || hadState) {
3601                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3602                }
3603            }
3604        }
3605    }
3606
3607    /**
3608     * Update the permission flags for all packages and runtime permissions of a user in order
3609     * to allow device or profile owner to remove POLICY_FIXED.
3610     */
3611    @Override
3612    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3613        if (!sUserManager.exists(userId)) {
3614            return;
3615        }
3616
3617        mContext.enforceCallingOrSelfPermission(
3618                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3619                "updatePermissionFlagsForAllApps");
3620
3621        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3622                "updatePermissionFlagsForAllApps");
3623
3624        // Only the system can change system fixed flags.
3625        if (getCallingUid() != Process.SYSTEM_UID) {
3626            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3627            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3628        }
3629
3630        synchronized (mPackages) {
3631            boolean changed = false;
3632            final int packageCount = mPackages.size();
3633            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3634                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3635                SettingBase sb = (SettingBase) pkg.mExtras;
3636                if (sb == null) {
3637                    continue;
3638                }
3639                PermissionsState permissionsState = sb.getPermissionsState();
3640                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3641                        userId, flagMask, flagValues);
3642            }
3643            if (changed) {
3644                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3645            }
3646        }
3647    }
3648
3649    @Override
3650    public boolean shouldShowRequestPermissionRationale(String permissionName,
3651            String packageName, int userId) {
3652        if (UserHandle.getCallingUserId() != userId) {
3653            mContext.enforceCallingPermission(
3654                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3655                    "canShowRequestPermissionRationale for user " + userId);
3656        }
3657
3658        final int uid = getPackageUid(packageName, userId);
3659        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3660            return false;
3661        }
3662
3663        if (checkPermission(permissionName, packageName, userId)
3664                == PackageManager.PERMISSION_GRANTED) {
3665            return false;
3666        }
3667
3668        final int flags;
3669
3670        final long identity = Binder.clearCallingIdentity();
3671        try {
3672            flags = getPermissionFlags(permissionName,
3673                    packageName, userId);
3674        } finally {
3675            Binder.restoreCallingIdentity(identity);
3676        }
3677
3678        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3679                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3680                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3681
3682        if ((flags & fixedFlags) != 0) {
3683            return false;
3684        }
3685
3686        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3687    }
3688
3689    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3690        BasePermission bp = mSettings.mPermissions.get(permission);
3691        if (bp == null) {
3692            throw new SecurityException("Missing " + permission + " permission");
3693        }
3694
3695        SettingBase sb = (SettingBase) pkg.mExtras;
3696        PermissionsState permissionsState = sb.getPermissionsState();
3697
3698        if (permissionsState.grantInstallPermission(bp) !=
3699                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3700            scheduleWriteSettingsLocked();
3701        }
3702    }
3703
3704    @Override
3705    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3706        mContext.enforceCallingOrSelfPermission(
3707                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3708                "addOnPermissionsChangeListener");
3709
3710        synchronized (mPackages) {
3711            mOnPermissionChangeListeners.addListenerLocked(listener);
3712        }
3713    }
3714
3715    @Override
3716    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3717        synchronized (mPackages) {
3718            mOnPermissionChangeListeners.removeListenerLocked(listener);
3719        }
3720    }
3721
3722    @Override
3723    public boolean isProtectedBroadcast(String actionName) {
3724        synchronized (mPackages) {
3725            return mProtectedBroadcasts.contains(actionName);
3726        }
3727    }
3728
3729    @Override
3730    public int checkSignatures(String pkg1, String pkg2) {
3731        synchronized (mPackages) {
3732            final PackageParser.Package p1 = mPackages.get(pkg1);
3733            final PackageParser.Package p2 = mPackages.get(pkg2);
3734            if (p1 == null || p1.mExtras == null
3735                    || p2 == null || p2.mExtras == null) {
3736                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3737            }
3738            return compareSignatures(p1.mSignatures, p2.mSignatures);
3739        }
3740    }
3741
3742    @Override
3743    public int checkUidSignatures(int uid1, int uid2) {
3744        // Map to base uids.
3745        uid1 = UserHandle.getAppId(uid1);
3746        uid2 = UserHandle.getAppId(uid2);
3747        // reader
3748        synchronized (mPackages) {
3749            Signature[] s1;
3750            Signature[] s2;
3751            Object obj = mSettings.getUserIdLPr(uid1);
3752            if (obj != null) {
3753                if (obj instanceof SharedUserSetting) {
3754                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3755                } else if (obj instanceof PackageSetting) {
3756                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3757                } else {
3758                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3759                }
3760            } else {
3761                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3762            }
3763            obj = mSettings.getUserIdLPr(uid2);
3764            if (obj != null) {
3765                if (obj instanceof SharedUserSetting) {
3766                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3767                } else if (obj instanceof PackageSetting) {
3768                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3769                } else {
3770                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3771                }
3772            } else {
3773                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3774            }
3775            return compareSignatures(s1, s2);
3776        }
3777    }
3778
3779    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3780        final long identity = Binder.clearCallingIdentity();
3781        try {
3782            if (sb instanceof SharedUserSetting) {
3783                SharedUserSetting sus = (SharedUserSetting) sb;
3784                final int packageCount = sus.packages.size();
3785                for (int i = 0; i < packageCount; i++) {
3786                    PackageSetting susPs = sus.packages.valueAt(i);
3787                    if (userId == UserHandle.USER_ALL) {
3788                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3789                    } else {
3790                        final int uid = UserHandle.getUid(userId, susPs.appId);
3791                        killUid(uid, reason);
3792                    }
3793                }
3794            } else if (sb instanceof PackageSetting) {
3795                PackageSetting ps = (PackageSetting) sb;
3796                if (userId == UserHandle.USER_ALL) {
3797                    killApplication(ps.pkg.packageName, ps.appId, reason);
3798                } else {
3799                    final int uid = UserHandle.getUid(userId, ps.appId);
3800                    killUid(uid, reason);
3801                }
3802            }
3803        } finally {
3804            Binder.restoreCallingIdentity(identity);
3805        }
3806    }
3807
3808    private static void killUid(int uid, String reason) {
3809        IActivityManager am = ActivityManagerNative.getDefault();
3810        if (am != null) {
3811            try {
3812                am.killUid(uid, reason);
3813            } catch (RemoteException e) {
3814                /* ignore - same process */
3815            }
3816        }
3817    }
3818
3819    /**
3820     * Compares two sets of signatures. Returns:
3821     * <br />
3822     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3823     * <br />
3824     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3825     * <br />
3826     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3827     * <br />
3828     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3829     * <br />
3830     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3831     */
3832    static int compareSignatures(Signature[] s1, Signature[] s2) {
3833        if (s1 == null) {
3834            return s2 == null
3835                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3836                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3837        }
3838
3839        if (s2 == null) {
3840            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3841        }
3842
3843        if (s1.length != s2.length) {
3844            return PackageManager.SIGNATURE_NO_MATCH;
3845        }
3846
3847        // Since both signature sets are of size 1, we can compare without HashSets.
3848        if (s1.length == 1) {
3849            return s1[0].equals(s2[0]) ?
3850                    PackageManager.SIGNATURE_MATCH :
3851                    PackageManager.SIGNATURE_NO_MATCH;
3852        }
3853
3854        ArraySet<Signature> set1 = new ArraySet<Signature>();
3855        for (Signature sig : s1) {
3856            set1.add(sig);
3857        }
3858        ArraySet<Signature> set2 = new ArraySet<Signature>();
3859        for (Signature sig : s2) {
3860            set2.add(sig);
3861        }
3862        // Make sure s2 contains all signatures in s1.
3863        if (set1.equals(set2)) {
3864            return PackageManager.SIGNATURE_MATCH;
3865        }
3866        return PackageManager.SIGNATURE_NO_MATCH;
3867    }
3868
3869    /**
3870     * If the database version for this type of package (internal storage or
3871     * external storage) is less than the version where package signatures
3872     * were updated, return true.
3873     */
3874    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3875        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3876                DatabaseVersion.SIGNATURE_END_ENTITY))
3877                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3878                        DatabaseVersion.SIGNATURE_END_ENTITY));
3879    }
3880
3881    /**
3882     * Used for backward compatibility to make sure any packages with
3883     * certificate chains get upgraded to the new style. {@code existingSigs}
3884     * will be in the old format (since they were stored on disk from before the
3885     * system upgrade) and {@code scannedSigs} will be in the newer format.
3886     */
3887    private int compareSignaturesCompat(PackageSignatures existingSigs,
3888            PackageParser.Package scannedPkg) {
3889        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3890            return PackageManager.SIGNATURE_NO_MATCH;
3891        }
3892
3893        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3894        for (Signature sig : existingSigs.mSignatures) {
3895            existingSet.add(sig);
3896        }
3897        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3898        for (Signature sig : scannedPkg.mSignatures) {
3899            try {
3900                Signature[] chainSignatures = sig.getChainSignatures();
3901                for (Signature chainSig : chainSignatures) {
3902                    scannedCompatSet.add(chainSig);
3903                }
3904            } catch (CertificateEncodingException e) {
3905                scannedCompatSet.add(sig);
3906            }
3907        }
3908        /*
3909         * Make sure the expanded scanned set contains all signatures in the
3910         * existing one.
3911         */
3912        if (scannedCompatSet.equals(existingSet)) {
3913            // Migrate the old signatures to the new scheme.
3914            existingSigs.assignSignatures(scannedPkg.mSignatures);
3915            // The new KeySets will be re-added later in the scanning process.
3916            synchronized (mPackages) {
3917                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3918            }
3919            return PackageManager.SIGNATURE_MATCH;
3920        }
3921        return PackageManager.SIGNATURE_NO_MATCH;
3922    }
3923
3924    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3925        if (isExternal(scannedPkg)) {
3926            return mSettings.isExternalDatabaseVersionOlderThan(
3927                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3928        } else {
3929            return mSettings.isInternalDatabaseVersionOlderThan(
3930                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3931        }
3932    }
3933
3934    private int compareSignaturesRecover(PackageSignatures existingSigs,
3935            PackageParser.Package scannedPkg) {
3936        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3937            return PackageManager.SIGNATURE_NO_MATCH;
3938        }
3939
3940        String msg = null;
3941        try {
3942            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3943                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3944                        + scannedPkg.packageName);
3945                return PackageManager.SIGNATURE_MATCH;
3946            }
3947        } catch (CertificateException e) {
3948            msg = e.getMessage();
3949        }
3950
3951        logCriticalInfo(Log.INFO,
3952                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3953        return PackageManager.SIGNATURE_NO_MATCH;
3954    }
3955
3956    @Override
3957    public String[] getPackagesForUid(int uid) {
3958        uid = UserHandle.getAppId(uid);
3959        // reader
3960        synchronized (mPackages) {
3961            Object obj = mSettings.getUserIdLPr(uid);
3962            if (obj instanceof SharedUserSetting) {
3963                final SharedUserSetting sus = (SharedUserSetting) obj;
3964                final int N = sus.packages.size();
3965                final String[] res = new String[N];
3966                final Iterator<PackageSetting> it = sus.packages.iterator();
3967                int i = 0;
3968                while (it.hasNext()) {
3969                    res[i++] = it.next().name;
3970                }
3971                return res;
3972            } else if (obj instanceof PackageSetting) {
3973                final PackageSetting ps = (PackageSetting) obj;
3974                return new String[] { ps.name };
3975            }
3976        }
3977        return null;
3978    }
3979
3980    @Override
3981    public String getNameForUid(int uid) {
3982        // reader
3983        synchronized (mPackages) {
3984            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3985            if (obj instanceof SharedUserSetting) {
3986                final SharedUserSetting sus = (SharedUserSetting) obj;
3987                return sus.name + ":" + sus.userId;
3988            } else if (obj instanceof PackageSetting) {
3989                final PackageSetting ps = (PackageSetting) obj;
3990                return ps.name;
3991            }
3992        }
3993        return null;
3994    }
3995
3996    @Override
3997    public int getUidForSharedUser(String sharedUserName) {
3998        if(sharedUserName == null) {
3999            return -1;
4000        }
4001        // reader
4002        synchronized (mPackages) {
4003            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4004            if (suid == null) {
4005                return -1;
4006            }
4007            return suid.userId;
4008        }
4009    }
4010
4011    @Override
4012    public int getFlagsForUid(int uid) {
4013        synchronized (mPackages) {
4014            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4015            if (obj instanceof SharedUserSetting) {
4016                final SharedUserSetting sus = (SharedUserSetting) obj;
4017                return sus.pkgFlags;
4018            } else if (obj instanceof PackageSetting) {
4019                final PackageSetting ps = (PackageSetting) obj;
4020                return ps.pkgFlags;
4021            }
4022        }
4023        return 0;
4024    }
4025
4026    @Override
4027    public int getPrivateFlagsForUid(int uid) {
4028        synchronized (mPackages) {
4029            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4030            if (obj instanceof SharedUserSetting) {
4031                final SharedUserSetting sus = (SharedUserSetting) obj;
4032                return sus.pkgPrivateFlags;
4033            } else if (obj instanceof PackageSetting) {
4034                final PackageSetting ps = (PackageSetting) obj;
4035                return ps.pkgPrivateFlags;
4036            }
4037        }
4038        return 0;
4039    }
4040
4041    @Override
4042    public boolean isUidPrivileged(int uid) {
4043        uid = UserHandle.getAppId(uid);
4044        // reader
4045        synchronized (mPackages) {
4046            Object obj = mSettings.getUserIdLPr(uid);
4047            if (obj instanceof SharedUserSetting) {
4048                final SharedUserSetting sus = (SharedUserSetting) obj;
4049                final Iterator<PackageSetting> it = sus.packages.iterator();
4050                while (it.hasNext()) {
4051                    if (it.next().isPrivileged()) {
4052                        return true;
4053                    }
4054                }
4055            } else if (obj instanceof PackageSetting) {
4056                final PackageSetting ps = (PackageSetting) obj;
4057                return ps.isPrivileged();
4058            }
4059        }
4060        return false;
4061    }
4062
4063    @Override
4064    public String[] getAppOpPermissionPackages(String permissionName) {
4065        synchronized (mPackages) {
4066            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4067            if (pkgs == null) {
4068                return null;
4069            }
4070            return pkgs.toArray(new String[pkgs.size()]);
4071        }
4072    }
4073
4074    @Override
4075    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4076            int flags, int userId) {
4077        if (!sUserManager.exists(userId)) return null;
4078        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4079        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4080        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4081    }
4082
4083    @Override
4084    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4085            IntentFilter filter, int match, ComponentName activity) {
4086        final int userId = UserHandle.getCallingUserId();
4087        if (DEBUG_PREFERRED) {
4088            Log.v(TAG, "setLastChosenActivity intent=" + intent
4089                + " resolvedType=" + resolvedType
4090                + " flags=" + flags
4091                + " filter=" + filter
4092                + " match=" + match
4093                + " activity=" + activity);
4094            filter.dump(new PrintStreamPrinter(System.out), "    ");
4095        }
4096        intent.setComponent(null);
4097        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4098        // Find any earlier preferred or last chosen entries and nuke them
4099        findPreferredActivity(intent, resolvedType,
4100                flags, query, 0, false, true, false, userId);
4101        // Add the new activity as the last chosen for this filter
4102        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4103                "Setting last chosen");
4104    }
4105
4106    @Override
4107    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4108        final int userId = UserHandle.getCallingUserId();
4109        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4110        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4111        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4112                false, false, false, userId);
4113    }
4114
4115    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4116            int flags, List<ResolveInfo> query, int userId) {
4117        if (query != null) {
4118            final int N = query.size();
4119            if (N == 1) {
4120                return query.get(0);
4121            } else if (N > 1) {
4122                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4123                // If there is more than one activity with the same priority,
4124                // then let the user decide between them.
4125                ResolveInfo r0 = query.get(0);
4126                ResolveInfo r1 = query.get(1);
4127                if (DEBUG_INTENT_MATCHING || debug) {
4128                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4129                            + r1.activityInfo.name + "=" + r1.priority);
4130                }
4131                // If the first activity has a higher priority, or a different
4132                // default, then it is always desireable to pick it.
4133                if (r0.priority != r1.priority
4134                        || r0.preferredOrder != r1.preferredOrder
4135                        || r0.isDefault != r1.isDefault) {
4136                    return query.get(0);
4137                }
4138                // If we have saved a preference for a preferred activity for
4139                // this Intent, use that.
4140                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4141                        flags, query, r0.priority, true, false, debug, userId);
4142                if (ri != null) {
4143                    return ri;
4144                }
4145                if (userId != 0) {
4146                    ri = new ResolveInfo(mResolveInfo);
4147                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4148                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4149                            ri.activityInfo.applicationInfo);
4150                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4151                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4152                    return ri;
4153                }
4154                return mResolveInfo;
4155            }
4156        }
4157        return null;
4158    }
4159
4160    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4161            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4162        final int N = query.size();
4163        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4164                .get(userId);
4165        // Get the list of persistent preferred activities that handle the intent
4166        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4167        List<PersistentPreferredActivity> pprefs = ppir != null
4168                ? ppir.queryIntent(intent, resolvedType,
4169                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4170                : null;
4171        if (pprefs != null && pprefs.size() > 0) {
4172            final int M = pprefs.size();
4173            for (int i=0; i<M; i++) {
4174                final PersistentPreferredActivity ppa = pprefs.get(i);
4175                if (DEBUG_PREFERRED || debug) {
4176                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4177                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4178                            + "\n  component=" + ppa.mComponent);
4179                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4180                }
4181                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4182                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4183                if (DEBUG_PREFERRED || debug) {
4184                    Slog.v(TAG, "Found persistent preferred activity:");
4185                    if (ai != null) {
4186                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4187                    } else {
4188                        Slog.v(TAG, "  null");
4189                    }
4190                }
4191                if (ai == null) {
4192                    // This previously registered persistent preferred activity
4193                    // component is no longer known. Ignore it and do NOT remove it.
4194                    continue;
4195                }
4196                for (int j=0; j<N; j++) {
4197                    final ResolveInfo ri = query.get(j);
4198                    if (!ri.activityInfo.applicationInfo.packageName
4199                            .equals(ai.applicationInfo.packageName)) {
4200                        continue;
4201                    }
4202                    if (!ri.activityInfo.name.equals(ai.name)) {
4203                        continue;
4204                    }
4205                    //  Found a persistent preference that can handle the intent.
4206                    if (DEBUG_PREFERRED || debug) {
4207                        Slog.v(TAG, "Returning persistent preferred activity: " +
4208                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4209                    }
4210                    return ri;
4211                }
4212            }
4213        }
4214        return null;
4215    }
4216
4217    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4218            List<ResolveInfo> query, int priority, boolean always,
4219            boolean removeMatches, boolean debug, int userId) {
4220        if (!sUserManager.exists(userId)) return null;
4221        // writer
4222        synchronized (mPackages) {
4223            if (intent.getSelector() != null) {
4224                intent = intent.getSelector();
4225            }
4226            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4227
4228            // Try to find a matching persistent preferred activity.
4229            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4230                    debug, userId);
4231
4232            // If a persistent preferred activity matched, use it.
4233            if (pri != null) {
4234                return pri;
4235            }
4236
4237            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4238            // Get the list of preferred activities that handle the intent
4239            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4240            List<PreferredActivity> prefs = pir != null
4241                    ? pir.queryIntent(intent, resolvedType,
4242                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4243                    : null;
4244            if (prefs != null && prefs.size() > 0) {
4245                boolean changed = false;
4246                try {
4247                    // First figure out how good the original match set is.
4248                    // We will only allow preferred activities that came
4249                    // from the same match quality.
4250                    int match = 0;
4251
4252                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4253
4254                    final int N = query.size();
4255                    for (int j=0; j<N; j++) {
4256                        final ResolveInfo ri = query.get(j);
4257                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4258                                + ": 0x" + Integer.toHexString(match));
4259                        if (ri.match > match) {
4260                            match = ri.match;
4261                        }
4262                    }
4263
4264                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4265                            + Integer.toHexString(match));
4266
4267                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4268                    final int M = prefs.size();
4269                    for (int i=0; i<M; i++) {
4270                        final PreferredActivity pa = prefs.get(i);
4271                        if (DEBUG_PREFERRED || debug) {
4272                            Slog.v(TAG, "Checking PreferredActivity ds="
4273                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4274                                    + "\n  component=" + pa.mPref.mComponent);
4275                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4276                        }
4277                        if (pa.mPref.mMatch != match) {
4278                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4279                                    + Integer.toHexString(pa.mPref.mMatch));
4280                            continue;
4281                        }
4282                        // If it's not an "always" type preferred activity and that's what we're
4283                        // looking for, skip it.
4284                        if (always && !pa.mPref.mAlways) {
4285                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4286                            continue;
4287                        }
4288                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4289                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4290                        if (DEBUG_PREFERRED || debug) {
4291                            Slog.v(TAG, "Found preferred activity:");
4292                            if (ai != null) {
4293                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4294                            } else {
4295                                Slog.v(TAG, "  null");
4296                            }
4297                        }
4298                        if (ai == null) {
4299                            // This previously registered preferred activity
4300                            // component is no longer known.  Most likely an update
4301                            // to the app was installed and in the new version this
4302                            // component no longer exists.  Clean it up by removing
4303                            // it from the preferred activities list, and skip it.
4304                            Slog.w(TAG, "Removing dangling preferred activity: "
4305                                    + pa.mPref.mComponent);
4306                            pir.removeFilter(pa);
4307                            changed = true;
4308                            continue;
4309                        }
4310                        for (int j=0; j<N; j++) {
4311                            final ResolveInfo ri = query.get(j);
4312                            if (!ri.activityInfo.applicationInfo.packageName
4313                                    .equals(ai.applicationInfo.packageName)) {
4314                                continue;
4315                            }
4316                            if (!ri.activityInfo.name.equals(ai.name)) {
4317                                continue;
4318                            }
4319
4320                            if (removeMatches) {
4321                                pir.removeFilter(pa);
4322                                changed = true;
4323                                if (DEBUG_PREFERRED) {
4324                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4325                                }
4326                                break;
4327                            }
4328
4329                            // Okay we found a previously set preferred or last chosen app.
4330                            // If the result set is different from when this
4331                            // was created, we need to clear it and re-ask the
4332                            // user their preference, if we're looking for an "always" type entry.
4333                            if (always && !pa.mPref.sameSet(query)) {
4334                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4335                                        + intent + " type " + resolvedType);
4336                                if (DEBUG_PREFERRED) {
4337                                    Slog.v(TAG, "Removing preferred activity since set changed "
4338                                            + pa.mPref.mComponent);
4339                                }
4340                                pir.removeFilter(pa);
4341                                // Re-add the filter as a "last chosen" entry (!always)
4342                                PreferredActivity lastChosen = new PreferredActivity(
4343                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4344                                pir.addFilter(lastChosen);
4345                                changed = true;
4346                                return null;
4347                            }
4348
4349                            // Yay! Either the set matched or we're looking for the last chosen
4350                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4351                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4352                            return ri;
4353                        }
4354                    }
4355                } finally {
4356                    if (changed) {
4357                        if (DEBUG_PREFERRED) {
4358                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4359                        }
4360                        scheduleWritePackageRestrictionsLocked(userId);
4361                    }
4362                }
4363            }
4364        }
4365        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4366        return null;
4367    }
4368
4369    /*
4370     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4371     */
4372    @Override
4373    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4374            int targetUserId) {
4375        mContext.enforceCallingOrSelfPermission(
4376                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4377        List<CrossProfileIntentFilter> matches =
4378                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4379        if (matches != null) {
4380            int size = matches.size();
4381            for (int i = 0; i < size; i++) {
4382                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4383            }
4384        }
4385        if (hasWebURI(intent)) {
4386            // cross-profile app linking works only towards the parent.
4387            final UserInfo parent = getProfileParent(sourceUserId);
4388            synchronized(mPackages) {
4389                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4390                        parent.id) != null;
4391            }
4392        }
4393        return false;
4394    }
4395
4396    private UserInfo getProfileParent(int userId) {
4397        final long identity = Binder.clearCallingIdentity();
4398        try {
4399            return sUserManager.getProfileParent(userId);
4400        } finally {
4401            Binder.restoreCallingIdentity(identity);
4402        }
4403    }
4404
4405    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4406            String resolvedType, int userId) {
4407        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4408        if (resolver != null) {
4409            return resolver.queryIntent(intent, resolvedType, false, userId);
4410        }
4411        return null;
4412    }
4413
4414    @Override
4415    public List<ResolveInfo> queryIntentActivities(Intent intent,
4416            String resolvedType, int flags, int userId) {
4417        if (!sUserManager.exists(userId)) return Collections.emptyList();
4418        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4419        ComponentName comp = intent.getComponent();
4420        if (comp == null) {
4421            if (intent.getSelector() != null) {
4422                intent = intent.getSelector();
4423                comp = intent.getComponent();
4424            }
4425        }
4426
4427        if (comp != null) {
4428            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4429            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4430            if (ai != null) {
4431                final ResolveInfo ri = new ResolveInfo();
4432                ri.activityInfo = ai;
4433                list.add(ri);
4434            }
4435            return list;
4436        }
4437
4438        // reader
4439        synchronized (mPackages) {
4440            final String pkgName = intent.getPackage();
4441            if (pkgName == null) {
4442                List<CrossProfileIntentFilter> matchingFilters =
4443                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4444                // Check for results that need to skip the current profile.
4445                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4446                        resolvedType, flags, userId);
4447                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4448                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4449                    result.add(xpResolveInfo);
4450                    return filterIfNotPrimaryUser(result, userId);
4451                }
4452
4453                // Check for results in the current profile.
4454                List<ResolveInfo> result = mActivities.queryIntent(
4455                        intent, resolvedType, flags, userId);
4456
4457                // Check for cross profile results.
4458                xpResolveInfo = queryCrossProfileIntents(
4459                        matchingFilters, intent, resolvedType, flags, userId);
4460                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4461                    result.add(xpResolveInfo);
4462                    Collections.sort(result, mResolvePrioritySorter);
4463                }
4464                result = filterIfNotPrimaryUser(result, userId);
4465                if (hasWebURI(intent)) {
4466                    CrossProfileDomainInfo xpDomainInfo = null;
4467                    final UserInfo parent = getProfileParent(userId);
4468                    if (parent != null) {
4469                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4470                                flags, userId, parent.id);
4471                    }
4472                    if (xpDomainInfo != null) {
4473                        if (xpResolveInfo != null) {
4474                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4475                            // in the result.
4476                            result.remove(xpResolveInfo);
4477                        }
4478                        if (result.size() == 0) {
4479                            result.add(xpDomainInfo.resolveInfo);
4480                            return result;
4481                        }
4482                    } else if (result.size() <= 1) {
4483                        return result;
4484                    }
4485                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4486                            xpDomainInfo);
4487                    Collections.sort(result, mResolvePrioritySorter);
4488                }
4489                return result;
4490            }
4491            final PackageParser.Package pkg = mPackages.get(pkgName);
4492            if (pkg != null) {
4493                return filterIfNotPrimaryUser(
4494                        mActivities.queryIntentForPackage(
4495                                intent, resolvedType, flags, pkg.activities, userId),
4496                        userId);
4497            }
4498            return new ArrayList<ResolveInfo>();
4499        }
4500    }
4501
4502    private static class CrossProfileDomainInfo {
4503        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4504        ResolveInfo resolveInfo;
4505        /* Best domain verification status of the activities found in the other profile */
4506        int bestDomainVerificationStatus;
4507    }
4508
4509    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4510            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4511        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4512                sourceUserId)) {
4513            return null;
4514        }
4515        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4516                resolvedType, flags, parentUserId);
4517
4518        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4519            return null;
4520        }
4521        CrossProfileDomainInfo result = null;
4522        int size = resultTargetUser.size();
4523        for (int i = 0; i < size; i++) {
4524            ResolveInfo riTargetUser = resultTargetUser.get(i);
4525            // Intent filter verification is only for filters that specify a host. So don't return
4526            // those that handle all web uris.
4527            if (riTargetUser.handleAllWebDataURI) {
4528                continue;
4529            }
4530            String packageName = riTargetUser.activityInfo.packageName;
4531            PackageSetting ps = mSettings.mPackages.get(packageName);
4532            if (ps == null) {
4533                continue;
4534            }
4535            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4536            if (result == null) {
4537                result = new CrossProfileDomainInfo();
4538                result.resolveInfo =
4539                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4540                result.bestDomainVerificationStatus = status;
4541            } else {
4542                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4543                        result.bestDomainVerificationStatus);
4544            }
4545        }
4546        return result;
4547    }
4548
4549    /**
4550     * Verification statuses are ordered from the worse to the best, except for
4551     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4552     */
4553    private int bestDomainVerificationStatus(int status1, int status2) {
4554        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4555            return status2;
4556        }
4557        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4558            return status1;
4559        }
4560        return (int) MathUtils.max(status1, status2);
4561    }
4562
4563    private boolean isUserEnabled(int userId) {
4564        long callingId = Binder.clearCallingIdentity();
4565        try {
4566            UserInfo userInfo = sUserManager.getUserInfo(userId);
4567            return userInfo != null && userInfo.isEnabled();
4568        } finally {
4569            Binder.restoreCallingIdentity(callingId);
4570        }
4571    }
4572
4573    /**
4574     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4575     *
4576     * @return filtered list
4577     */
4578    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4579        if (userId == UserHandle.USER_OWNER) {
4580            return resolveInfos;
4581        }
4582        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4583            ResolveInfo info = resolveInfos.get(i);
4584            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4585                resolveInfos.remove(i);
4586            }
4587        }
4588        return resolveInfos;
4589    }
4590
4591    private static boolean hasWebURI(Intent intent) {
4592        if (intent.getData() == null) {
4593            return false;
4594        }
4595        final String scheme = intent.getScheme();
4596        if (TextUtils.isEmpty(scheme)) {
4597            return false;
4598        }
4599        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4600    }
4601
4602    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4603            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4604        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4605            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4606                    candidates.size());
4607        }
4608
4609        final int userId = UserHandle.getCallingUserId();
4610        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4611        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4612        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4613        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4614        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4615
4616        synchronized (mPackages) {
4617            final int count = candidates.size();
4618            // First, try to use linked apps. Partition the candidates into four lists:
4619            // one for the final results, one for the "do not use ever", one for "undefined status"
4620            // and finally one for "browser app type".
4621            for (int n=0; n<count; n++) {
4622                ResolveInfo info = candidates.get(n);
4623                String packageName = info.activityInfo.packageName;
4624                PackageSetting ps = mSettings.mPackages.get(packageName);
4625                if (ps != null) {
4626                    // Add to the special match all list (Browser use case)
4627                    if (info.handleAllWebDataURI) {
4628                        matchAllList.add(info);
4629                        continue;
4630                    }
4631                    // Try to get the status from User settings first
4632                    int status = getDomainVerificationStatusLPr(ps, userId);
4633                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4634                        if (DEBUG_DOMAIN_VERIFICATION) {
4635                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4636                        }
4637                        alwaysList.add(info);
4638                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4639                        if (DEBUG_DOMAIN_VERIFICATION) {
4640                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4641                        }
4642                        neverList.add(info);
4643                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4644                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4645                        if (DEBUG_DOMAIN_VERIFICATION) {
4646                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4647                        }
4648                        undefinedList.add(info);
4649                    }
4650                }
4651            }
4652            // First try to add the "always" resolution for the current user if there is any
4653            if (alwaysList.size() > 0) {
4654                result.addAll(alwaysList);
4655            // if there is an "always" for the parent user, add it.
4656            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4657                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4658                result.add(xpDomainInfo.resolveInfo);
4659            } else {
4660                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4661                result.addAll(undefinedList);
4662                if (xpDomainInfo != null && (
4663                        xpDomainInfo.bestDomainVerificationStatus
4664                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4665                        || xpDomainInfo.bestDomainVerificationStatus
4666                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4667                    result.add(xpDomainInfo.resolveInfo);
4668                }
4669                // Also add Browsers (all of them or only the default one)
4670                if ((flags & MATCH_ALL) != 0) {
4671                    result.addAll(matchAllList);
4672                } else {
4673                    // Try to add the Default Browser if we can
4674                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4675                            UserHandle.myUserId());
4676                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4677                        boolean defaultBrowserFound = false;
4678                        final int browserCount = matchAllList.size();
4679                        for (int n=0; n<browserCount; n++) {
4680                            ResolveInfo browser = matchAllList.get(n);
4681                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4682                                result.add(browser);
4683                                defaultBrowserFound = true;
4684                                break;
4685                            }
4686                        }
4687                        if (!defaultBrowserFound) {
4688                            result.addAll(matchAllList);
4689                        }
4690                    } else {
4691                        result.addAll(matchAllList);
4692                    }
4693                }
4694
4695                // If there is nothing selected, add all candidates and remove the ones that the user
4696                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4697                if (result.size() == 0) {
4698                    result.addAll(candidates);
4699                    result.removeAll(neverList);
4700                }
4701            }
4702        }
4703        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4704            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4705                    result.size());
4706            for (ResolveInfo info : result) {
4707                Slog.v(TAG, "  + " + info.activityInfo);
4708            }
4709        }
4710        return result;
4711    }
4712
4713    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4714        int status = ps.getDomainVerificationStatusForUser(userId);
4715        // if none available, get the master status
4716        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4717            if (ps.getIntentFilterVerificationInfo() != null) {
4718                status = ps.getIntentFilterVerificationInfo().getStatus();
4719            }
4720        }
4721        return status;
4722    }
4723
4724    private ResolveInfo querySkipCurrentProfileIntents(
4725            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4726            int flags, int sourceUserId) {
4727        if (matchingFilters != null) {
4728            int size = matchingFilters.size();
4729            for (int i = 0; i < size; i ++) {
4730                CrossProfileIntentFilter filter = matchingFilters.get(i);
4731                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4732                    // Checking if there are activities in the target user that can handle the
4733                    // intent.
4734                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4735                            flags, sourceUserId);
4736                    if (resolveInfo != null) {
4737                        return resolveInfo;
4738                    }
4739                }
4740            }
4741        }
4742        return null;
4743    }
4744
4745    // Return matching ResolveInfo if any for skip current profile intent filters.
4746    private ResolveInfo queryCrossProfileIntents(
4747            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4748            int flags, int sourceUserId) {
4749        if (matchingFilters != null) {
4750            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4751            // match the same intent. For performance reasons, it is better not to
4752            // run queryIntent twice for the same userId
4753            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4754            int size = matchingFilters.size();
4755            for (int i = 0; i < size; i++) {
4756                CrossProfileIntentFilter filter = matchingFilters.get(i);
4757                int targetUserId = filter.getTargetUserId();
4758                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4759                        && !alreadyTriedUserIds.get(targetUserId)) {
4760                    // Checking if there are activities in the target user that can handle the
4761                    // intent.
4762                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4763                            flags, sourceUserId);
4764                    if (resolveInfo != null) return resolveInfo;
4765                    alreadyTriedUserIds.put(targetUserId, true);
4766                }
4767            }
4768        }
4769        return null;
4770    }
4771
4772    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4773            String resolvedType, int flags, int sourceUserId) {
4774        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4775                resolvedType, flags, filter.getTargetUserId());
4776        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4777            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4778        }
4779        return null;
4780    }
4781
4782    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4783            int sourceUserId, int targetUserId) {
4784        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4785        String className;
4786        if (targetUserId == UserHandle.USER_OWNER) {
4787            className = FORWARD_INTENT_TO_USER_OWNER;
4788        } else {
4789            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4790        }
4791        ComponentName forwardingActivityComponentName = new ComponentName(
4792                mAndroidApplication.packageName, className);
4793        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4794                sourceUserId);
4795        if (targetUserId == UserHandle.USER_OWNER) {
4796            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4797            forwardingResolveInfo.noResourceId = true;
4798        }
4799        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4800        forwardingResolveInfo.priority = 0;
4801        forwardingResolveInfo.preferredOrder = 0;
4802        forwardingResolveInfo.match = 0;
4803        forwardingResolveInfo.isDefault = true;
4804        forwardingResolveInfo.filter = filter;
4805        forwardingResolveInfo.targetUserId = targetUserId;
4806        return forwardingResolveInfo;
4807    }
4808
4809    @Override
4810    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4811            Intent[] specifics, String[] specificTypes, Intent intent,
4812            String resolvedType, int flags, int userId) {
4813        if (!sUserManager.exists(userId)) return Collections.emptyList();
4814        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4815                false, "query intent activity options");
4816        final String resultsAction = intent.getAction();
4817
4818        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4819                | PackageManager.GET_RESOLVED_FILTER, userId);
4820
4821        if (DEBUG_INTENT_MATCHING) {
4822            Log.v(TAG, "Query " + intent + ": " + results);
4823        }
4824
4825        int specificsPos = 0;
4826        int N;
4827
4828        // todo: note that the algorithm used here is O(N^2).  This
4829        // isn't a problem in our current environment, but if we start running
4830        // into situations where we have more than 5 or 10 matches then this
4831        // should probably be changed to something smarter...
4832
4833        // First we go through and resolve each of the specific items
4834        // that were supplied, taking care of removing any corresponding
4835        // duplicate items in the generic resolve list.
4836        if (specifics != null) {
4837            for (int i=0; i<specifics.length; i++) {
4838                final Intent sintent = specifics[i];
4839                if (sintent == null) {
4840                    continue;
4841                }
4842
4843                if (DEBUG_INTENT_MATCHING) {
4844                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4845                }
4846
4847                String action = sintent.getAction();
4848                if (resultsAction != null && resultsAction.equals(action)) {
4849                    // If this action was explicitly requested, then don't
4850                    // remove things that have it.
4851                    action = null;
4852                }
4853
4854                ResolveInfo ri = null;
4855                ActivityInfo ai = null;
4856
4857                ComponentName comp = sintent.getComponent();
4858                if (comp == null) {
4859                    ri = resolveIntent(
4860                        sintent,
4861                        specificTypes != null ? specificTypes[i] : null,
4862                            flags, userId);
4863                    if (ri == null) {
4864                        continue;
4865                    }
4866                    if (ri == mResolveInfo) {
4867                        // ACK!  Must do something better with this.
4868                    }
4869                    ai = ri.activityInfo;
4870                    comp = new ComponentName(ai.applicationInfo.packageName,
4871                            ai.name);
4872                } else {
4873                    ai = getActivityInfo(comp, flags, userId);
4874                    if (ai == null) {
4875                        continue;
4876                    }
4877                }
4878
4879                // Look for any generic query activities that are duplicates
4880                // of this specific one, and remove them from the results.
4881                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4882                N = results.size();
4883                int j;
4884                for (j=specificsPos; j<N; j++) {
4885                    ResolveInfo sri = results.get(j);
4886                    if ((sri.activityInfo.name.equals(comp.getClassName())
4887                            && sri.activityInfo.applicationInfo.packageName.equals(
4888                                    comp.getPackageName()))
4889                        || (action != null && sri.filter.matchAction(action))) {
4890                        results.remove(j);
4891                        if (DEBUG_INTENT_MATCHING) Log.v(
4892                            TAG, "Removing duplicate item from " + j
4893                            + " due to specific " + specificsPos);
4894                        if (ri == null) {
4895                            ri = sri;
4896                        }
4897                        j--;
4898                        N--;
4899                    }
4900                }
4901
4902                // Add this specific item to its proper place.
4903                if (ri == null) {
4904                    ri = new ResolveInfo();
4905                    ri.activityInfo = ai;
4906                }
4907                results.add(specificsPos, ri);
4908                ri.specificIndex = i;
4909                specificsPos++;
4910            }
4911        }
4912
4913        // Now we go through the remaining generic results and remove any
4914        // duplicate actions that are found here.
4915        N = results.size();
4916        for (int i=specificsPos; i<N-1; i++) {
4917            final ResolveInfo rii = results.get(i);
4918            if (rii.filter == null) {
4919                continue;
4920            }
4921
4922            // Iterate over all of the actions of this result's intent
4923            // filter...  typically this should be just one.
4924            final Iterator<String> it = rii.filter.actionsIterator();
4925            if (it == null) {
4926                continue;
4927            }
4928            while (it.hasNext()) {
4929                final String action = it.next();
4930                if (resultsAction != null && resultsAction.equals(action)) {
4931                    // If this action was explicitly requested, then don't
4932                    // remove things that have it.
4933                    continue;
4934                }
4935                for (int j=i+1; j<N; j++) {
4936                    final ResolveInfo rij = results.get(j);
4937                    if (rij.filter != null && rij.filter.hasAction(action)) {
4938                        results.remove(j);
4939                        if (DEBUG_INTENT_MATCHING) Log.v(
4940                            TAG, "Removing duplicate item from " + j
4941                            + " due to action " + action + " at " + i);
4942                        j--;
4943                        N--;
4944                    }
4945                }
4946            }
4947
4948            // If the caller didn't request filter information, drop it now
4949            // so we don't have to marshall/unmarshall it.
4950            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4951                rii.filter = null;
4952            }
4953        }
4954
4955        // Filter out the caller activity if so requested.
4956        if (caller != null) {
4957            N = results.size();
4958            for (int i=0; i<N; i++) {
4959                ActivityInfo ainfo = results.get(i).activityInfo;
4960                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4961                        && caller.getClassName().equals(ainfo.name)) {
4962                    results.remove(i);
4963                    break;
4964                }
4965            }
4966        }
4967
4968        // If the caller didn't request filter information,
4969        // drop them now so we don't have to
4970        // marshall/unmarshall it.
4971        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4972            N = results.size();
4973            for (int i=0; i<N; i++) {
4974                results.get(i).filter = null;
4975            }
4976        }
4977
4978        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4979        return results;
4980    }
4981
4982    @Override
4983    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4984            int userId) {
4985        if (!sUserManager.exists(userId)) return Collections.emptyList();
4986        ComponentName comp = intent.getComponent();
4987        if (comp == null) {
4988            if (intent.getSelector() != null) {
4989                intent = intent.getSelector();
4990                comp = intent.getComponent();
4991            }
4992        }
4993        if (comp != null) {
4994            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4995            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4996            if (ai != null) {
4997                ResolveInfo ri = new ResolveInfo();
4998                ri.activityInfo = ai;
4999                list.add(ri);
5000            }
5001            return list;
5002        }
5003
5004        // reader
5005        synchronized (mPackages) {
5006            String pkgName = intent.getPackage();
5007            if (pkgName == null) {
5008                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5009            }
5010            final PackageParser.Package pkg = mPackages.get(pkgName);
5011            if (pkg != null) {
5012                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5013                        userId);
5014            }
5015            return null;
5016        }
5017    }
5018
5019    @Override
5020    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5021        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5022        if (!sUserManager.exists(userId)) return null;
5023        if (query != null) {
5024            if (query.size() >= 1) {
5025                // If there is more than one service with the same priority,
5026                // just arbitrarily pick the first one.
5027                return query.get(0);
5028            }
5029        }
5030        return null;
5031    }
5032
5033    @Override
5034    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5035            int userId) {
5036        if (!sUserManager.exists(userId)) return Collections.emptyList();
5037        ComponentName comp = intent.getComponent();
5038        if (comp == null) {
5039            if (intent.getSelector() != null) {
5040                intent = intent.getSelector();
5041                comp = intent.getComponent();
5042            }
5043        }
5044        if (comp != null) {
5045            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5046            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5047            if (si != null) {
5048                final ResolveInfo ri = new ResolveInfo();
5049                ri.serviceInfo = si;
5050                list.add(ri);
5051            }
5052            return list;
5053        }
5054
5055        // reader
5056        synchronized (mPackages) {
5057            String pkgName = intent.getPackage();
5058            if (pkgName == null) {
5059                return mServices.queryIntent(intent, resolvedType, flags, userId);
5060            }
5061            final PackageParser.Package pkg = mPackages.get(pkgName);
5062            if (pkg != null) {
5063                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5064                        userId);
5065            }
5066            return null;
5067        }
5068    }
5069
5070    @Override
5071    public List<ResolveInfo> queryIntentContentProviders(
5072            Intent intent, String resolvedType, int flags, int userId) {
5073        if (!sUserManager.exists(userId)) return Collections.emptyList();
5074        ComponentName comp = intent.getComponent();
5075        if (comp == null) {
5076            if (intent.getSelector() != null) {
5077                intent = intent.getSelector();
5078                comp = intent.getComponent();
5079            }
5080        }
5081        if (comp != null) {
5082            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5083            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5084            if (pi != null) {
5085                final ResolveInfo ri = new ResolveInfo();
5086                ri.providerInfo = pi;
5087                list.add(ri);
5088            }
5089            return list;
5090        }
5091
5092        // reader
5093        synchronized (mPackages) {
5094            String pkgName = intent.getPackage();
5095            if (pkgName == null) {
5096                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5097            }
5098            final PackageParser.Package pkg = mPackages.get(pkgName);
5099            if (pkg != null) {
5100                return mProviders.queryIntentForPackage(
5101                        intent, resolvedType, flags, pkg.providers, userId);
5102            }
5103            return null;
5104        }
5105    }
5106
5107    @Override
5108    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5109        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5110
5111        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5112
5113        // writer
5114        synchronized (mPackages) {
5115            ArrayList<PackageInfo> list;
5116            if (listUninstalled) {
5117                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5118                for (PackageSetting ps : mSettings.mPackages.values()) {
5119                    PackageInfo pi;
5120                    if (ps.pkg != null) {
5121                        pi = generatePackageInfo(ps.pkg, flags, userId);
5122                    } else {
5123                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5124                    }
5125                    if (pi != null) {
5126                        list.add(pi);
5127                    }
5128                }
5129            } else {
5130                list = new ArrayList<PackageInfo>(mPackages.size());
5131                for (PackageParser.Package p : mPackages.values()) {
5132                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5133                    if (pi != null) {
5134                        list.add(pi);
5135                    }
5136                }
5137            }
5138
5139            return new ParceledListSlice<PackageInfo>(list);
5140        }
5141    }
5142
5143    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5144            String[] permissions, boolean[] tmp, int flags, int userId) {
5145        int numMatch = 0;
5146        final PermissionsState permissionsState = ps.getPermissionsState();
5147        for (int i=0; i<permissions.length; i++) {
5148            final String permission = permissions[i];
5149            if (permissionsState.hasPermission(permission, userId)) {
5150                tmp[i] = true;
5151                numMatch++;
5152            } else {
5153                tmp[i] = false;
5154            }
5155        }
5156        if (numMatch == 0) {
5157            return;
5158        }
5159        PackageInfo pi;
5160        if (ps.pkg != null) {
5161            pi = generatePackageInfo(ps.pkg, flags, userId);
5162        } else {
5163            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5164        }
5165        // The above might return null in cases of uninstalled apps or install-state
5166        // skew across users/profiles.
5167        if (pi != null) {
5168            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5169                if (numMatch == permissions.length) {
5170                    pi.requestedPermissions = permissions;
5171                } else {
5172                    pi.requestedPermissions = new String[numMatch];
5173                    numMatch = 0;
5174                    for (int i=0; i<permissions.length; i++) {
5175                        if (tmp[i]) {
5176                            pi.requestedPermissions[numMatch] = permissions[i];
5177                            numMatch++;
5178                        }
5179                    }
5180                }
5181            }
5182            list.add(pi);
5183        }
5184    }
5185
5186    @Override
5187    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5188            String[] permissions, int flags, int userId) {
5189        if (!sUserManager.exists(userId)) return null;
5190        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5191
5192        // writer
5193        synchronized (mPackages) {
5194            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5195            boolean[] tmpBools = new boolean[permissions.length];
5196            if (listUninstalled) {
5197                for (PackageSetting ps : mSettings.mPackages.values()) {
5198                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5199                }
5200            } else {
5201                for (PackageParser.Package pkg : mPackages.values()) {
5202                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5203                    if (ps != null) {
5204                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5205                                userId);
5206                    }
5207                }
5208            }
5209
5210            return new ParceledListSlice<PackageInfo>(list);
5211        }
5212    }
5213
5214    @Override
5215    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5216        if (!sUserManager.exists(userId)) return null;
5217        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5218
5219        // writer
5220        synchronized (mPackages) {
5221            ArrayList<ApplicationInfo> list;
5222            if (listUninstalled) {
5223                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5224                for (PackageSetting ps : mSettings.mPackages.values()) {
5225                    ApplicationInfo ai;
5226                    if (ps.pkg != null) {
5227                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5228                                ps.readUserState(userId), userId);
5229                    } else {
5230                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5231                    }
5232                    if (ai != null) {
5233                        list.add(ai);
5234                    }
5235                }
5236            } else {
5237                list = new ArrayList<ApplicationInfo>(mPackages.size());
5238                for (PackageParser.Package p : mPackages.values()) {
5239                    if (p.mExtras != null) {
5240                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5241                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5242                        if (ai != null) {
5243                            list.add(ai);
5244                        }
5245                    }
5246                }
5247            }
5248
5249            return new ParceledListSlice<ApplicationInfo>(list);
5250        }
5251    }
5252
5253    public List<ApplicationInfo> getPersistentApplications(int flags) {
5254        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5255
5256        // reader
5257        synchronized (mPackages) {
5258            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5259            final int userId = UserHandle.getCallingUserId();
5260            while (i.hasNext()) {
5261                final PackageParser.Package p = i.next();
5262                if (p.applicationInfo != null
5263                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5264                        && (!mSafeMode || isSystemApp(p))) {
5265                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5266                    if (ps != null) {
5267                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5268                                ps.readUserState(userId), userId);
5269                        if (ai != null) {
5270                            finalList.add(ai);
5271                        }
5272                    }
5273                }
5274            }
5275        }
5276
5277        return finalList;
5278    }
5279
5280    @Override
5281    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5282        if (!sUserManager.exists(userId)) return null;
5283        // reader
5284        synchronized (mPackages) {
5285            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5286            PackageSetting ps = provider != null
5287                    ? mSettings.mPackages.get(provider.owner.packageName)
5288                    : null;
5289            return ps != null
5290                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5291                    && (!mSafeMode || (provider.info.applicationInfo.flags
5292                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5293                    ? PackageParser.generateProviderInfo(provider, flags,
5294                            ps.readUserState(userId), userId)
5295                    : null;
5296        }
5297    }
5298
5299    /**
5300     * @deprecated
5301     */
5302    @Deprecated
5303    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5304        // reader
5305        synchronized (mPackages) {
5306            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5307                    .entrySet().iterator();
5308            final int userId = UserHandle.getCallingUserId();
5309            while (i.hasNext()) {
5310                Map.Entry<String, PackageParser.Provider> entry = i.next();
5311                PackageParser.Provider p = entry.getValue();
5312                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5313
5314                if (ps != null && p.syncable
5315                        && (!mSafeMode || (p.info.applicationInfo.flags
5316                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5317                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5318                            ps.readUserState(userId), userId);
5319                    if (info != null) {
5320                        outNames.add(entry.getKey());
5321                        outInfo.add(info);
5322                    }
5323                }
5324            }
5325        }
5326    }
5327
5328    @Override
5329    public List<ProviderInfo> queryContentProviders(String processName,
5330            int uid, int flags) {
5331        ArrayList<ProviderInfo> finalList = null;
5332        // reader
5333        synchronized (mPackages) {
5334            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5335            final int userId = processName != null ?
5336                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5337            while (i.hasNext()) {
5338                final PackageParser.Provider p = i.next();
5339                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5340                if (ps != null && p.info.authority != null
5341                        && (processName == null
5342                                || (p.info.processName.equals(processName)
5343                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5344                        && mSettings.isEnabledLPr(p.info, flags, userId)
5345                        && (!mSafeMode
5346                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5347                    if (finalList == null) {
5348                        finalList = new ArrayList<ProviderInfo>(3);
5349                    }
5350                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5351                            ps.readUserState(userId), userId);
5352                    if (info != null) {
5353                        finalList.add(info);
5354                    }
5355                }
5356            }
5357        }
5358
5359        if (finalList != null) {
5360            Collections.sort(finalList, mProviderInitOrderSorter);
5361        }
5362
5363        return finalList;
5364    }
5365
5366    @Override
5367    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5368            int flags) {
5369        // reader
5370        synchronized (mPackages) {
5371            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5372            return PackageParser.generateInstrumentationInfo(i, flags);
5373        }
5374    }
5375
5376    @Override
5377    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5378            int flags) {
5379        ArrayList<InstrumentationInfo> finalList =
5380            new ArrayList<InstrumentationInfo>();
5381
5382        // reader
5383        synchronized (mPackages) {
5384            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5385            while (i.hasNext()) {
5386                final PackageParser.Instrumentation p = i.next();
5387                if (targetPackage == null
5388                        || targetPackage.equals(p.info.targetPackage)) {
5389                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5390                            flags);
5391                    if (ii != null) {
5392                        finalList.add(ii);
5393                    }
5394                }
5395            }
5396        }
5397
5398        return finalList;
5399    }
5400
5401    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5402        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5403        if (overlays == null) {
5404            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5405            return;
5406        }
5407        for (PackageParser.Package opkg : overlays.values()) {
5408            // Not much to do if idmap fails: we already logged the error
5409            // and we certainly don't want to abort installation of pkg simply
5410            // because an overlay didn't fit properly. For these reasons,
5411            // ignore the return value of createIdmapForPackagePairLI.
5412            createIdmapForPackagePairLI(pkg, opkg);
5413        }
5414    }
5415
5416    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5417            PackageParser.Package opkg) {
5418        if (!opkg.mTrustedOverlay) {
5419            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5420                    opkg.baseCodePath + ": overlay not trusted");
5421            return false;
5422        }
5423        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5424        if (overlaySet == null) {
5425            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5426                    opkg.baseCodePath + " but target package has no known overlays");
5427            return false;
5428        }
5429        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5430        // TODO: generate idmap for split APKs
5431        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5432            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5433                    + opkg.baseCodePath);
5434            return false;
5435        }
5436        PackageParser.Package[] overlayArray =
5437            overlaySet.values().toArray(new PackageParser.Package[0]);
5438        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5439            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5440                return p1.mOverlayPriority - p2.mOverlayPriority;
5441            }
5442        };
5443        Arrays.sort(overlayArray, cmp);
5444
5445        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5446        int i = 0;
5447        for (PackageParser.Package p : overlayArray) {
5448            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5449        }
5450        return true;
5451    }
5452
5453    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5454        final File[] files = dir.listFiles();
5455        if (ArrayUtils.isEmpty(files)) {
5456            Log.d(TAG, "No files in app dir " + dir);
5457            return;
5458        }
5459
5460        if (DEBUG_PACKAGE_SCANNING) {
5461            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5462                    + " flags=0x" + Integer.toHexString(parseFlags));
5463        }
5464
5465        for (File file : files) {
5466            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5467                    && !PackageInstallerService.isStageName(file.getName());
5468            if (!isPackage) {
5469                // Ignore entries which are not packages
5470                continue;
5471            }
5472            try {
5473                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5474                        scanFlags, currentTime, null);
5475            } catch (PackageManagerException e) {
5476                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5477
5478                // Delete invalid userdata apps
5479                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5480                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5481                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5482                    if (file.isDirectory()) {
5483                        mInstaller.rmPackageDir(file.getAbsolutePath());
5484                    } else {
5485                        file.delete();
5486                    }
5487                }
5488            }
5489        }
5490    }
5491
5492    private static File getSettingsProblemFile() {
5493        File dataDir = Environment.getDataDirectory();
5494        File systemDir = new File(dataDir, "system");
5495        File fname = new File(systemDir, "uiderrors.txt");
5496        return fname;
5497    }
5498
5499    static void reportSettingsProblem(int priority, String msg) {
5500        logCriticalInfo(priority, msg);
5501    }
5502
5503    static void logCriticalInfo(int priority, String msg) {
5504        Slog.println(priority, TAG, msg);
5505        EventLogTags.writePmCriticalInfo(msg);
5506        try {
5507            File fname = getSettingsProblemFile();
5508            FileOutputStream out = new FileOutputStream(fname, true);
5509            PrintWriter pw = new FastPrintWriter(out);
5510            SimpleDateFormat formatter = new SimpleDateFormat();
5511            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5512            pw.println(dateString + ": " + msg);
5513            pw.close();
5514            FileUtils.setPermissions(
5515                    fname.toString(),
5516                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5517                    -1, -1);
5518        } catch (java.io.IOException e) {
5519        }
5520    }
5521
5522    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5523            PackageParser.Package pkg, File srcFile, int parseFlags)
5524            throws PackageManagerException {
5525        if (ps != null
5526                && ps.codePath.equals(srcFile)
5527                && ps.timeStamp == srcFile.lastModified()
5528                && !isCompatSignatureUpdateNeeded(pkg)
5529                && !isRecoverSignatureUpdateNeeded(pkg)) {
5530            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5531            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5532            ArraySet<PublicKey> signingKs;
5533            synchronized (mPackages) {
5534                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5535            }
5536            if (ps.signatures.mSignatures != null
5537                    && ps.signatures.mSignatures.length != 0
5538                    && signingKs != null) {
5539                // Optimization: reuse the existing cached certificates
5540                // if the package appears to be unchanged.
5541                pkg.mSignatures = ps.signatures.mSignatures;
5542                pkg.mSigningKeys = signingKs;
5543                return;
5544            }
5545
5546            Slog.w(TAG, "PackageSetting for " + ps.name
5547                    + " is missing signatures.  Collecting certs again to recover them.");
5548        } else {
5549            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5550        }
5551
5552        try {
5553            pp.collectCertificates(pkg, parseFlags);
5554            pp.collectManifestDigest(pkg);
5555        } catch (PackageParserException e) {
5556            throw PackageManagerException.from(e);
5557        }
5558    }
5559
5560    /*
5561     *  Scan a package and return the newly parsed package.
5562     *  Returns null in case of errors and the error code is stored in mLastScanError
5563     */
5564    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5565            long currentTime, UserHandle user) throws PackageManagerException {
5566        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5567        parseFlags |= mDefParseFlags;
5568        PackageParser pp = new PackageParser();
5569        pp.setSeparateProcesses(mSeparateProcesses);
5570        pp.setOnlyCoreApps(mOnlyCore);
5571        pp.setDisplayMetrics(mMetrics);
5572
5573        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5574            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5575        }
5576
5577        final PackageParser.Package pkg;
5578        try {
5579            pkg = pp.parsePackage(scanFile, parseFlags);
5580        } catch (PackageParserException e) {
5581            throw PackageManagerException.from(e);
5582        }
5583
5584        PackageSetting ps = null;
5585        PackageSetting updatedPkg;
5586        // reader
5587        synchronized (mPackages) {
5588            // Look to see if we already know about this package.
5589            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5590            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5591                // This package has been renamed to its original name.  Let's
5592                // use that.
5593                ps = mSettings.peekPackageLPr(oldName);
5594            }
5595            // If there was no original package, see one for the real package name.
5596            if (ps == null) {
5597                ps = mSettings.peekPackageLPr(pkg.packageName);
5598            }
5599            // Check to see if this package could be hiding/updating a system
5600            // package.  Must look for it either under the original or real
5601            // package name depending on our state.
5602            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5603            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5604        }
5605        boolean updatedPkgBetter = false;
5606        // First check if this is a system package that may involve an update
5607        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5608            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5609            // it needs to drop FLAG_PRIVILEGED.
5610            if (locationIsPrivileged(scanFile)) {
5611                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5612            } else {
5613                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5614            }
5615
5616            if (ps != null && !ps.codePath.equals(scanFile)) {
5617                // The path has changed from what was last scanned...  check the
5618                // version of the new path against what we have stored to determine
5619                // what to do.
5620                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5621                if (pkg.mVersionCode <= ps.versionCode) {
5622                    // The system package has been updated and the code path does not match
5623                    // Ignore entry. Skip it.
5624                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5625                            + " ignored: updated version " + ps.versionCode
5626                            + " better than this " + pkg.mVersionCode);
5627                    if (!updatedPkg.codePath.equals(scanFile)) {
5628                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5629                                + ps.name + " changing from " + updatedPkg.codePathString
5630                                + " to " + scanFile);
5631                        updatedPkg.codePath = scanFile;
5632                        updatedPkg.codePathString = scanFile.toString();
5633                        updatedPkg.resourcePath = scanFile;
5634                        updatedPkg.resourcePathString = scanFile.toString();
5635                    }
5636                    updatedPkg.pkg = pkg;
5637                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5638                } else {
5639                    // The current app on the system partition is better than
5640                    // what we have updated to on the data partition; switch
5641                    // back to the system partition version.
5642                    // At this point, its safely assumed that package installation for
5643                    // apps in system partition will go through. If not there won't be a working
5644                    // version of the app
5645                    // writer
5646                    synchronized (mPackages) {
5647                        // Just remove the loaded entries from package lists.
5648                        mPackages.remove(ps.name);
5649                    }
5650
5651                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5652                            + " reverting from " + ps.codePathString
5653                            + ": new version " + pkg.mVersionCode
5654                            + " better than installed " + ps.versionCode);
5655
5656                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5657                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5658                    synchronized (mInstallLock) {
5659                        args.cleanUpResourcesLI();
5660                    }
5661                    synchronized (mPackages) {
5662                        mSettings.enableSystemPackageLPw(ps.name);
5663                    }
5664                    updatedPkgBetter = true;
5665                }
5666            }
5667        }
5668
5669        if (updatedPkg != null) {
5670            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5671            // initially
5672            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5673
5674            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5675            // flag set initially
5676            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5677                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5678            }
5679        }
5680
5681        // Verify certificates against what was last scanned
5682        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5683
5684        /*
5685         * A new system app appeared, but we already had a non-system one of the
5686         * same name installed earlier.
5687         */
5688        boolean shouldHideSystemApp = false;
5689        if (updatedPkg == null && ps != null
5690                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5691            /*
5692             * Check to make sure the signatures match first. If they don't,
5693             * wipe the installed application and its data.
5694             */
5695            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5696                    != PackageManager.SIGNATURE_MATCH) {
5697                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5698                        + " signatures don't match existing userdata copy; removing");
5699                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5700                ps = null;
5701            } else {
5702                /*
5703                 * If the newly-added system app is an older version than the
5704                 * already installed version, hide it. It will be scanned later
5705                 * and re-added like an update.
5706                 */
5707                if (pkg.mVersionCode <= ps.versionCode) {
5708                    shouldHideSystemApp = true;
5709                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5710                            + " but new version " + pkg.mVersionCode + " better than installed "
5711                            + ps.versionCode + "; hiding system");
5712                } else {
5713                    /*
5714                     * The newly found system app is a newer version that the
5715                     * one previously installed. Simply remove the
5716                     * already-installed application and replace it with our own
5717                     * while keeping the application data.
5718                     */
5719                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5720                            + " reverting from " + ps.codePathString + ": new version "
5721                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5722                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5723                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5724                    synchronized (mInstallLock) {
5725                        args.cleanUpResourcesLI();
5726                    }
5727                }
5728            }
5729        }
5730
5731        // The apk is forward locked (not public) if its code and resources
5732        // are kept in different files. (except for app in either system or
5733        // vendor path).
5734        // TODO grab this value from PackageSettings
5735        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5736            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5737                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5738            }
5739        }
5740
5741        // TODO: extend to support forward-locked splits
5742        String resourcePath = null;
5743        String baseResourcePath = null;
5744        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5745            if (ps != null && ps.resourcePathString != null) {
5746                resourcePath = ps.resourcePathString;
5747                baseResourcePath = ps.resourcePathString;
5748            } else {
5749                // Should not happen at all. Just log an error.
5750                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5751            }
5752        } else {
5753            resourcePath = pkg.codePath;
5754            baseResourcePath = pkg.baseCodePath;
5755        }
5756
5757        // Set application objects path explicitly.
5758        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5759        pkg.applicationInfo.setCodePath(pkg.codePath);
5760        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5761        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5762        pkg.applicationInfo.setResourcePath(resourcePath);
5763        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5764        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5765
5766        // Note that we invoke the following method only if we are about to unpack an application
5767        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5768                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5769
5770        /*
5771         * If the system app should be overridden by a previously installed
5772         * data, hide the system app now and let the /data/app scan pick it up
5773         * again.
5774         */
5775        if (shouldHideSystemApp) {
5776            synchronized (mPackages) {
5777                /*
5778                 * We have to grant systems permissions before we hide, because
5779                 * grantPermissions will assume the package update is trying to
5780                 * expand its permissions.
5781                 */
5782                grantPermissionsLPw(pkg, true, pkg.packageName);
5783                mSettings.disableSystemPackageLPw(pkg.packageName);
5784            }
5785        }
5786
5787        return scannedPkg;
5788    }
5789
5790    private static String fixProcessName(String defProcessName,
5791            String processName, int uid) {
5792        if (processName == null) {
5793            return defProcessName;
5794        }
5795        return processName;
5796    }
5797
5798    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5799            throws PackageManagerException {
5800        if (pkgSetting.signatures.mSignatures != null) {
5801            // Already existing package. Make sure signatures match
5802            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5803                    == PackageManager.SIGNATURE_MATCH;
5804            if (!match) {
5805                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5806                        == PackageManager.SIGNATURE_MATCH;
5807            }
5808            if (!match) {
5809                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5810                        == PackageManager.SIGNATURE_MATCH;
5811            }
5812            if (!match) {
5813                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5814                        + pkg.packageName + " signatures do not match the "
5815                        + "previously installed version; ignoring!");
5816            }
5817        }
5818
5819        // Check for shared user signatures
5820        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5821            // Already existing package. Make sure signatures match
5822            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5823                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5824            if (!match) {
5825                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5826                        == PackageManager.SIGNATURE_MATCH;
5827            }
5828            if (!match) {
5829                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5830                        == PackageManager.SIGNATURE_MATCH;
5831            }
5832            if (!match) {
5833                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5834                        "Package " + pkg.packageName
5835                        + " has no signatures that match those in shared user "
5836                        + pkgSetting.sharedUser.name + "; ignoring!");
5837            }
5838        }
5839    }
5840
5841    /**
5842     * Enforces that only the system UID or root's UID can call a method exposed
5843     * via Binder.
5844     *
5845     * @param message used as message if SecurityException is thrown
5846     * @throws SecurityException if the caller is not system or root
5847     */
5848    private static final void enforceSystemOrRoot(String message) {
5849        final int uid = Binder.getCallingUid();
5850        if (uid != Process.SYSTEM_UID && uid != 0) {
5851            throw new SecurityException(message);
5852        }
5853    }
5854
5855    @Override
5856    public void performBootDexOpt() {
5857        enforceSystemOrRoot("Only the system can request dexopt be performed");
5858
5859        // Before everything else, see whether we need to fstrim.
5860        try {
5861            IMountService ms = PackageHelper.getMountService();
5862            if (ms != null) {
5863                final boolean isUpgrade = isUpgrade();
5864                boolean doTrim = isUpgrade;
5865                if (doTrim) {
5866                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5867                } else {
5868                    final long interval = android.provider.Settings.Global.getLong(
5869                            mContext.getContentResolver(),
5870                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5871                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5872                    if (interval > 0) {
5873                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5874                        if (timeSinceLast > interval) {
5875                            doTrim = true;
5876                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5877                                    + "; running immediately");
5878                        }
5879                    }
5880                }
5881                if (doTrim) {
5882                    if (!isFirstBoot()) {
5883                        try {
5884                            ActivityManagerNative.getDefault().showBootMessage(
5885                                    mContext.getResources().getString(
5886                                            R.string.android_upgrading_fstrim), true);
5887                        } catch (RemoteException e) {
5888                        }
5889                    }
5890                    ms.runMaintenance();
5891                }
5892            } else {
5893                Slog.e(TAG, "Mount service unavailable!");
5894            }
5895        } catch (RemoteException e) {
5896            // Can't happen; MountService is local
5897        }
5898
5899        final ArraySet<PackageParser.Package> pkgs;
5900        synchronized (mPackages) {
5901            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5902        }
5903
5904        if (pkgs != null) {
5905            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5906            // in case the device runs out of space.
5907            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5908            // Give priority to core apps.
5909            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5910                PackageParser.Package pkg = it.next();
5911                if (pkg.coreApp) {
5912                    if (DEBUG_DEXOPT) {
5913                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5914                    }
5915                    sortedPkgs.add(pkg);
5916                    it.remove();
5917                }
5918            }
5919            // Give priority to system apps that listen for pre boot complete.
5920            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5921            ArraySet<String> 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 pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5927                    }
5928                    sortedPkgs.add(pkg);
5929                    it.remove();
5930                }
5931            }
5932            // Give priority to system apps.
5933            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5934                PackageParser.Package pkg = it.next();
5935                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5936                    if (DEBUG_DEXOPT) {
5937                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5938                    }
5939                    sortedPkgs.add(pkg);
5940                    it.remove();
5941                }
5942            }
5943            // Give priority to updated system apps.
5944            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5945                PackageParser.Package pkg = it.next();
5946                if (pkg.isUpdatedSystemApp()) {
5947                    if (DEBUG_DEXOPT) {
5948                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5949                    }
5950                    sortedPkgs.add(pkg);
5951                    it.remove();
5952                }
5953            }
5954            // Give priority to apps that listen for boot complete.
5955            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5956            pkgNames = getPackageNamesForIntent(intent);
5957            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5958                PackageParser.Package pkg = it.next();
5959                if (pkgNames.contains(pkg.packageName)) {
5960                    if (DEBUG_DEXOPT) {
5961                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5962                    }
5963                    sortedPkgs.add(pkg);
5964                    it.remove();
5965                }
5966            }
5967            // Filter out packages that aren't recently used.
5968            filterRecentlyUsedApps(pkgs);
5969            // Add all remaining apps.
5970            for (PackageParser.Package pkg : pkgs) {
5971                if (DEBUG_DEXOPT) {
5972                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5973                }
5974                sortedPkgs.add(pkg);
5975            }
5976
5977            // If we want to be lazy, filter everything that wasn't recently used.
5978            if (mLazyDexOpt) {
5979                filterRecentlyUsedApps(sortedPkgs);
5980            }
5981
5982            int i = 0;
5983            int total = sortedPkgs.size();
5984            File dataDir = Environment.getDataDirectory();
5985            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5986            if (lowThreshold == 0) {
5987                throw new IllegalStateException("Invalid low memory threshold");
5988            }
5989            for (PackageParser.Package pkg : sortedPkgs) {
5990                long usableSpace = dataDir.getUsableSpace();
5991                if (usableSpace < lowThreshold) {
5992                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5993                    break;
5994                }
5995                performBootDexOpt(pkg, ++i, total);
5996            }
5997        }
5998    }
5999
6000    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6001        // Filter out packages that aren't recently used.
6002        //
6003        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6004        // should do a full dexopt.
6005        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6006            int total = pkgs.size();
6007            int skipped = 0;
6008            long now = System.currentTimeMillis();
6009            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6010                PackageParser.Package pkg = i.next();
6011                long then = pkg.mLastPackageUsageTimeInMills;
6012                if (then + mDexOptLRUThresholdInMills < now) {
6013                    if (DEBUG_DEXOPT) {
6014                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6015                              ((then == 0) ? "never" : new Date(then)));
6016                    }
6017                    i.remove();
6018                    skipped++;
6019                }
6020            }
6021            if (DEBUG_DEXOPT) {
6022                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6023            }
6024        }
6025    }
6026
6027    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6028        List<ResolveInfo> ris = null;
6029        try {
6030            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6031                    intent, null, 0, UserHandle.USER_OWNER);
6032        } catch (RemoteException e) {
6033        }
6034        ArraySet<String> pkgNames = new ArraySet<String>();
6035        if (ris != null) {
6036            for (ResolveInfo ri : ris) {
6037                pkgNames.add(ri.activityInfo.packageName);
6038            }
6039        }
6040        return pkgNames;
6041    }
6042
6043    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6044        if (DEBUG_DEXOPT) {
6045            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6046        }
6047        if (!isFirstBoot()) {
6048            try {
6049                ActivityManagerNative.getDefault().showBootMessage(
6050                        mContext.getResources().getString(R.string.android_upgrading_apk,
6051                                curr, total), true);
6052            } catch (RemoteException e) {
6053            }
6054        }
6055        PackageParser.Package p = pkg;
6056        synchronized (mInstallLock) {
6057            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6058                    false /* force dex */, false /* defer */, true /* include dependencies */);
6059        }
6060    }
6061
6062    @Override
6063    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6064        return performDexOpt(packageName, instructionSet, false);
6065    }
6066
6067    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6068        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6069        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6070        if (!dexopt && !updateUsage) {
6071            // We aren't going to dexopt or update usage, so bail early.
6072            return false;
6073        }
6074        PackageParser.Package p;
6075        final String targetInstructionSet;
6076        synchronized (mPackages) {
6077            p = mPackages.get(packageName);
6078            if (p == null) {
6079                return false;
6080            }
6081            if (updateUsage) {
6082                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6083            }
6084            mPackageUsage.write(false);
6085            if (!dexopt) {
6086                // We aren't going to dexopt, so bail early.
6087                return false;
6088            }
6089
6090            targetInstructionSet = instructionSet != null ? instructionSet :
6091                    getPrimaryInstructionSet(p.applicationInfo);
6092            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6093                return false;
6094            }
6095        }
6096
6097        synchronized (mInstallLock) {
6098            final String[] instructionSets = new String[] { targetInstructionSet };
6099            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6100                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6101            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6102        }
6103    }
6104
6105    public ArraySet<String> getPackagesThatNeedDexOpt() {
6106        ArraySet<String> pkgs = null;
6107        synchronized (mPackages) {
6108            for (PackageParser.Package p : mPackages.values()) {
6109                if (DEBUG_DEXOPT) {
6110                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6111                }
6112                if (!p.mDexOptPerformed.isEmpty()) {
6113                    continue;
6114                }
6115                if (pkgs == null) {
6116                    pkgs = new ArraySet<String>();
6117                }
6118                pkgs.add(p.packageName);
6119            }
6120        }
6121        return pkgs;
6122    }
6123
6124    public void shutdown() {
6125        mPackageUsage.write(true);
6126    }
6127
6128    @Override
6129    public void forceDexOpt(String packageName) {
6130        enforceSystemOrRoot("forceDexOpt");
6131
6132        PackageParser.Package pkg;
6133        synchronized (mPackages) {
6134            pkg = mPackages.get(packageName);
6135            if (pkg == null) {
6136                throw new IllegalArgumentException("Missing package: " + packageName);
6137            }
6138        }
6139
6140        synchronized (mInstallLock) {
6141            final String[] instructionSets = new String[] {
6142                    getPrimaryInstructionSet(pkg.applicationInfo) };
6143            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6144                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6145            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6146                throw new IllegalStateException("Failed to dexopt: " + res);
6147            }
6148        }
6149    }
6150
6151    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6152        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6153            Slog.w(TAG, "Unable to update from " + oldPkg.name
6154                    + " to " + newPkg.packageName
6155                    + ": old package not in system partition");
6156            return false;
6157        } else if (mPackages.get(oldPkg.name) != null) {
6158            Slog.w(TAG, "Unable to update from " + oldPkg.name
6159                    + " to " + newPkg.packageName
6160                    + ": old package still exists");
6161            return false;
6162        }
6163        return true;
6164    }
6165
6166    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6167        int[] users = sUserManager.getUserIds();
6168        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6169        if (res < 0) {
6170            return res;
6171        }
6172        for (int user : users) {
6173            if (user != 0) {
6174                res = mInstaller.createUserData(volumeUuid, packageName,
6175                        UserHandle.getUid(user, uid), user, seinfo);
6176                if (res < 0) {
6177                    return res;
6178                }
6179            }
6180        }
6181        return res;
6182    }
6183
6184    private int removeDataDirsLI(String volumeUuid, String packageName) {
6185        int[] users = sUserManager.getUserIds();
6186        int res = 0;
6187        for (int user : users) {
6188            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6189            if (resInner < 0) {
6190                res = resInner;
6191            }
6192        }
6193
6194        return res;
6195    }
6196
6197    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6198        int[] users = sUserManager.getUserIds();
6199        int res = 0;
6200        for (int user : users) {
6201            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6202            if (resInner < 0) {
6203                res = resInner;
6204            }
6205        }
6206        return res;
6207    }
6208
6209    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6210            PackageParser.Package changingLib) {
6211        if (file.path != null) {
6212            usesLibraryFiles.add(file.path);
6213            return;
6214        }
6215        PackageParser.Package p = mPackages.get(file.apk);
6216        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6217            // If we are doing this while in the middle of updating a library apk,
6218            // then we need to make sure to use that new apk for determining the
6219            // dependencies here.  (We haven't yet finished committing the new apk
6220            // to the package manager state.)
6221            if (p == null || p.packageName.equals(changingLib.packageName)) {
6222                p = changingLib;
6223            }
6224        }
6225        if (p != null) {
6226            usesLibraryFiles.addAll(p.getAllCodePaths());
6227        }
6228    }
6229
6230    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6231            PackageParser.Package changingLib) throws PackageManagerException {
6232        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6233            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6234            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6235            for (int i=0; i<N; i++) {
6236                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6237                if (file == null) {
6238                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6239                            "Package " + pkg.packageName + " requires unavailable shared library "
6240                            + pkg.usesLibraries.get(i) + "; failing!");
6241                }
6242                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6243            }
6244            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6245            for (int i=0; i<N; i++) {
6246                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6247                if (file == null) {
6248                    Slog.w(TAG, "Package " + pkg.packageName
6249                            + " desires unavailable shared library "
6250                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6251                } else {
6252                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6253                }
6254            }
6255            N = usesLibraryFiles.size();
6256            if (N > 0) {
6257                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6258            } else {
6259                pkg.usesLibraryFiles = null;
6260            }
6261        }
6262    }
6263
6264    private static boolean hasString(List<String> list, List<String> which) {
6265        if (list == null) {
6266            return false;
6267        }
6268        for (int i=list.size()-1; i>=0; i--) {
6269            for (int j=which.size()-1; j>=0; j--) {
6270                if (which.get(j).equals(list.get(i))) {
6271                    return true;
6272                }
6273            }
6274        }
6275        return false;
6276    }
6277
6278    private void updateAllSharedLibrariesLPw() {
6279        for (PackageParser.Package pkg : mPackages.values()) {
6280            try {
6281                updateSharedLibrariesLPw(pkg, null);
6282            } catch (PackageManagerException e) {
6283                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6284            }
6285        }
6286    }
6287
6288    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6289            PackageParser.Package changingPkg) {
6290        ArrayList<PackageParser.Package> res = null;
6291        for (PackageParser.Package pkg : mPackages.values()) {
6292            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6293                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6294                if (res == null) {
6295                    res = new ArrayList<PackageParser.Package>();
6296                }
6297                res.add(pkg);
6298                try {
6299                    updateSharedLibrariesLPw(pkg, changingPkg);
6300                } catch (PackageManagerException e) {
6301                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6302                }
6303            }
6304        }
6305        return res;
6306    }
6307
6308    /**
6309     * Derive the value of the {@code cpuAbiOverride} based on the provided
6310     * value and an optional stored value from the package settings.
6311     */
6312    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6313        String cpuAbiOverride = null;
6314
6315        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6316            cpuAbiOverride = null;
6317        } else if (abiOverride != null) {
6318            cpuAbiOverride = abiOverride;
6319        } else if (settings != null) {
6320            cpuAbiOverride = settings.cpuAbiOverrideString;
6321        }
6322
6323        return cpuAbiOverride;
6324    }
6325
6326    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6327            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6328        boolean success = false;
6329        try {
6330            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6331                    currentTime, user);
6332            success = true;
6333            return res;
6334        } finally {
6335            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6336                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6337            }
6338        }
6339    }
6340
6341    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6342            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6343        final File scanFile = new File(pkg.codePath);
6344        if (pkg.applicationInfo.getCodePath() == null ||
6345                pkg.applicationInfo.getResourcePath() == null) {
6346            // Bail out. The resource and code paths haven't been set.
6347            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6348                    "Code and resource paths haven't been set correctly");
6349        }
6350
6351        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6352            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6353        } else {
6354            // Only allow system apps to be flagged as core apps.
6355            pkg.coreApp = false;
6356        }
6357
6358        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6359            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6360        }
6361
6362        if (mCustomResolverComponentName != null &&
6363                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6364            setUpCustomResolverActivity(pkg);
6365        }
6366
6367        if (pkg.packageName.equals("android")) {
6368            synchronized (mPackages) {
6369                if (mAndroidApplication != null) {
6370                    Slog.w(TAG, "*************************************************");
6371                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6372                    Slog.w(TAG, " file=" + scanFile);
6373                    Slog.w(TAG, "*************************************************");
6374                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6375                            "Core android package being redefined.  Skipping.");
6376                }
6377
6378                // Set up information for our fall-back user intent resolution activity.
6379                mPlatformPackage = pkg;
6380                pkg.mVersionCode = mSdkVersion;
6381                mAndroidApplication = pkg.applicationInfo;
6382
6383                if (!mResolverReplaced) {
6384                    mResolveActivity.applicationInfo = mAndroidApplication;
6385                    mResolveActivity.name = ResolverActivity.class.getName();
6386                    mResolveActivity.packageName = mAndroidApplication.packageName;
6387                    mResolveActivity.processName = "system:ui";
6388                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6389                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6390                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6391                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6392                    mResolveActivity.exported = true;
6393                    mResolveActivity.enabled = true;
6394                    mResolveInfo.activityInfo = mResolveActivity;
6395                    mResolveInfo.priority = 0;
6396                    mResolveInfo.preferredOrder = 0;
6397                    mResolveInfo.match = 0;
6398                    mResolveComponentName = new ComponentName(
6399                            mAndroidApplication.packageName, mResolveActivity.name);
6400                }
6401            }
6402        }
6403
6404        if (DEBUG_PACKAGE_SCANNING) {
6405            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6406                Log.d(TAG, "Scanning package " + pkg.packageName);
6407        }
6408
6409        if (mPackages.containsKey(pkg.packageName)
6410                || mSharedLibraries.containsKey(pkg.packageName)) {
6411            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6412                    "Application package " + pkg.packageName
6413                    + " already installed.  Skipping duplicate.");
6414        }
6415
6416        // If we're only installing presumed-existing packages, require that the
6417        // scanned APK is both already known and at the path previously established
6418        // for it.  Previously unknown packages we pick up normally, but if we have an
6419        // a priori expectation about this package's install presence, enforce it.
6420        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6421            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6422            if (known != null) {
6423                if (DEBUG_PACKAGE_SCANNING) {
6424                    Log.d(TAG, "Examining " + pkg.codePath
6425                            + " and requiring known paths " + known.codePathString
6426                            + " & " + known.resourcePathString);
6427                }
6428                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6429                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6430                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6431                            "Application package " + pkg.packageName
6432                            + " found at " + pkg.applicationInfo.getCodePath()
6433                            + " but expected at " + known.codePathString + "; ignoring.");
6434                }
6435            }
6436        }
6437
6438        // Initialize package source and resource directories
6439        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6440        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6441
6442        SharedUserSetting suid = null;
6443        PackageSetting pkgSetting = null;
6444
6445        if (!isSystemApp(pkg)) {
6446            // Only system apps can use these features.
6447            pkg.mOriginalPackages = null;
6448            pkg.mRealPackage = null;
6449            pkg.mAdoptPermissions = null;
6450        }
6451
6452        // writer
6453        synchronized (mPackages) {
6454            if (pkg.mSharedUserId != null) {
6455                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6456                if (suid == null) {
6457                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6458                            "Creating application package " + pkg.packageName
6459                            + " for shared user failed");
6460                }
6461                if (DEBUG_PACKAGE_SCANNING) {
6462                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6463                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6464                                + "): packages=" + suid.packages);
6465                }
6466            }
6467
6468            // Check if we are renaming from an original package name.
6469            PackageSetting origPackage = null;
6470            String realName = null;
6471            if (pkg.mOriginalPackages != null) {
6472                // This package may need to be renamed to a previously
6473                // installed name.  Let's check on that...
6474                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6475                if (pkg.mOriginalPackages.contains(renamed)) {
6476                    // This package had originally been installed as the
6477                    // original name, and we have already taken care of
6478                    // transitioning to the new one.  Just update the new
6479                    // one to continue using the old name.
6480                    realName = pkg.mRealPackage;
6481                    if (!pkg.packageName.equals(renamed)) {
6482                        // Callers into this function may have already taken
6483                        // care of renaming the package; only do it here if
6484                        // it is not already done.
6485                        pkg.setPackageName(renamed);
6486                    }
6487
6488                } else {
6489                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6490                        if ((origPackage = mSettings.peekPackageLPr(
6491                                pkg.mOriginalPackages.get(i))) != null) {
6492                            // We do have the package already installed under its
6493                            // original name...  should we use it?
6494                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6495                                // New package is not compatible with original.
6496                                origPackage = null;
6497                                continue;
6498                            } else if (origPackage.sharedUser != null) {
6499                                // Make sure uid is compatible between packages.
6500                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6501                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6502                                            + " to " + pkg.packageName + ": old uid "
6503                                            + origPackage.sharedUser.name
6504                                            + " differs from " + pkg.mSharedUserId);
6505                                    origPackage = null;
6506                                    continue;
6507                                }
6508                            } else {
6509                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6510                                        + pkg.packageName + " to old name " + origPackage.name);
6511                            }
6512                            break;
6513                        }
6514                    }
6515                }
6516            }
6517
6518            if (mTransferedPackages.contains(pkg.packageName)) {
6519                Slog.w(TAG, "Package " + pkg.packageName
6520                        + " was transferred to another, but its .apk remains");
6521            }
6522
6523            // Just create the setting, don't add it yet. For already existing packages
6524            // the PkgSetting exists already and doesn't have to be created.
6525            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6526                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6527                    pkg.applicationInfo.primaryCpuAbi,
6528                    pkg.applicationInfo.secondaryCpuAbi,
6529                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6530                    user, false);
6531            if (pkgSetting == null) {
6532                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6533                        "Creating application package " + pkg.packageName + " failed");
6534            }
6535
6536            if (pkgSetting.origPackage != null) {
6537                // If we are first transitioning from an original package,
6538                // fix up the new package's name now.  We need to do this after
6539                // looking up the package under its new name, so getPackageLP
6540                // can take care of fiddling things correctly.
6541                pkg.setPackageName(origPackage.name);
6542
6543                // File a report about this.
6544                String msg = "New package " + pkgSetting.realName
6545                        + " renamed to replace old package " + pkgSetting.name;
6546                reportSettingsProblem(Log.WARN, msg);
6547
6548                // Make a note of it.
6549                mTransferedPackages.add(origPackage.name);
6550
6551                // No longer need to retain this.
6552                pkgSetting.origPackage = null;
6553            }
6554
6555            if (realName != null) {
6556                // Make a note of it.
6557                mTransferedPackages.add(pkg.packageName);
6558            }
6559
6560            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6561                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6562            }
6563
6564            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6565                // Check all shared libraries and map to their actual file path.
6566                // We only do this here for apps not on a system dir, because those
6567                // are the only ones that can fail an install due to this.  We
6568                // will take care of the system apps by updating all of their
6569                // library paths after the scan is done.
6570                updateSharedLibrariesLPw(pkg, null);
6571            }
6572
6573            if (mFoundPolicyFile) {
6574                SELinuxMMAC.assignSeinfoValue(pkg);
6575            }
6576
6577            pkg.applicationInfo.uid = pkgSetting.appId;
6578            pkg.mExtras = pkgSetting;
6579            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6580                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6581                    // We just determined the app is signed correctly, so bring
6582                    // over the latest parsed certs.
6583                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6584                } else {
6585                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6586                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6587                                "Package " + pkg.packageName + " upgrade keys do not match the "
6588                                + "previously installed version");
6589                    } else {
6590                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6591                        String msg = "System package " + pkg.packageName
6592                            + " signature changed; retaining data.";
6593                        reportSettingsProblem(Log.WARN, msg);
6594                    }
6595                }
6596            } else {
6597                try {
6598                    verifySignaturesLP(pkgSetting, pkg);
6599                    // We just determined the app is signed correctly, so bring
6600                    // over the latest parsed certs.
6601                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6602                } catch (PackageManagerException e) {
6603                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6604                        throw e;
6605                    }
6606                    // The signature has changed, but this package is in the system
6607                    // image...  let's recover!
6608                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6609                    // However...  if this package is part of a shared user, but it
6610                    // doesn't match the signature of the shared user, let's fail.
6611                    // What this means is that you can't change the signatures
6612                    // associated with an overall shared user, which doesn't seem all
6613                    // that unreasonable.
6614                    if (pkgSetting.sharedUser != null) {
6615                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6616                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6617                            throw new PackageManagerException(
6618                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6619                                            "Signature mismatch for shared user : "
6620                                            + pkgSetting.sharedUser);
6621                        }
6622                    }
6623                    // File a report about this.
6624                    String msg = "System package " + pkg.packageName
6625                        + " signature changed; retaining data.";
6626                    reportSettingsProblem(Log.WARN, msg);
6627                }
6628            }
6629            // Verify that this new package doesn't have any content providers
6630            // that conflict with existing packages.  Only do this if the
6631            // package isn't already installed, since we don't want to break
6632            // things that are installed.
6633            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6634                final int N = pkg.providers.size();
6635                int i;
6636                for (i=0; i<N; i++) {
6637                    PackageParser.Provider p = pkg.providers.get(i);
6638                    if (p.info.authority != null) {
6639                        String names[] = p.info.authority.split(";");
6640                        for (int j = 0; j < names.length; j++) {
6641                            if (mProvidersByAuthority.containsKey(names[j])) {
6642                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6643                                final String otherPackageName =
6644                                        ((other != null && other.getComponentName() != null) ?
6645                                                other.getComponentName().getPackageName() : "?");
6646                                throw new PackageManagerException(
6647                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6648                                                "Can't install because provider name " + names[j]
6649                                                + " (in package " + pkg.applicationInfo.packageName
6650                                                + ") is already used by " + otherPackageName);
6651                            }
6652                        }
6653                    }
6654                }
6655            }
6656
6657            if (pkg.mAdoptPermissions != null) {
6658                // This package wants to adopt ownership of permissions from
6659                // another package.
6660                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6661                    final String origName = pkg.mAdoptPermissions.get(i);
6662                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6663                    if (orig != null) {
6664                        if (verifyPackageUpdateLPr(orig, pkg)) {
6665                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6666                                    + pkg.packageName);
6667                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6668                        }
6669                    }
6670                }
6671            }
6672        }
6673
6674        final String pkgName = pkg.packageName;
6675
6676        final long scanFileTime = scanFile.lastModified();
6677        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6678        pkg.applicationInfo.processName = fixProcessName(
6679                pkg.applicationInfo.packageName,
6680                pkg.applicationInfo.processName,
6681                pkg.applicationInfo.uid);
6682
6683        File dataPath;
6684        if (mPlatformPackage == pkg) {
6685            // The system package is special.
6686            dataPath = new File(Environment.getDataDirectory(), "system");
6687
6688            pkg.applicationInfo.dataDir = dataPath.getPath();
6689
6690        } else {
6691            // This is a normal package, need to make its data directory.
6692            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6693                    UserHandle.USER_OWNER, pkg.packageName);
6694
6695            boolean uidError = false;
6696            if (dataPath.exists()) {
6697                int currentUid = 0;
6698                try {
6699                    StructStat stat = Os.stat(dataPath.getPath());
6700                    currentUid = stat.st_uid;
6701                } catch (ErrnoException e) {
6702                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6703                }
6704
6705                // If we have mismatched owners for the data path, we have a problem.
6706                if (currentUid != pkg.applicationInfo.uid) {
6707                    boolean recovered = false;
6708                    if (currentUid == 0) {
6709                        // The directory somehow became owned by root.  Wow.
6710                        // This is probably because the system was stopped while
6711                        // installd was in the middle of messing with its libs
6712                        // directory.  Ask installd to fix that.
6713                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6714                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6715                        if (ret >= 0) {
6716                            recovered = true;
6717                            String msg = "Package " + pkg.packageName
6718                                    + " unexpectedly changed to uid 0; recovered to " +
6719                                    + pkg.applicationInfo.uid;
6720                            reportSettingsProblem(Log.WARN, msg);
6721                        }
6722                    }
6723                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6724                            || (scanFlags&SCAN_BOOTING) != 0)) {
6725                        // If this is a system app, we can at least delete its
6726                        // current data so the application will still work.
6727                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6728                        if (ret >= 0) {
6729                            // TODO: Kill the processes first
6730                            // Old data gone!
6731                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6732                                    ? "System package " : "Third party package ";
6733                            String msg = prefix + pkg.packageName
6734                                    + " has changed from uid: "
6735                                    + currentUid + " to "
6736                                    + pkg.applicationInfo.uid + "; old data erased";
6737                            reportSettingsProblem(Log.WARN, msg);
6738                            recovered = true;
6739
6740                            // And now re-install the app.
6741                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6742                                    pkg.applicationInfo.seinfo);
6743                            if (ret == -1) {
6744                                // Ack should not happen!
6745                                msg = prefix + pkg.packageName
6746                                        + " could not have data directory re-created after delete.";
6747                                reportSettingsProblem(Log.WARN, msg);
6748                                throw new PackageManagerException(
6749                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6750                            }
6751                        }
6752                        if (!recovered) {
6753                            mHasSystemUidErrors = true;
6754                        }
6755                    } else if (!recovered) {
6756                        // If we allow this install to proceed, we will be broken.
6757                        // Abort, abort!
6758                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6759                                "scanPackageLI");
6760                    }
6761                    if (!recovered) {
6762                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6763                            + pkg.applicationInfo.uid + "/fs_"
6764                            + currentUid;
6765                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6766                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6767                        String msg = "Package " + pkg.packageName
6768                                + " has mismatched uid: "
6769                                + currentUid + " on disk, "
6770                                + pkg.applicationInfo.uid + " in settings";
6771                        // writer
6772                        synchronized (mPackages) {
6773                            mSettings.mReadMessages.append(msg);
6774                            mSettings.mReadMessages.append('\n');
6775                            uidError = true;
6776                            if (!pkgSetting.uidError) {
6777                                reportSettingsProblem(Log.ERROR, msg);
6778                            }
6779                        }
6780                    }
6781                }
6782                pkg.applicationInfo.dataDir = dataPath.getPath();
6783                if (mShouldRestoreconData) {
6784                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6785                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6786                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6787                }
6788            } else {
6789                if (DEBUG_PACKAGE_SCANNING) {
6790                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6791                        Log.v(TAG, "Want this data dir: " + dataPath);
6792                }
6793                //invoke installer to do the actual installation
6794                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6795                        pkg.applicationInfo.seinfo);
6796                if (ret < 0) {
6797                    // Error from installer
6798                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6799                            "Unable to create data dirs [errorCode=" + ret + "]");
6800                }
6801
6802                if (dataPath.exists()) {
6803                    pkg.applicationInfo.dataDir = dataPath.getPath();
6804                } else {
6805                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6806                    pkg.applicationInfo.dataDir = null;
6807                }
6808            }
6809
6810            pkgSetting.uidError = uidError;
6811        }
6812
6813        final String path = scanFile.getPath();
6814        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6815
6816        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6817            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6818
6819            // Some system apps still use directory structure for native libraries
6820            // in which case we might end up not detecting abi solely based on apk
6821            // structure. Try to detect abi based on directory structure.
6822            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6823                    pkg.applicationInfo.primaryCpuAbi == null) {
6824                setBundledAppAbisAndRoots(pkg, pkgSetting);
6825                setNativeLibraryPaths(pkg);
6826            }
6827
6828        } else {
6829            if ((scanFlags & SCAN_MOVE) != 0) {
6830                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6831                // but we already have this packages package info in the PackageSetting. We just
6832                // use that and derive the native library path based on the new codepath.
6833                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6834                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6835            }
6836
6837            // Set native library paths again. For moves, the path will be updated based on the
6838            // ABIs we've determined above. For non-moves, the path will be updated based on the
6839            // ABIs we determined during compilation, but the path will depend on the final
6840            // package path (after the rename away from the stage path).
6841            setNativeLibraryPaths(pkg);
6842        }
6843
6844        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6845        final int[] userIds = sUserManager.getUserIds();
6846        synchronized (mInstallLock) {
6847            // Make sure all user data directories are ready to roll; we're okay
6848            // if they already exist
6849            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6850                for (int userId : userIds) {
6851                    if (userId != 0) {
6852                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6853                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6854                                pkg.applicationInfo.seinfo);
6855                    }
6856                }
6857            }
6858
6859            // Create a native library symlink only if we have native libraries
6860            // and if the native libraries are 32 bit libraries. We do not provide
6861            // this symlink for 64 bit libraries.
6862            if (pkg.applicationInfo.primaryCpuAbi != null &&
6863                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6864                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6865                for (int userId : userIds) {
6866                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6867                            nativeLibPath, userId) < 0) {
6868                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6869                                "Failed linking native library dir (user=" + userId + ")");
6870                    }
6871                }
6872            }
6873        }
6874
6875        // This is a special case for the "system" package, where the ABI is
6876        // dictated by the zygote configuration (and init.rc). We should keep track
6877        // of this ABI so that we can deal with "normal" applications that run under
6878        // the same UID correctly.
6879        if (mPlatformPackage == pkg) {
6880            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6881                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6882        }
6883
6884        // If there's a mismatch between the abi-override in the package setting
6885        // and the abiOverride specified for the install. Warn about this because we
6886        // would've already compiled the app without taking the package setting into
6887        // account.
6888        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6889            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6890                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6891                        " for package: " + pkg.packageName);
6892            }
6893        }
6894
6895        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6896        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6897        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6898
6899        // Copy the derived override back to the parsed package, so that we can
6900        // update the package settings accordingly.
6901        pkg.cpuAbiOverride = cpuAbiOverride;
6902
6903        if (DEBUG_ABI_SELECTION) {
6904            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6905                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6906                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6907        }
6908
6909        // Push the derived path down into PackageSettings so we know what to
6910        // clean up at uninstall time.
6911        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6912
6913        if (DEBUG_ABI_SELECTION) {
6914            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6915                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6916                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6917        }
6918
6919        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6920            // We don't do this here during boot because we can do it all
6921            // at once after scanning all existing packages.
6922            //
6923            // We also do this *before* we perform dexopt on this package, so that
6924            // we can avoid redundant dexopts, and also to make sure we've got the
6925            // code and package path correct.
6926            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6927                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6928        }
6929
6930        if ((scanFlags & SCAN_NO_DEX) == 0) {
6931            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6932                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6933            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6934                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6935            }
6936        }
6937        if (mFactoryTest && pkg.requestedPermissions.contains(
6938                android.Manifest.permission.FACTORY_TEST)) {
6939            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6940        }
6941
6942        ArrayList<PackageParser.Package> clientLibPkgs = null;
6943
6944        // writer
6945        synchronized (mPackages) {
6946            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6947                // Only system apps can add new shared libraries.
6948                if (pkg.libraryNames != null) {
6949                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6950                        String name = pkg.libraryNames.get(i);
6951                        boolean allowed = false;
6952                        if (pkg.isUpdatedSystemApp()) {
6953                            // New library entries can only be added through the
6954                            // system image.  This is important to get rid of a lot
6955                            // of nasty edge cases: for example if we allowed a non-
6956                            // system update of the app to add a library, then uninstalling
6957                            // the update would make the library go away, and assumptions
6958                            // we made such as through app install filtering would now
6959                            // have allowed apps on the device which aren't compatible
6960                            // with it.  Better to just have the restriction here, be
6961                            // conservative, and create many fewer cases that can negatively
6962                            // impact the user experience.
6963                            final PackageSetting sysPs = mSettings
6964                                    .getDisabledSystemPkgLPr(pkg.packageName);
6965                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6966                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6967                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6968                                        allowed = true;
6969                                        allowed = true;
6970                                        break;
6971                                    }
6972                                }
6973                            }
6974                        } else {
6975                            allowed = true;
6976                        }
6977                        if (allowed) {
6978                            if (!mSharedLibraries.containsKey(name)) {
6979                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6980                            } else if (!name.equals(pkg.packageName)) {
6981                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6982                                        + name + " already exists; skipping");
6983                            }
6984                        } else {
6985                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6986                                    + name + " that is not declared on system image; skipping");
6987                        }
6988                    }
6989                    if ((scanFlags&SCAN_BOOTING) == 0) {
6990                        // If we are not booting, we need to update any applications
6991                        // that are clients of our shared library.  If we are booting,
6992                        // this will all be done once the scan is complete.
6993                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6994                    }
6995                }
6996            }
6997        }
6998
6999        // We also need to dexopt any apps that are dependent on this library.  Note that
7000        // if these fail, we should abort the install since installing the library will
7001        // result in some apps being broken.
7002        if (clientLibPkgs != null) {
7003            if ((scanFlags & SCAN_NO_DEX) == 0) {
7004                for (int i = 0; i < clientLibPkgs.size(); i++) {
7005                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7006                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7007                            null /* instruction sets */, forceDex,
7008                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7009                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7010                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7011                                "scanPackageLI failed to dexopt clientLibPkgs");
7012                    }
7013                }
7014            }
7015        }
7016
7017        // Also need to kill any apps that are dependent on the library.
7018        if (clientLibPkgs != null) {
7019            for (int i=0; i<clientLibPkgs.size(); i++) {
7020                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7021                killApplication(clientPkg.applicationInfo.packageName,
7022                        clientPkg.applicationInfo.uid, "update lib");
7023            }
7024        }
7025
7026        // Make sure we're not adding any bogus keyset info
7027        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7028        ksms.assertScannedPackageValid(pkg);
7029
7030        // writer
7031        synchronized (mPackages) {
7032            // We don't expect installation to fail beyond this point
7033
7034            // Add the new setting to mSettings
7035            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7036            // Add the new setting to mPackages
7037            mPackages.put(pkg.applicationInfo.packageName, pkg);
7038            // Make sure we don't accidentally delete its data.
7039            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7040            while (iter.hasNext()) {
7041                PackageCleanItem item = iter.next();
7042                if (pkgName.equals(item.packageName)) {
7043                    iter.remove();
7044                }
7045            }
7046
7047            // Take care of first install / last update times.
7048            if (currentTime != 0) {
7049                if (pkgSetting.firstInstallTime == 0) {
7050                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7051                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7052                    pkgSetting.lastUpdateTime = currentTime;
7053                }
7054            } else if (pkgSetting.firstInstallTime == 0) {
7055                // We need *something*.  Take time time stamp of the file.
7056                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7057            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7058                if (scanFileTime != pkgSetting.timeStamp) {
7059                    // A package on the system image has changed; consider this
7060                    // to be an update.
7061                    pkgSetting.lastUpdateTime = scanFileTime;
7062                }
7063            }
7064
7065            // Add the package's KeySets to the global KeySetManagerService
7066            ksms.addScannedPackageLPw(pkg);
7067
7068            int N = pkg.providers.size();
7069            StringBuilder r = null;
7070            int i;
7071            for (i=0; i<N; i++) {
7072                PackageParser.Provider p = pkg.providers.get(i);
7073                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7074                        p.info.processName, pkg.applicationInfo.uid);
7075                mProviders.addProvider(p);
7076                p.syncable = p.info.isSyncable;
7077                if (p.info.authority != null) {
7078                    String names[] = p.info.authority.split(";");
7079                    p.info.authority = null;
7080                    for (int j = 0; j < names.length; j++) {
7081                        if (j == 1 && p.syncable) {
7082                            // We only want the first authority for a provider to possibly be
7083                            // syncable, so if we already added this provider using a different
7084                            // authority clear the syncable flag. We copy the provider before
7085                            // changing it because the mProviders object contains a reference
7086                            // to a provider that we don't want to change.
7087                            // Only do this for the second authority since the resulting provider
7088                            // object can be the same for all future authorities for this provider.
7089                            p = new PackageParser.Provider(p);
7090                            p.syncable = false;
7091                        }
7092                        if (!mProvidersByAuthority.containsKey(names[j])) {
7093                            mProvidersByAuthority.put(names[j], p);
7094                            if (p.info.authority == null) {
7095                                p.info.authority = names[j];
7096                            } else {
7097                                p.info.authority = p.info.authority + ";" + names[j];
7098                            }
7099                            if (DEBUG_PACKAGE_SCANNING) {
7100                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7101                                    Log.d(TAG, "Registered content provider: " + names[j]
7102                                            + ", className = " + p.info.name + ", isSyncable = "
7103                                            + p.info.isSyncable);
7104                            }
7105                        } else {
7106                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7107                            Slog.w(TAG, "Skipping provider name " + names[j] +
7108                                    " (in package " + pkg.applicationInfo.packageName +
7109                                    "): name already used by "
7110                                    + ((other != null && other.getComponentName() != null)
7111                                            ? other.getComponentName().getPackageName() : "?"));
7112                        }
7113                    }
7114                }
7115                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7116                    if (r == null) {
7117                        r = new StringBuilder(256);
7118                    } else {
7119                        r.append(' ');
7120                    }
7121                    r.append(p.info.name);
7122                }
7123            }
7124            if (r != null) {
7125                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7126            }
7127
7128            N = pkg.services.size();
7129            r = null;
7130            for (i=0; i<N; i++) {
7131                PackageParser.Service s = pkg.services.get(i);
7132                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7133                        s.info.processName, pkg.applicationInfo.uid);
7134                mServices.addService(s);
7135                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7136                    if (r == null) {
7137                        r = new StringBuilder(256);
7138                    } else {
7139                        r.append(' ');
7140                    }
7141                    r.append(s.info.name);
7142                }
7143            }
7144            if (r != null) {
7145                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7146            }
7147
7148            N = pkg.receivers.size();
7149            r = null;
7150            for (i=0; i<N; i++) {
7151                PackageParser.Activity a = pkg.receivers.get(i);
7152                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7153                        a.info.processName, pkg.applicationInfo.uid);
7154                mReceivers.addActivity(a, "receiver");
7155                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7156                    if (r == null) {
7157                        r = new StringBuilder(256);
7158                    } else {
7159                        r.append(' ');
7160                    }
7161                    r.append(a.info.name);
7162                }
7163            }
7164            if (r != null) {
7165                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7166            }
7167
7168            N = pkg.activities.size();
7169            r = null;
7170            for (i=0; i<N; i++) {
7171                PackageParser.Activity a = pkg.activities.get(i);
7172                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7173                        a.info.processName, pkg.applicationInfo.uid);
7174                mActivities.addActivity(a, "activity");
7175                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7176                    if (r == null) {
7177                        r = new StringBuilder(256);
7178                    } else {
7179                        r.append(' ');
7180                    }
7181                    r.append(a.info.name);
7182                }
7183            }
7184            if (r != null) {
7185                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7186            }
7187
7188            N = pkg.permissionGroups.size();
7189            r = null;
7190            for (i=0; i<N; i++) {
7191                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7192                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7193                if (cur == null) {
7194                    mPermissionGroups.put(pg.info.name, pg);
7195                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7196                        if (r == null) {
7197                            r = new StringBuilder(256);
7198                        } else {
7199                            r.append(' ');
7200                        }
7201                        r.append(pg.info.name);
7202                    }
7203                } else {
7204                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7205                            + pg.info.packageName + " ignored: original from "
7206                            + cur.info.packageName);
7207                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7208                        if (r == null) {
7209                            r = new StringBuilder(256);
7210                        } else {
7211                            r.append(' ');
7212                        }
7213                        r.append("DUP:");
7214                        r.append(pg.info.name);
7215                    }
7216                }
7217            }
7218            if (r != null) {
7219                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7220            }
7221
7222            N = pkg.permissions.size();
7223            r = null;
7224            for (i=0; i<N; i++) {
7225                PackageParser.Permission p = pkg.permissions.get(i);
7226
7227                // Now that permission groups have a special meaning, we ignore permission
7228                // groups for legacy apps to prevent unexpected behavior. In particular,
7229                // permissions for one app being granted to someone just becuase they happen
7230                // to be in a group defined by another app (before this had no implications).
7231                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7232                    p.group = mPermissionGroups.get(p.info.group);
7233                    // Warn for a permission in an unknown group.
7234                    if (p.info.group != null && p.group == null) {
7235                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7236                                + p.info.packageName + " in an unknown group " + p.info.group);
7237                    }
7238                }
7239
7240                ArrayMap<String, BasePermission> permissionMap =
7241                        p.tree ? mSettings.mPermissionTrees
7242                                : mSettings.mPermissions;
7243                BasePermission bp = permissionMap.get(p.info.name);
7244
7245                // Allow system apps to redefine non-system permissions
7246                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7247                    final boolean currentOwnerIsSystem = (bp.perm != null
7248                            && isSystemApp(bp.perm.owner));
7249                    if (isSystemApp(p.owner)) {
7250                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7251                            // It's a built-in permission and no owner, take ownership now
7252                            bp.packageSetting = pkgSetting;
7253                            bp.perm = p;
7254                            bp.uid = pkg.applicationInfo.uid;
7255                            bp.sourcePackage = p.info.packageName;
7256                        } else if (!currentOwnerIsSystem) {
7257                            String msg = "New decl " + p.owner + " of permission  "
7258                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7259                            reportSettingsProblem(Log.WARN, msg);
7260                            bp = null;
7261                        }
7262                    }
7263                }
7264
7265                if (bp == null) {
7266                    bp = new BasePermission(p.info.name, p.info.packageName,
7267                            BasePermission.TYPE_NORMAL);
7268                    permissionMap.put(p.info.name, bp);
7269                }
7270
7271                if (bp.perm == null) {
7272                    if (bp.sourcePackage == null
7273                            || bp.sourcePackage.equals(p.info.packageName)) {
7274                        BasePermission tree = findPermissionTreeLP(p.info.name);
7275                        if (tree == null
7276                                || tree.sourcePackage.equals(p.info.packageName)) {
7277                            bp.packageSetting = pkgSetting;
7278                            bp.perm = p;
7279                            bp.uid = pkg.applicationInfo.uid;
7280                            bp.sourcePackage = p.info.packageName;
7281                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7282                                if (r == null) {
7283                                    r = new StringBuilder(256);
7284                                } else {
7285                                    r.append(' ');
7286                                }
7287                                r.append(p.info.name);
7288                            }
7289                        } else {
7290                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7291                                    + p.info.packageName + " ignored: base tree "
7292                                    + tree.name + " is from package "
7293                                    + tree.sourcePackage);
7294                        }
7295                    } else {
7296                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7297                                + p.info.packageName + " ignored: original from "
7298                                + bp.sourcePackage);
7299                    }
7300                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7301                    if (r == null) {
7302                        r = new StringBuilder(256);
7303                    } else {
7304                        r.append(' ');
7305                    }
7306                    r.append("DUP:");
7307                    r.append(p.info.name);
7308                }
7309                if (bp.perm == p) {
7310                    bp.protectionLevel = p.info.protectionLevel;
7311                }
7312            }
7313
7314            if (r != null) {
7315                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7316            }
7317
7318            N = pkg.instrumentation.size();
7319            r = null;
7320            for (i=0; i<N; i++) {
7321                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7322                a.info.packageName = pkg.applicationInfo.packageName;
7323                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7324                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7325                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7326                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7327                a.info.dataDir = pkg.applicationInfo.dataDir;
7328
7329                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7330                // need other information about the application, like the ABI and what not ?
7331                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7332                mInstrumentation.put(a.getComponentName(), a);
7333                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7334                    if (r == null) {
7335                        r = new StringBuilder(256);
7336                    } else {
7337                        r.append(' ');
7338                    }
7339                    r.append(a.info.name);
7340                }
7341            }
7342            if (r != null) {
7343                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7344            }
7345
7346            if (pkg.protectedBroadcasts != null) {
7347                N = pkg.protectedBroadcasts.size();
7348                for (i=0; i<N; i++) {
7349                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7350                }
7351            }
7352
7353            pkgSetting.setTimeStamp(scanFileTime);
7354
7355            // Create idmap files for pairs of (packages, overlay packages).
7356            // Note: "android", ie framework-res.apk, is handled by native layers.
7357            if (pkg.mOverlayTarget != null) {
7358                // This is an overlay package.
7359                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7360                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7361                        mOverlays.put(pkg.mOverlayTarget,
7362                                new ArrayMap<String, PackageParser.Package>());
7363                    }
7364                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7365                    map.put(pkg.packageName, pkg);
7366                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7367                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7368                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7369                                "scanPackageLI failed to createIdmap");
7370                    }
7371                }
7372            } else if (mOverlays.containsKey(pkg.packageName) &&
7373                    !pkg.packageName.equals("android")) {
7374                // This is a regular package, with one or more known overlay packages.
7375                createIdmapsForPackageLI(pkg);
7376            }
7377        }
7378
7379        return pkg;
7380    }
7381
7382    /**
7383     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7384     * is derived purely on the basis of the contents of {@code scanFile} and
7385     * {@code cpuAbiOverride}.
7386     *
7387     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7388     */
7389    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7390                                 String cpuAbiOverride, boolean extractLibs)
7391            throws PackageManagerException {
7392        // TODO: We can probably be smarter about this stuff. For installed apps,
7393        // we can calculate this information at install time once and for all. For
7394        // system apps, we can probably assume that this information doesn't change
7395        // after the first boot scan. As things stand, we do lots of unnecessary work.
7396
7397        // Give ourselves some initial paths; we'll come back for another
7398        // pass once we've determined ABI below.
7399        setNativeLibraryPaths(pkg);
7400
7401        // We would never need to extract libs for forward-locked and external packages,
7402        // since the container service will do it for us. We shouldn't attempt to
7403        // extract libs from system app when it was not updated.
7404        if (pkg.isForwardLocked() || isExternal(pkg) ||
7405            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7406            extractLibs = false;
7407        }
7408
7409        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7410        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7411
7412        NativeLibraryHelper.Handle handle = null;
7413        try {
7414            handle = NativeLibraryHelper.Handle.create(pkg);
7415            // TODO(multiArch): This can be null for apps that didn't go through the
7416            // usual installation process. We can calculate it again, like we
7417            // do during install time.
7418            //
7419            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7420            // unnecessary.
7421            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7422
7423            // Null out the abis so that they can be recalculated.
7424            pkg.applicationInfo.primaryCpuAbi = null;
7425            pkg.applicationInfo.secondaryCpuAbi = null;
7426            if (isMultiArch(pkg.applicationInfo)) {
7427                // Warn if we've set an abiOverride for multi-lib packages..
7428                // By definition, we need to copy both 32 and 64 bit libraries for
7429                // such packages.
7430                if (pkg.cpuAbiOverride != null
7431                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7432                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7433                }
7434
7435                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7436                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7437                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7438                    if (extractLibs) {
7439                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7440                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7441                                useIsaSpecificSubdirs);
7442                    } else {
7443                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7444                    }
7445                }
7446
7447                maybeThrowExceptionForMultiArchCopy(
7448                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7449
7450                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7451                    if (extractLibs) {
7452                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7453                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7454                                useIsaSpecificSubdirs);
7455                    } else {
7456                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7457                    }
7458                }
7459
7460                maybeThrowExceptionForMultiArchCopy(
7461                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7462
7463                if (abi64 >= 0) {
7464                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7465                }
7466
7467                if (abi32 >= 0) {
7468                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7469                    if (abi64 >= 0) {
7470                        pkg.applicationInfo.secondaryCpuAbi = abi;
7471                    } else {
7472                        pkg.applicationInfo.primaryCpuAbi = abi;
7473                    }
7474                }
7475            } else {
7476                String[] abiList = (cpuAbiOverride != null) ?
7477                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7478
7479                // Enable gross and lame hacks for apps that are built with old
7480                // SDK tools. We must scan their APKs for renderscript bitcode and
7481                // not launch them if it's present. Don't bother checking on devices
7482                // that don't have 64 bit support.
7483                boolean needsRenderScriptOverride = false;
7484                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7485                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7486                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7487                    needsRenderScriptOverride = true;
7488                }
7489
7490                final int copyRet;
7491                if (extractLibs) {
7492                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7493                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7494                } else {
7495                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7496                }
7497
7498                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7499                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7500                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7501                }
7502
7503                if (copyRet >= 0) {
7504                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7505                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7506                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7507                } else if (needsRenderScriptOverride) {
7508                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7509                }
7510            }
7511        } catch (IOException ioe) {
7512            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7513        } finally {
7514            IoUtils.closeQuietly(handle);
7515        }
7516
7517        // Now that we've calculated the ABIs and determined if it's an internal app,
7518        // we will go ahead and populate the nativeLibraryPath.
7519        setNativeLibraryPaths(pkg);
7520    }
7521
7522    /**
7523     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7524     * i.e, so that all packages can be run inside a single process if required.
7525     *
7526     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7527     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7528     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7529     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7530     * updating a package that belongs to a shared user.
7531     *
7532     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7533     * adds unnecessary complexity.
7534     */
7535    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7536            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7537        String requiredInstructionSet = null;
7538        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7539            requiredInstructionSet = VMRuntime.getInstructionSet(
7540                     scannedPackage.applicationInfo.primaryCpuAbi);
7541        }
7542
7543        PackageSetting requirer = null;
7544        for (PackageSetting ps : packagesForUser) {
7545            // If packagesForUser contains scannedPackage, we skip it. This will happen
7546            // when scannedPackage is an update of an existing package. Without this check,
7547            // we will never be able to change the ABI of any package belonging to a shared
7548            // user, even if it's compatible with other packages.
7549            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7550                if (ps.primaryCpuAbiString == null) {
7551                    continue;
7552                }
7553
7554                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7555                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7556                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7557                    // this but there's not much we can do.
7558                    String errorMessage = "Instruction set mismatch, "
7559                            + ((requirer == null) ? "[caller]" : requirer)
7560                            + " requires " + requiredInstructionSet + " whereas " + ps
7561                            + " requires " + instructionSet;
7562                    Slog.w(TAG, errorMessage);
7563                }
7564
7565                if (requiredInstructionSet == null) {
7566                    requiredInstructionSet = instructionSet;
7567                    requirer = ps;
7568                }
7569            }
7570        }
7571
7572        if (requiredInstructionSet != null) {
7573            String adjustedAbi;
7574            if (requirer != null) {
7575                // requirer != null implies that either scannedPackage was null or that scannedPackage
7576                // did not require an ABI, in which case we have to adjust scannedPackage to match
7577                // the ABI of the set (which is the same as requirer's ABI)
7578                adjustedAbi = requirer.primaryCpuAbiString;
7579                if (scannedPackage != null) {
7580                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7581                }
7582            } else {
7583                // requirer == null implies that we're updating all ABIs in the set to
7584                // match scannedPackage.
7585                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7586            }
7587
7588            for (PackageSetting ps : packagesForUser) {
7589                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7590                    if (ps.primaryCpuAbiString != null) {
7591                        continue;
7592                    }
7593
7594                    ps.primaryCpuAbiString = adjustedAbi;
7595                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7596                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7597                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7598
7599                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7600                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7601                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7602                            ps.primaryCpuAbiString = null;
7603                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7604                            return;
7605                        } else {
7606                            mInstaller.rmdex(ps.codePathString,
7607                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7608                        }
7609                    }
7610                }
7611            }
7612        }
7613    }
7614
7615    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7616        synchronized (mPackages) {
7617            mResolverReplaced = true;
7618            // Set up information for custom user intent resolution activity.
7619            mResolveActivity.applicationInfo = pkg.applicationInfo;
7620            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7621            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7622            mResolveActivity.processName = pkg.applicationInfo.packageName;
7623            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7624            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7625                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7626            mResolveActivity.theme = 0;
7627            mResolveActivity.exported = true;
7628            mResolveActivity.enabled = true;
7629            mResolveInfo.activityInfo = mResolveActivity;
7630            mResolveInfo.priority = 0;
7631            mResolveInfo.preferredOrder = 0;
7632            mResolveInfo.match = 0;
7633            mResolveComponentName = mCustomResolverComponentName;
7634            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7635                    mResolveComponentName);
7636        }
7637    }
7638
7639    private static String calculateBundledApkRoot(final String codePathString) {
7640        final File codePath = new File(codePathString);
7641        final File codeRoot;
7642        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7643            codeRoot = Environment.getRootDirectory();
7644        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7645            codeRoot = Environment.getOemDirectory();
7646        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7647            codeRoot = Environment.getVendorDirectory();
7648        } else {
7649            // Unrecognized code path; take its top real segment as the apk root:
7650            // e.g. /something/app/blah.apk => /something
7651            try {
7652                File f = codePath.getCanonicalFile();
7653                File parent = f.getParentFile();    // non-null because codePath is a file
7654                File tmp;
7655                while ((tmp = parent.getParentFile()) != null) {
7656                    f = parent;
7657                    parent = tmp;
7658                }
7659                codeRoot = f;
7660                Slog.w(TAG, "Unrecognized code path "
7661                        + codePath + " - using " + codeRoot);
7662            } catch (IOException e) {
7663                // Can't canonicalize the code path -- shenanigans?
7664                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7665                return Environment.getRootDirectory().getPath();
7666            }
7667        }
7668        return codeRoot.getPath();
7669    }
7670
7671    /**
7672     * Derive and set the location of native libraries for the given package,
7673     * which varies depending on where and how the package was installed.
7674     */
7675    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7676        final ApplicationInfo info = pkg.applicationInfo;
7677        final String codePath = pkg.codePath;
7678        final File codeFile = new File(codePath);
7679        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7680        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7681
7682        info.nativeLibraryRootDir = null;
7683        info.nativeLibraryRootRequiresIsa = false;
7684        info.nativeLibraryDir = null;
7685        info.secondaryNativeLibraryDir = null;
7686
7687        if (isApkFile(codeFile)) {
7688            // Monolithic install
7689            if (bundledApp) {
7690                // If "/system/lib64/apkname" exists, assume that is the per-package
7691                // native library directory to use; otherwise use "/system/lib/apkname".
7692                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7693                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7694                        getPrimaryInstructionSet(info));
7695
7696                // This is a bundled system app so choose the path based on the ABI.
7697                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7698                // is just the default path.
7699                final String apkName = deriveCodePathName(codePath);
7700                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7701                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7702                        apkName).getAbsolutePath();
7703
7704                if (info.secondaryCpuAbi != null) {
7705                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7706                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7707                            secondaryLibDir, apkName).getAbsolutePath();
7708                }
7709            } else if (asecApp) {
7710                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7711                        .getAbsolutePath();
7712            } else {
7713                final String apkName = deriveCodePathName(codePath);
7714                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7715                        .getAbsolutePath();
7716            }
7717
7718            info.nativeLibraryRootRequiresIsa = false;
7719            info.nativeLibraryDir = info.nativeLibraryRootDir;
7720        } else {
7721            // Cluster install
7722            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7723            info.nativeLibraryRootRequiresIsa = true;
7724
7725            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7726                    getPrimaryInstructionSet(info)).getAbsolutePath();
7727
7728            if (info.secondaryCpuAbi != null) {
7729                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7730                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7731            }
7732        }
7733    }
7734
7735    /**
7736     * Calculate the abis and roots for a bundled app. These can uniquely
7737     * be determined from the contents of the system partition, i.e whether
7738     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7739     * of this information, and instead assume that the system was built
7740     * sensibly.
7741     */
7742    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7743                                           PackageSetting pkgSetting) {
7744        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7745
7746        // If "/system/lib64/apkname" exists, assume that is the per-package
7747        // native library directory to use; otherwise use "/system/lib/apkname".
7748        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7749        setBundledAppAbi(pkg, apkRoot, apkName);
7750        // pkgSetting might be null during rescan following uninstall of updates
7751        // to a bundled app, so accommodate that possibility.  The settings in
7752        // that case will be established later from the parsed package.
7753        //
7754        // If the settings aren't null, sync them up with what we've just derived.
7755        // note that apkRoot isn't stored in the package settings.
7756        if (pkgSetting != null) {
7757            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7758            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7759        }
7760    }
7761
7762    /**
7763     * Deduces the ABI of a bundled app and sets the relevant fields on the
7764     * parsed pkg object.
7765     *
7766     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7767     *        under which system libraries are installed.
7768     * @param apkName the name of the installed package.
7769     */
7770    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7771        final File codeFile = new File(pkg.codePath);
7772
7773        final boolean has64BitLibs;
7774        final boolean has32BitLibs;
7775        if (isApkFile(codeFile)) {
7776            // Monolithic install
7777            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7778            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7779        } else {
7780            // Cluster install
7781            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7782            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7783                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7784                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7785                has64BitLibs = (new File(rootDir, isa)).exists();
7786            } else {
7787                has64BitLibs = false;
7788            }
7789            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7790                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7791                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7792                has32BitLibs = (new File(rootDir, isa)).exists();
7793            } else {
7794                has32BitLibs = false;
7795            }
7796        }
7797
7798        if (has64BitLibs && !has32BitLibs) {
7799            // The package has 64 bit libs, but not 32 bit libs. Its primary
7800            // ABI should be 64 bit. We can safely assume here that the bundled
7801            // native libraries correspond to the most preferred ABI in the list.
7802
7803            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7804            pkg.applicationInfo.secondaryCpuAbi = null;
7805        } else if (has32BitLibs && !has64BitLibs) {
7806            // The package has 32 bit libs but not 64 bit libs. Its primary
7807            // ABI should be 32 bit.
7808
7809            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7810            pkg.applicationInfo.secondaryCpuAbi = null;
7811        } else if (has32BitLibs && has64BitLibs) {
7812            // The application has both 64 and 32 bit bundled libraries. We check
7813            // here that the app declares multiArch support, and warn if it doesn't.
7814            //
7815            // We will be lenient here and record both ABIs. The primary will be the
7816            // ABI that's higher on the list, i.e, a device that's configured to prefer
7817            // 64 bit apps will see a 64 bit primary ABI,
7818
7819            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7820                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7821            }
7822
7823            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7824                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7825                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7826            } else {
7827                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7828                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7829            }
7830        } else {
7831            pkg.applicationInfo.primaryCpuAbi = null;
7832            pkg.applicationInfo.secondaryCpuAbi = null;
7833        }
7834    }
7835
7836    private void killApplication(String pkgName, int appId, String reason) {
7837        // Request the ActivityManager to kill the process(only for existing packages)
7838        // so that we do not end up in a confused state while the user is still using the older
7839        // version of the application while the new one gets installed.
7840        IActivityManager am = ActivityManagerNative.getDefault();
7841        if (am != null) {
7842            try {
7843                am.killApplicationWithAppId(pkgName, appId, reason);
7844            } catch (RemoteException e) {
7845            }
7846        }
7847    }
7848
7849    void removePackageLI(PackageSetting ps, boolean chatty) {
7850        if (DEBUG_INSTALL) {
7851            if (chatty)
7852                Log.d(TAG, "Removing package " + ps.name);
7853        }
7854
7855        // writer
7856        synchronized (mPackages) {
7857            mPackages.remove(ps.name);
7858            final PackageParser.Package pkg = ps.pkg;
7859            if (pkg != null) {
7860                cleanPackageDataStructuresLILPw(pkg, chatty);
7861            }
7862        }
7863    }
7864
7865    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7866        if (DEBUG_INSTALL) {
7867            if (chatty)
7868                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7869        }
7870
7871        // writer
7872        synchronized (mPackages) {
7873            mPackages.remove(pkg.applicationInfo.packageName);
7874            cleanPackageDataStructuresLILPw(pkg, chatty);
7875        }
7876    }
7877
7878    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7879        int N = pkg.providers.size();
7880        StringBuilder r = null;
7881        int i;
7882        for (i=0; i<N; i++) {
7883            PackageParser.Provider p = pkg.providers.get(i);
7884            mProviders.removeProvider(p);
7885            if (p.info.authority == null) {
7886
7887                /* There was another ContentProvider with this authority when
7888                 * this app was installed so this authority is null,
7889                 * Ignore it as we don't have to unregister the provider.
7890                 */
7891                continue;
7892            }
7893            String names[] = p.info.authority.split(";");
7894            for (int j = 0; j < names.length; j++) {
7895                if (mProvidersByAuthority.get(names[j]) == p) {
7896                    mProvidersByAuthority.remove(names[j]);
7897                    if (DEBUG_REMOVE) {
7898                        if (chatty)
7899                            Log.d(TAG, "Unregistered content provider: " + names[j]
7900                                    + ", className = " + p.info.name + ", isSyncable = "
7901                                    + p.info.isSyncable);
7902                    }
7903                }
7904            }
7905            if (DEBUG_REMOVE && chatty) {
7906                if (r == null) {
7907                    r = new StringBuilder(256);
7908                } else {
7909                    r.append(' ');
7910                }
7911                r.append(p.info.name);
7912            }
7913        }
7914        if (r != null) {
7915            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7916        }
7917
7918        N = pkg.services.size();
7919        r = null;
7920        for (i=0; i<N; i++) {
7921            PackageParser.Service s = pkg.services.get(i);
7922            mServices.removeService(s);
7923            if (chatty) {
7924                if (r == null) {
7925                    r = new StringBuilder(256);
7926                } else {
7927                    r.append(' ');
7928                }
7929                r.append(s.info.name);
7930            }
7931        }
7932        if (r != null) {
7933            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7934        }
7935
7936        N = pkg.receivers.size();
7937        r = null;
7938        for (i=0; i<N; i++) {
7939            PackageParser.Activity a = pkg.receivers.get(i);
7940            mReceivers.removeActivity(a, "receiver");
7941            if (DEBUG_REMOVE && chatty) {
7942                if (r == null) {
7943                    r = new StringBuilder(256);
7944                } else {
7945                    r.append(' ');
7946                }
7947                r.append(a.info.name);
7948            }
7949        }
7950        if (r != null) {
7951            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7952        }
7953
7954        N = pkg.activities.size();
7955        r = null;
7956        for (i=0; i<N; i++) {
7957            PackageParser.Activity a = pkg.activities.get(i);
7958            mActivities.removeActivity(a, "activity");
7959            if (DEBUG_REMOVE && chatty) {
7960                if (r == null) {
7961                    r = new StringBuilder(256);
7962                } else {
7963                    r.append(' ');
7964                }
7965                r.append(a.info.name);
7966            }
7967        }
7968        if (r != null) {
7969            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7970        }
7971
7972        N = pkg.permissions.size();
7973        r = null;
7974        for (i=0; i<N; i++) {
7975            PackageParser.Permission p = pkg.permissions.get(i);
7976            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7977            if (bp == null) {
7978                bp = mSettings.mPermissionTrees.get(p.info.name);
7979            }
7980            if (bp != null && bp.perm == p) {
7981                bp.perm = null;
7982                if (DEBUG_REMOVE && chatty) {
7983                    if (r == null) {
7984                        r = new StringBuilder(256);
7985                    } else {
7986                        r.append(' ');
7987                    }
7988                    r.append(p.info.name);
7989                }
7990            }
7991            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7992                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7993                if (appOpPerms != null) {
7994                    appOpPerms.remove(pkg.packageName);
7995                }
7996            }
7997        }
7998        if (r != null) {
7999            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8000        }
8001
8002        N = pkg.requestedPermissions.size();
8003        r = null;
8004        for (i=0; i<N; i++) {
8005            String perm = pkg.requestedPermissions.get(i);
8006            BasePermission bp = mSettings.mPermissions.get(perm);
8007            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8008                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8009                if (appOpPerms != null) {
8010                    appOpPerms.remove(pkg.packageName);
8011                    if (appOpPerms.isEmpty()) {
8012                        mAppOpPermissionPackages.remove(perm);
8013                    }
8014                }
8015            }
8016        }
8017        if (r != null) {
8018            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8019        }
8020
8021        N = pkg.instrumentation.size();
8022        r = null;
8023        for (i=0; i<N; i++) {
8024            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8025            mInstrumentation.remove(a.getComponentName());
8026            if (DEBUG_REMOVE && chatty) {
8027                if (r == null) {
8028                    r = new StringBuilder(256);
8029                } else {
8030                    r.append(' ');
8031                }
8032                r.append(a.info.name);
8033            }
8034        }
8035        if (r != null) {
8036            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8037        }
8038
8039        r = null;
8040        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8041            // Only system apps can hold shared libraries.
8042            if (pkg.libraryNames != null) {
8043                for (i=0; i<pkg.libraryNames.size(); i++) {
8044                    String name = pkg.libraryNames.get(i);
8045                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8046                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8047                        mSharedLibraries.remove(name);
8048                        if (DEBUG_REMOVE && chatty) {
8049                            if (r == null) {
8050                                r = new StringBuilder(256);
8051                            } else {
8052                                r.append(' ');
8053                            }
8054                            r.append(name);
8055                        }
8056                    }
8057                }
8058            }
8059        }
8060        if (r != null) {
8061            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8062        }
8063    }
8064
8065    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8066        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8067            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8068                return true;
8069            }
8070        }
8071        return false;
8072    }
8073
8074    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8075    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8076    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8077
8078    private void updatePermissionsLPw(String changingPkg,
8079            PackageParser.Package pkgInfo, int flags) {
8080        // Make sure there are no dangling permission trees.
8081        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8082        while (it.hasNext()) {
8083            final BasePermission bp = it.next();
8084            if (bp.packageSetting == null) {
8085                // We may not yet have parsed the package, so just see if
8086                // we still know about its settings.
8087                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8088            }
8089            if (bp.packageSetting == null) {
8090                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8091                        + " from package " + bp.sourcePackage);
8092                it.remove();
8093            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8094                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8095                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8096                            + " from package " + bp.sourcePackage);
8097                    flags |= UPDATE_PERMISSIONS_ALL;
8098                    it.remove();
8099                }
8100            }
8101        }
8102
8103        // Make sure all dynamic permissions have been assigned to a package,
8104        // and make sure there are no dangling permissions.
8105        it = mSettings.mPermissions.values().iterator();
8106        while (it.hasNext()) {
8107            final BasePermission bp = it.next();
8108            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8109                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8110                        + bp.name + " pkg=" + bp.sourcePackage
8111                        + " info=" + bp.pendingInfo);
8112                if (bp.packageSetting == null && bp.pendingInfo != null) {
8113                    final BasePermission tree = findPermissionTreeLP(bp.name);
8114                    if (tree != null && tree.perm != null) {
8115                        bp.packageSetting = tree.packageSetting;
8116                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8117                                new PermissionInfo(bp.pendingInfo));
8118                        bp.perm.info.packageName = tree.perm.info.packageName;
8119                        bp.perm.info.name = bp.name;
8120                        bp.uid = tree.uid;
8121                    }
8122                }
8123            }
8124            if (bp.packageSetting == null) {
8125                // We may not yet have parsed the package, so just see if
8126                // we still know about its settings.
8127                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8128            }
8129            if (bp.packageSetting == null) {
8130                Slog.w(TAG, "Removing dangling permission: " + bp.name
8131                        + " from package " + bp.sourcePackage);
8132                it.remove();
8133            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8134                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8135                    Slog.i(TAG, "Removing old permission: " + bp.name
8136                            + " from package " + bp.sourcePackage);
8137                    flags |= UPDATE_PERMISSIONS_ALL;
8138                    it.remove();
8139                }
8140            }
8141        }
8142
8143        // Now update the permissions for all packages, in particular
8144        // replace the granted permissions of the system packages.
8145        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8146            for (PackageParser.Package pkg : mPackages.values()) {
8147                if (pkg != pkgInfo) {
8148                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8149                            changingPkg);
8150                }
8151            }
8152        }
8153
8154        if (pkgInfo != null) {
8155            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8156        }
8157    }
8158
8159    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8160            String packageOfInterest) {
8161        // IMPORTANT: There are two types of permissions: install and runtime.
8162        // Install time permissions are granted when the app is installed to
8163        // all device users and users added in the future. Runtime permissions
8164        // are granted at runtime explicitly to specific users. Normal and signature
8165        // protected permissions are install time permissions. Dangerous permissions
8166        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8167        // otherwise they are runtime permissions. This function does not manage
8168        // runtime permissions except for the case an app targeting Lollipop MR1
8169        // being upgraded to target a newer SDK, in which case dangerous permissions
8170        // are transformed from install time to runtime ones.
8171
8172        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8173        if (ps == null) {
8174            return;
8175        }
8176
8177        PermissionsState permissionsState = ps.getPermissionsState();
8178        PermissionsState origPermissions = permissionsState;
8179
8180        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8181
8182        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8183
8184        boolean changedInstallPermission = false;
8185
8186        if (replace) {
8187            ps.installPermissionsFixed = false;
8188            if (!ps.isSharedUser()) {
8189                origPermissions = new PermissionsState(permissionsState);
8190                permissionsState.reset();
8191            }
8192        }
8193
8194        permissionsState.setGlobalGids(mGlobalGids);
8195
8196        final int N = pkg.requestedPermissions.size();
8197        for (int i=0; i<N; i++) {
8198            final String name = pkg.requestedPermissions.get(i);
8199            final BasePermission bp = mSettings.mPermissions.get(name);
8200
8201            if (DEBUG_INSTALL) {
8202                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8203            }
8204
8205            if (bp == null || bp.packageSetting == null) {
8206                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8207                    Slog.w(TAG, "Unknown permission " + name
8208                            + " in package " + pkg.packageName);
8209                }
8210                continue;
8211            }
8212
8213            final String perm = bp.name;
8214            boolean allowedSig = false;
8215            int grant = GRANT_DENIED;
8216
8217            // Keep track of app op permissions.
8218            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8219                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8220                if (pkgs == null) {
8221                    pkgs = new ArraySet<>();
8222                    mAppOpPermissionPackages.put(bp.name, pkgs);
8223                }
8224                pkgs.add(pkg.packageName);
8225            }
8226
8227            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8228            switch (level) {
8229                case PermissionInfo.PROTECTION_NORMAL: {
8230                    // For all apps normal permissions are install time ones.
8231                    grant = GRANT_INSTALL;
8232                } break;
8233
8234                case PermissionInfo.PROTECTION_DANGEROUS: {
8235                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8236                        // For legacy apps dangerous permissions are install time ones.
8237                        grant = GRANT_INSTALL_LEGACY;
8238                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8239                        // For legacy apps that became modern, install becomes runtime.
8240                        grant = GRANT_UPGRADE;
8241                    } else {
8242                        // For modern apps keep runtime permissions unchanged.
8243                        grant = GRANT_RUNTIME;
8244                    }
8245                } break;
8246
8247                case PermissionInfo.PROTECTION_SIGNATURE: {
8248                    // For all apps signature permissions are install time ones.
8249                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8250                    if (allowedSig) {
8251                        grant = GRANT_INSTALL;
8252                    }
8253                } break;
8254            }
8255
8256            if (DEBUG_INSTALL) {
8257                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8258            }
8259
8260            if (grant != GRANT_DENIED) {
8261                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8262                    // If this is an existing, non-system package, then
8263                    // we can't add any new permissions to it.
8264                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8265                        // Except...  if this is a permission that was added
8266                        // to the platform (note: need to only do this when
8267                        // updating the platform).
8268                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8269                            grant = GRANT_DENIED;
8270                        }
8271                    }
8272                }
8273
8274                switch (grant) {
8275                    case GRANT_INSTALL: {
8276                        // Revoke this as runtime permission to handle the case of
8277                        // a runtime permission being downgraded to an install one.
8278                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8279                            if (origPermissions.getRuntimePermissionState(
8280                                    bp.name, userId) != null) {
8281                                // Revoke the runtime permission and clear the flags.
8282                                origPermissions.revokeRuntimePermission(bp, userId);
8283                                origPermissions.updatePermissionFlags(bp, userId,
8284                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8285                                // If we revoked a permission permission, we have to write.
8286                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8287                                        changedRuntimePermissionUserIds, userId);
8288                            }
8289                        }
8290                        // Grant an install permission.
8291                        if (permissionsState.grantInstallPermission(bp) !=
8292                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8293                            changedInstallPermission = true;
8294                        }
8295                    } break;
8296
8297                    case GRANT_INSTALL_LEGACY: {
8298                        // Grant an install permission.
8299                        if (permissionsState.grantInstallPermission(bp) !=
8300                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8301                            changedInstallPermission = true;
8302                        }
8303                    } break;
8304
8305                    case GRANT_RUNTIME: {
8306                        // Grant previously granted runtime permissions.
8307                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8308                            PermissionState permissionState = origPermissions
8309                                    .getRuntimePermissionState(bp.name, userId);
8310                            final int flags = permissionState != null
8311                                    ? permissionState.getFlags() : 0;
8312                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8313                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8314                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8315                                    // If we cannot put the permission as it was, we have to write.
8316                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8317                                            changedRuntimePermissionUserIds, userId);
8318                                }
8319                            }
8320                            // Propagate the permission flags.
8321                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8322                        }
8323                    } break;
8324
8325                    case GRANT_UPGRADE: {
8326                        // Grant runtime permissions for a previously held install permission.
8327                        PermissionState permissionState = origPermissions
8328                                .getInstallPermissionState(bp.name);
8329                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8330
8331                        if (origPermissions.revokeInstallPermission(bp)
8332                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8333                            // We will be transferring the permission flags, so clear them.
8334                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8335                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8336                            changedInstallPermission = true;
8337                        }
8338
8339                        // If the permission is not to be promoted to runtime we ignore it and
8340                        // also its other flags as they are not applicable to install permissions.
8341                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8342                            for (int userId : currentUserIds) {
8343                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8344                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8345                                    // Transfer the permission flags.
8346                                    permissionsState.updatePermissionFlags(bp, userId,
8347                                            flags, flags);
8348                                    // If we granted the permission, we have to write.
8349                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8350                                            changedRuntimePermissionUserIds, userId);
8351                                }
8352                            }
8353                        }
8354                    } break;
8355
8356                    default: {
8357                        if (packageOfInterest == null
8358                                || packageOfInterest.equals(pkg.packageName)) {
8359                            Slog.w(TAG, "Not granting permission " + perm
8360                                    + " to package " + pkg.packageName
8361                                    + " because it was previously installed without");
8362                        }
8363                    } break;
8364                }
8365            } else {
8366                if (permissionsState.revokeInstallPermission(bp) !=
8367                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8368                    // Also drop the permission flags.
8369                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8370                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8371                    changedInstallPermission = true;
8372                    Slog.i(TAG, "Un-granting permission " + perm
8373                            + " from package " + pkg.packageName
8374                            + " (protectionLevel=" + bp.protectionLevel
8375                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8376                            + ")");
8377                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8378                    // Don't print warning for app op permissions, since it is fine for them
8379                    // not to be granted, there is a UI for the user to decide.
8380                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8381                        Slog.w(TAG, "Not granting permission " + perm
8382                                + " to package " + pkg.packageName
8383                                + " (protectionLevel=" + bp.protectionLevel
8384                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8385                                + ")");
8386                    }
8387                }
8388            }
8389        }
8390
8391        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8392                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8393            // This is the first that we have heard about this package, so the
8394            // permissions we have now selected are fixed until explicitly
8395            // changed.
8396            ps.installPermissionsFixed = true;
8397        }
8398
8399        // Persist the runtime permissions state for users with changes.
8400        for (int userId : changedRuntimePermissionUserIds) {
8401            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8402        }
8403    }
8404
8405    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8406        boolean allowed = false;
8407        final int NP = PackageParser.NEW_PERMISSIONS.length;
8408        for (int ip=0; ip<NP; ip++) {
8409            final PackageParser.NewPermissionInfo npi
8410                    = PackageParser.NEW_PERMISSIONS[ip];
8411            if (npi.name.equals(perm)
8412                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8413                allowed = true;
8414                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8415                        + pkg.packageName);
8416                break;
8417            }
8418        }
8419        return allowed;
8420    }
8421
8422    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8423            BasePermission bp, PermissionsState origPermissions) {
8424        boolean allowed;
8425        allowed = (compareSignatures(
8426                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8427                        == PackageManager.SIGNATURE_MATCH)
8428                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8429                        == PackageManager.SIGNATURE_MATCH);
8430        if (!allowed && (bp.protectionLevel
8431                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8432            if (isSystemApp(pkg)) {
8433                // For updated system applications, a system permission
8434                // is granted only if it had been defined by the original application.
8435                if (pkg.isUpdatedSystemApp()) {
8436                    final PackageSetting sysPs = mSettings
8437                            .getDisabledSystemPkgLPr(pkg.packageName);
8438                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8439                        // If the original was granted this permission, we take
8440                        // that grant decision as read and propagate it to the
8441                        // update.
8442                        if (sysPs.isPrivileged()) {
8443                            allowed = true;
8444                        }
8445                    } else {
8446                        // The system apk may have been updated with an older
8447                        // version of the one on the data partition, but which
8448                        // granted a new system permission that it didn't have
8449                        // before.  In this case we do want to allow the app to
8450                        // now get the new permission if the ancestral apk is
8451                        // privileged to get it.
8452                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8453                            for (int j=0;
8454                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8455                                if (perm.equals(
8456                                        sysPs.pkg.requestedPermissions.get(j))) {
8457                                    allowed = true;
8458                                    break;
8459                                }
8460                            }
8461                        }
8462                    }
8463                } else {
8464                    allowed = isPrivilegedApp(pkg);
8465                }
8466            }
8467        }
8468        if (!allowed) {
8469            if (!allowed && (bp.protectionLevel
8470                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8471                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8472                // If this was a previously normal/dangerous permission that got moved
8473                // to a system permission as part of the runtime permission redesign, then
8474                // we still want to blindly grant it to old apps.
8475                allowed = true;
8476            }
8477            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8478                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8479                // If this permission is to be granted to the system installer and
8480                // this app is an installer, then it gets the permission.
8481                allowed = true;
8482            }
8483            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8484                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8485                // If this permission is to be granted to the system verifier and
8486                // this app is a verifier, then it gets the permission.
8487                allowed = true;
8488            }
8489            if (!allowed && (bp.protectionLevel
8490                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8491                    && isSystemApp(pkg)) {
8492                // Any pre-installed system app is allowed to get this permission.
8493                allowed = true;
8494            }
8495            if (!allowed && (bp.protectionLevel
8496                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8497                // For development permissions, a development permission
8498                // is granted only if it was already granted.
8499                allowed = origPermissions.hasInstallPermission(perm);
8500            }
8501        }
8502        return allowed;
8503    }
8504
8505    final class ActivityIntentResolver
8506            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8507        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8508                boolean defaultOnly, int userId) {
8509            if (!sUserManager.exists(userId)) return null;
8510            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8511            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8512        }
8513
8514        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8515                int userId) {
8516            if (!sUserManager.exists(userId)) return null;
8517            mFlags = flags;
8518            return super.queryIntent(intent, resolvedType,
8519                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8520        }
8521
8522        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8523                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8524            if (!sUserManager.exists(userId)) return null;
8525            if (packageActivities == null) {
8526                return null;
8527            }
8528            mFlags = flags;
8529            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8530            final int N = packageActivities.size();
8531            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8532                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8533
8534            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8535            for (int i = 0; i < N; ++i) {
8536                intentFilters = packageActivities.get(i).intents;
8537                if (intentFilters != null && intentFilters.size() > 0) {
8538                    PackageParser.ActivityIntentInfo[] array =
8539                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8540                    intentFilters.toArray(array);
8541                    listCut.add(array);
8542                }
8543            }
8544            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8545        }
8546
8547        public final void addActivity(PackageParser.Activity a, String type) {
8548            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8549            mActivities.put(a.getComponentName(), a);
8550            if (DEBUG_SHOW_INFO)
8551                Log.v(
8552                TAG, "  " + type + " " +
8553                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8554            if (DEBUG_SHOW_INFO)
8555                Log.v(TAG, "    Class=" + a.info.name);
8556            final int NI = a.intents.size();
8557            for (int j=0; j<NI; j++) {
8558                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8559                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8560                    intent.setPriority(0);
8561                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8562                            + a.className + " with priority > 0, forcing to 0");
8563                }
8564                if (DEBUG_SHOW_INFO) {
8565                    Log.v(TAG, "    IntentFilter:");
8566                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8567                }
8568                if (!intent.debugCheck()) {
8569                    Log.w(TAG, "==> For Activity " + a.info.name);
8570                }
8571                addFilter(intent);
8572            }
8573        }
8574
8575        public final void removeActivity(PackageParser.Activity a, String type) {
8576            mActivities.remove(a.getComponentName());
8577            if (DEBUG_SHOW_INFO) {
8578                Log.v(TAG, "  " + type + " "
8579                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8580                                : a.info.name) + ":");
8581                Log.v(TAG, "    Class=" + a.info.name);
8582            }
8583            final int NI = a.intents.size();
8584            for (int j=0; j<NI; j++) {
8585                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8586                if (DEBUG_SHOW_INFO) {
8587                    Log.v(TAG, "    IntentFilter:");
8588                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8589                }
8590                removeFilter(intent);
8591            }
8592        }
8593
8594        @Override
8595        protected boolean allowFilterResult(
8596                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8597            ActivityInfo filterAi = filter.activity.info;
8598            for (int i=dest.size()-1; i>=0; i--) {
8599                ActivityInfo destAi = dest.get(i).activityInfo;
8600                if (destAi.name == filterAi.name
8601                        && destAi.packageName == filterAi.packageName) {
8602                    return false;
8603                }
8604            }
8605            return true;
8606        }
8607
8608        @Override
8609        protected ActivityIntentInfo[] newArray(int size) {
8610            return new ActivityIntentInfo[size];
8611        }
8612
8613        @Override
8614        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8615            if (!sUserManager.exists(userId)) return true;
8616            PackageParser.Package p = filter.activity.owner;
8617            if (p != null) {
8618                PackageSetting ps = (PackageSetting)p.mExtras;
8619                if (ps != null) {
8620                    // System apps are never considered stopped for purposes of
8621                    // filtering, because there may be no way for the user to
8622                    // actually re-launch them.
8623                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8624                            && ps.getStopped(userId);
8625                }
8626            }
8627            return false;
8628        }
8629
8630        @Override
8631        protected boolean isPackageForFilter(String packageName,
8632                PackageParser.ActivityIntentInfo info) {
8633            return packageName.equals(info.activity.owner.packageName);
8634        }
8635
8636        @Override
8637        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8638                int match, int userId) {
8639            if (!sUserManager.exists(userId)) return null;
8640            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8641                return null;
8642            }
8643            final PackageParser.Activity activity = info.activity;
8644            if (mSafeMode && (activity.info.applicationInfo.flags
8645                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8646                return null;
8647            }
8648            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8649            if (ps == null) {
8650                return null;
8651            }
8652            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8653                    ps.readUserState(userId), userId);
8654            if (ai == null) {
8655                return null;
8656            }
8657            final ResolveInfo res = new ResolveInfo();
8658            res.activityInfo = ai;
8659            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8660                res.filter = info;
8661            }
8662            if (info != null) {
8663                res.handleAllWebDataURI = info.handleAllWebDataURI();
8664            }
8665            res.priority = info.getPriority();
8666            res.preferredOrder = activity.owner.mPreferredOrder;
8667            //System.out.println("Result: " + res.activityInfo.className +
8668            //                   " = " + res.priority);
8669            res.match = match;
8670            res.isDefault = info.hasDefault;
8671            res.labelRes = info.labelRes;
8672            res.nonLocalizedLabel = info.nonLocalizedLabel;
8673            if (userNeedsBadging(userId)) {
8674                res.noResourceId = true;
8675            } else {
8676                res.icon = info.icon;
8677            }
8678            res.iconResourceId = info.icon;
8679            res.system = res.activityInfo.applicationInfo.isSystemApp();
8680            return res;
8681        }
8682
8683        @Override
8684        protected void sortResults(List<ResolveInfo> results) {
8685            Collections.sort(results, mResolvePrioritySorter);
8686        }
8687
8688        @Override
8689        protected void dumpFilter(PrintWriter out, String prefix,
8690                PackageParser.ActivityIntentInfo filter) {
8691            out.print(prefix); out.print(
8692                    Integer.toHexString(System.identityHashCode(filter.activity)));
8693                    out.print(' ');
8694                    filter.activity.printComponentShortName(out);
8695                    out.print(" filter ");
8696                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8697        }
8698
8699        @Override
8700        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8701            return filter.activity;
8702        }
8703
8704        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8705            PackageParser.Activity activity = (PackageParser.Activity)label;
8706            out.print(prefix); out.print(
8707                    Integer.toHexString(System.identityHashCode(activity)));
8708                    out.print(' ');
8709                    activity.printComponentShortName(out);
8710            if (count > 1) {
8711                out.print(" ("); out.print(count); out.print(" filters)");
8712            }
8713            out.println();
8714        }
8715
8716//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8717//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8718//            final List<ResolveInfo> retList = Lists.newArrayList();
8719//            while (i.hasNext()) {
8720//                final ResolveInfo resolveInfo = i.next();
8721//                if (isEnabledLP(resolveInfo.activityInfo)) {
8722//                    retList.add(resolveInfo);
8723//                }
8724//            }
8725//            return retList;
8726//        }
8727
8728        // Keys are String (activity class name), values are Activity.
8729        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8730                = new ArrayMap<ComponentName, PackageParser.Activity>();
8731        private int mFlags;
8732    }
8733
8734    private final class ServiceIntentResolver
8735            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8736        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8737                boolean defaultOnly, int userId) {
8738            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8739            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8740        }
8741
8742        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8743                int userId) {
8744            if (!sUserManager.exists(userId)) return null;
8745            mFlags = flags;
8746            return super.queryIntent(intent, resolvedType,
8747                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8748        }
8749
8750        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8751                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8752            if (!sUserManager.exists(userId)) return null;
8753            if (packageServices == null) {
8754                return null;
8755            }
8756            mFlags = flags;
8757            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8758            final int N = packageServices.size();
8759            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8760                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8761
8762            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8763            for (int i = 0; i < N; ++i) {
8764                intentFilters = packageServices.get(i).intents;
8765                if (intentFilters != null && intentFilters.size() > 0) {
8766                    PackageParser.ServiceIntentInfo[] array =
8767                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8768                    intentFilters.toArray(array);
8769                    listCut.add(array);
8770                }
8771            }
8772            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8773        }
8774
8775        public final void addService(PackageParser.Service s) {
8776            mServices.put(s.getComponentName(), s);
8777            if (DEBUG_SHOW_INFO) {
8778                Log.v(TAG, "  "
8779                        + (s.info.nonLocalizedLabel != null
8780                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8781                Log.v(TAG, "    Class=" + s.info.name);
8782            }
8783            final int NI = s.intents.size();
8784            int j;
8785            for (j=0; j<NI; j++) {
8786                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8787                if (DEBUG_SHOW_INFO) {
8788                    Log.v(TAG, "    IntentFilter:");
8789                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8790                }
8791                if (!intent.debugCheck()) {
8792                    Log.w(TAG, "==> For Service " + s.info.name);
8793                }
8794                addFilter(intent);
8795            }
8796        }
8797
8798        public final void removeService(PackageParser.Service s) {
8799            mServices.remove(s.getComponentName());
8800            if (DEBUG_SHOW_INFO) {
8801                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8802                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8803                Log.v(TAG, "    Class=" + s.info.name);
8804            }
8805            final int NI = s.intents.size();
8806            int j;
8807            for (j=0; j<NI; j++) {
8808                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8809                if (DEBUG_SHOW_INFO) {
8810                    Log.v(TAG, "    IntentFilter:");
8811                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8812                }
8813                removeFilter(intent);
8814            }
8815        }
8816
8817        @Override
8818        protected boolean allowFilterResult(
8819                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8820            ServiceInfo filterSi = filter.service.info;
8821            for (int i=dest.size()-1; i>=0; i--) {
8822                ServiceInfo destAi = dest.get(i).serviceInfo;
8823                if (destAi.name == filterSi.name
8824                        && destAi.packageName == filterSi.packageName) {
8825                    return false;
8826                }
8827            }
8828            return true;
8829        }
8830
8831        @Override
8832        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8833            return new PackageParser.ServiceIntentInfo[size];
8834        }
8835
8836        @Override
8837        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8838            if (!sUserManager.exists(userId)) return true;
8839            PackageParser.Package p = filter.service.owner;
8840            if (p != null) {
8841                PackageSetting ps = (PackageSetting)p.mExtras;
8842                if (ps != null) {
8843                    // System apps are never considered stopped for purposes of
8844                    // filtering, because there may be no way for the user to
8845                    // actually re-launch them.
8846                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8847                            && ps.getStopped(userId);
8848                }
8849            }
8850            return false;
8851        }
8852
8853        @Override
8854        protected boolean isPackageForFilter(String packageName,
8855                PackageParser.ServiceIntentInfo info) {
8856            return packageName.equals(info.service.owner.packageName);
8857        }
8858
8859        @Override
8860        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8861                int match, int userId) {
8862            if (!sUserManager.exists(userId)) return null;
8863            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8864            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8865                return null;
8866            }
8867            final PackageParser.Service service = info.service;
8868            if (mSafeMode && (service.info.applicationInfo.flags
8869                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8870                return null;
8871            }
8872            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8873            if (ps == null) {
8874                return null;
8875            }
8876            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8877                    ps.readUserState(userId), userId);
8878            if (si == null) {
8879                return null;
8880            }
8881            final ResolveInfo res = new ResolveInfo();
8882            res.serviceInfo = si;
8883            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8884                res.filter = filter;
8885            }
8886            res.priority = info.getPriority();
8887            res.preferredOrder = service.owner.mPreferredOrder;
8888            res.match = match;
8889            res.isDefault = info.hasDefault;
8890            res.labelRes = info.labelRes;
8891            res.nonLocalizedLabel = info.nonLocalizedLabel;
8892            res.icon = info.icon;
8893            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8894            return res;
8895        }
8896
8897        @Override
8898        protected void sortResults(List<ResolveInfo> results) {
8899            Collections.sort(results, mResolvePrioritySorter);
8900        }
8901
8902        @Override
8903        protected void dumpFilter(PrintWriter out, String prefix,
8904                PackageParser.ServiceIntentInfo filter) {
8905            out.print(prefix); out.print(
8906                    Integer.toHexString(System.identityHashCode(filter.service)));
8907                    out.print(' ');
8908                    filter.service.printComponentShortName(out);
8909                    out.print(" filter ");
8910                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8911        }
8912
8913        @Override
8914        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8915            return filter.service;
8916        }
8917
8918        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8919            PackageParser.Service service = (PackageParser.Service)label;
8920            out.print(prefix); out.print(
8921                    Integer.toHexString(System.identityHashCode(service)));
8922                    out.print(' ');
8923                    service.printComponentShortName(out);
8924            if (count > 1) {
8925                out.print(" ("); out.print(count); out.print(" filters)");
8926            }
8927            out.println();
8928        }
8929
8930//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8931//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8932//            final List<ResolveInfo> retList = Lists.newArrayList();
8933//            while (i.hasNext()) {
8934//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8935//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8936//                    retList.add(resolveInfo);
8937//                }
8938//            }
8939//            return retList;
8940//        }
8941
8942        // Keys are String (activity class name), values are Activity.
8943        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8944                = new ArrayMap<ComponentName, PackageParser.Service>();
8945        private int mFlags;
8946    };
8947
8948    private final class ProviderIntentResolver
8949            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8950        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8951                boolean defaultOnly, int userId) {
8952            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8953            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8954        }
8955
8956        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8957                int userId) {
8958            if (!sUserManager.exists(userId))
8959                return null;
8960            mFlags = flags;
8961            return super.queryIntent(intent, resolvedType,
8962                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8963        }
8964
8965        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8966                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8967            if (!sUserManager.exists(userId))
8968                return null;
8969            if (packageProviders == null) {
8970                return null;
8971            }
8972            mFlags = flags;
8973            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8974            final int N = packageProviders.size();
8975            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8976                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8977
8978            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8979            for (int i = 0; i < N; ++i) {
8980                intentFilters = packageProviders.get(i).intents;
8981                if (intentFilters != null && intentFilters.size() > 0) {
8982                    PackageParser.ProviderIntentInfo[] array =
8983                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8984                    intentFilters.toArray(array);
8985                    listCut.add(array);
8986                }
8987            }
8988            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8989        }
8990
8991        public final void addProvider(PackageParser.Provider p) {
8992            if (mProviders.containsKey(p.getComponentName())) {
8993                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8994                return;
8995            }
8996
8997            mProviders.put(p.getComponentName(), p);
8998            if (DEBUG_SHOW_INFO) {
8999                Log.v(TAG, "  "
9000                        + (p.info.nonLocalizedLabel != null
9001                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9002                Log.v(TAG, "    Class=" + p.info.name);
9003            }
9004            final int NI = p.intents.size();
9005            int j;
9006            for (j = 0; j < NI; j++) {
9007                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9008                if (DEBUG_SHOW_INFO) {
9009                    Log.v(TAG, "    IntentFilter:");
9010                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9011                }
9012                if (!intent.debugCheck()) {
9013                    Log.w(TAG, "==> For Provider " + p.info.name);
9014                }
9015                addFilter(intent);
9016            }
9017        }
9018
9019        public final void removeProvider(PackageParser.Provider p) {
9020            mProviders.remove(p.getComponentName());
9021            if (DEBUG_SHOW_INFO) {
9022                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9023                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9024                Log.v(TAG, "    Class=" + p.info.name);
9025            }
9026            final int NI = p.intents.size();
9027            int j;
9028            for (j = 0; j < NI; j++) {
9029                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9030                if (DEBUG_SHOW_INFO) {
9031                    Log.v(TAG, "    IntentFilter:");
9032                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9033                }
9034                removeFilter(intent);
9035            }
9036        }
9037
9038        @Override
9039        protected boolean allowFilterResult(
9040                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9041            ProviderInfo filterPi = filter.provider.info;
9042            for (int i = dest.size() - 1; i >= 0; i--) {
9043                ProviderInfo destPi = dest.get(i).providerInfo;
9044                if (destPi.name == filterPi.name
9045                        && destPi.packageName == filterPi.packageName) {
9046                    return false;
9047                }
9048            }
9049            return true;
9050        }
9051
9052        @Override
9053        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9054            return new PackageParser.ProviderIntentInfo[size];
9055        }
9056
9057        @Override
9058        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9059            if (!sUserManager.exists(userId))
9060                return true;
9061            PackageParser.Package p = filter.provider.owner;
9062            if (p != null) {
9063                PackageSetting ps = (PackageSetting) p.mExtras;
9064                if (ps != null) {
9065                    // System apps are never considered stopped for purposes of
9066                    // filtering, because there may be no way for the user to
9067                    // actually re-launch them.
9068                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9069                            && ps.getStopped(userId);
9070                }
9071            }
9072            return false;
9073        }
9074
9075        @Override
9076        protected boolean isPackageForFilter(String packageName,
9077                PackageParser.ProviderIntentInfo info) {
9078            return packageName.equals(info.provider.owner.packageName);
9079        }
9080
9081        @Override
9082        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9083                int match, int userId) {
9084            if (!sUserManager.exists(userId))
9085                return null;
9086            final PackageParser.ProviderIntentInfo info = filter;
9087            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9088                return null;
9089            }
9090            final PackageParser.Provider provider = info.provider;
9091            if (mSafeMode && (provider.info.applicationInfo.flags
9092                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9093                return null;
9094            }
9095            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9096            if (ps == null) {
9097                return null;
9098            }
9099            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9100                    ps.readUserState(userId), userId);
9101            if (pi == null) {
9102                return null;
9103            }
9104            final ResolveInfo res = new ResolveInfo();
9105            res.providerInfo = pi;
9106            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9107                res.filter = filter;
9108            }
9109            res.priority = info.getPriority();
9110            res.preferredOrder = provider.owner.mPreferredOrder;
9111            res.match = match;
9112            res.isDefault = info.hasDefault;
9113            res.labelRes = info.labelRes;
9114            res.nonLocalizedLabel = info.nonLocalizedLabel;
9115            res.icon = info.icon;
9116            res.system = res.providerInfo.applicationInfo.isSystemApp();
9117            return res;
9118        }
9119
9120        @Override
9121        protected void sortResults(List<ResolveInfo> results) {
9122            Collections.sort(results, mResolvePrioritySorter);
9123        }
9124
9125        @Override
9126        protected void dumpFilter(PrintWriter out, String prefix,
9127                PackageParser.ProviderIntentInfo filter) {
9128            out.print(prefix);
9129            out.print(
9130                    Integer.toHexString(System.identityHashCode(filter.provider)));
9131            out.print(' ');
9132            filter.provider.printComponentShortName(out);
9133            out.print(" filter ");
9134            out.println(Integer.toHexString(System.identityHashCode(filter)));
9135        }
9136
9137        @Override
9138        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9139            return filter.provider;
9140        }
9141
9142        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9143            PackageParser.Provider provider = (PackageParser.Provider)label;
9144            out.print(prefix); out.print(
9145                    Integer.toHexString(System.identityHashCode(provider)));
9146                    out.print(' ');
9147                    provider.printComponentShortName(out);
9148            if (count > 1) {
9149                out.print(" ("); out.print(count); out.print(" filters)");
9150            }
9151            out.println();
9152        }
9153
9154        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9155                = new ArrayMap<ComponentName, PackageParser.Provider>();
9156        private int mFlags;
9157    };
9158
9159    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9160            new Comparator<ResolveInfo>() {
9161        public int compare(ResolveInfo r1, ResolveInfo r2) {
9162            int v1 = r1.priority;
9163            int v2 = r2.priority;
9164            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9165            if (v1 != v2) {
9166                return (v1 > v2) ? -1 : 1;
9167            }
9168            v1 = r1.preferredOrder;
9169            v2 = r2.preferredOrder;
9170            if (v1 != v2) {
9171                return (v1 > v2) ? -1 : 1;
9172            }
9173            if (r1.isDefault != r2.isDefault) {
9174                return r1.isDefault ? -1 : 1;
9175            }
9176            v1 = r1.match;
9177            v2 = r2.match;
9178            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9179            if (v1 != v2) {
9180                return (v1 > v2) ? -1 : 1;
9181            }
9182            if (r1.system != r2.system) {
9183                return r1.system ? -1 : 1;
9184            }
9185            return 0;
9186        }
9187    };
9188
9189    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9190            new Comparator<ProviderInfo>() {
9191        public int compare(ProviderInfo p1, ProviderInfo p2) {
9192            final int v1 = p1.initOrder;
9193            final int v2 = p2.initOrder;
9194            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9195        }
9196    };
9197
9198    final void sendPackageBroadcast(final String action, final String pkg,
9199            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9200            final int[] userIds) {
9201        mHandler.post(new Runnable() {
9202            @Override
9203            public void run() {
9204                try {
9205                    final IActivityManager am = ActivityManagerNative.getDefault();
9206                    if (am == null) return;
9207                    final int[] resolvedUserIds;
9208                    if (userIds == null) {
9209                        resolvedUserIds = am.getRunningUserIds();
9210                    } else {
9211                        resolvedUserIds = userIds;
9212                    }
9213                    for (int id : resolvedUserIds) {
9214                        final Intent intent = new Intent(action,
9215                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9216                        if (extras != null) {
9217                            intent.putExtras(extras);
9218                        }
9219                        if (targetPkg != null) {
9220                            intent.setPackage(targetPkg);
9221                        }
9222                        // Modify the UID when posting to other users
9223                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9224                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9225                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9226                            intent.putExtra(Intent.EXTRA_UID, uid);
9227                        }
9228                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9229                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9230                        if (DEBUG_BROADCASTS) {
9231                            RuntimeException here = new RuntimeException("here");
9232                            here.fillInStackTrace();
9233                            Slog.d(TAG, "Sending to user " + id + ": "
9234                                    + intent.toShortString(false, true, false, false)
9235                                    + " " + intent.getExtras(), here);
9236                        }
9237                        am.broadcastIntent(null, intent, null, finishedReceiver,
9238                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9239                                null, finishedReceiver != null, false, id);
9240                    }
9241                } catch (RemoteException ex) {
9242                }
9243            }
9244        });
9245    }
9246
9247    /**
9248     * Check if the external storage media is available. This is true if there
9249     * is a mounted external storage medium or if the external storage is
9250     * emulated.
9251     */
9252    private boolean isExternalMediaAvailable() {
9253        return mMediaMounted || Environment.isExternalStorageEmulated();
9254    }
9255
9256    @Override
9257    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9258        // writer
9259        synchronized (mPackages) {
9260            if (!isExternalMediaAvailable()) {
9261                // If the external storage is no longer mounted at this point,
9262                // the caller may not have been able to delete all of this
9263                // packages files and can not delete any more.  Bail.
9264                return null;
9265            }
9266            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9267            if (lastPackage != null) {
9268                pkgs.remove(lastPackage);
9269            }
9270            if (pkgs.size() > 0) {
9271                return pkgs.get(0);
9272            }
9273        }
9274        return null;
9275    }
9276
9277    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9278        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9279                userId, andCode ? 1 : 0, packageName);
9280        if (mSystemReady) {
9281            msg.sendToTarget();
9282        } else {
9283            if (mPostSystemReadyMessages == null) {
9284                mPostSystemReadyMessages = new ArrayList<>();
9285            }
9286            mPostSystemReadyMessages.add(msg);
9287        }
9288    }
9289
9290    void startCleaningPackages() {
9291        // reader
9292        synchronized (mPackages) {
9293            if (!isExternalMediaAvailable()) {
9294                return;
9295            }
9296            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9297                return;
9298            }
9299        }
9300        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9301        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9302        IActivityManager am = ActivityManagerNative.getDefault();
9303        if (am != null) {
9304            try {
9305                am.startService(null, intent, null, mContext.getOpPackageName(),
9306                        UserHandle.USER_OWNER);
9307            } catch (RemoteException e) {
9308            }
9309        }
9310    }
9311
9312    @Override
9313    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9314            int installFlags, String installerPackageName, VerificationParams verificationParams,
9315            String packageAbiOverride) {
9316        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9317                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9318    }
9319
9320    @Override
9321    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9322            int installFlags, String installerPackageName, VerificationParams verificationParams,
9323            String packageAbiOverride, int userId) {
9324        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9325
9326        final int callingUid = Binder.getCallingUid();
9327        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9328
9329        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9330            try {
9331                if (observer != null) {
9332                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9333                }
9334            } catch (RemoteException re) {
9335            }
9336            return;
9337        }
9338
9339        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9340            installFlags |= PackageManager.INSTALL_FROM_ADB;
9341
9342        } else {
9343            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9344            // about installerPackageName.
9345
9346            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9347            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9348        }
9349
9350        UserHandle user;
9351        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9352            user = UserHandle.ALL;
9353        } else {
9354            user = new UserHandle(userId);
9355        }
9356
9357        // Only system components can circumvent runtime permissions when installing.
9358        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9359                && mContext.checkCallingOrSelfPermission(Manifest.permission
9360                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9361            throw new SecurityException("You need the "
9362                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9363                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9364        }
9365
9366        verificationParams.setInstallerUid(callingUid);
9367
9368        final File originFile = new File(originPath);
9369        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9370
9371        final Message msg = mHandler.obtainMessage(INIT_COPY);
9372        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9373                null, verificationParams, user, packageAbiOverride);
9374        mHandler.sendMessage(msg);
9375    }
9376
9377    void installStage(String packageName, File stagedDir, String stagedCid,
9378            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9379            String installerPackageName, int installerUid, UserHandle user) {
9380        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9381                params.referrerUri, installerUid, null);
9382        verifParams.setInstallerUid(installerUid);
9383
9384        final OriginInfo origin;
9385        if (stagedDir != null) {
9386            origin = OriginInfo.fromStagedFile(stagedDir);
9387        } else {
9388            origin = OriginInfo.fromStagedContainer(stagedCid);
9389        }
9390
9391        final Message msg = mHandler.obtainMessage(INIT_COPY);
9392        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9393                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9394        mHandler.sendMessage(msg);
9395    }
9396
9397    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9398        Bundle extras = new Bundle(1);
9399        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9400
9401        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9402                packageName, extras, null, null, new int[] {userId});
9403        try {
9404            IActivityManager am = ActivityManagerNative.getDefault();
9405            final boolean isSystem =
9406                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9407            if (isSystem && am.isUserRunning(userId, false)) {
9408                // The just-installed/enabled app is bundled on the system, so presumed
9409                // to be able to run automatically without needing an explicit launch.
9410                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9411                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9412                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9413                        .setPackage(packageName);
9414                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9415                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9416            }
9417        } catch (RemoteException e) {
9418            // shouldn't happen
9419            Slog.w(TAG, "Unable to bootstrap installed package", e);
9420        }
9421    }
9422
9423    @Override
9424    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9425            int userId) {
9426        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9427        PackageSetting pkgSetting;
9428        final int uid = Binder.getCallingUid();
9429        enforceCrossUserPermission(uid, userId, true, true,
9430                "setApplicationHiddenSetting for user " + userId);
9431
9432        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9433            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9434            return false;
9435        }
9436
9437        long callingId = Binder.clearCallingIdentity();
9438        try {
9439            boolean sendAdded = false;
9440            boolean sendRemoved = false;
9441            // writer
9442            synchronized (mPackages) {
9443                pkgSetting = mSettings.mPackages.get(packageName);
9444                if (pkgSetting == null) {
9445                    return false;
9446                }
9447                if (pkgSetting.getHidden(userId) != hidden) {
9448                    pkgSetting.setHidden(hidden, userId);
9449                    mSettings.writePackageRestrictionsLPr(userId);
9450                    if (hidden) {
9451                        sendRemoved = true;
9452                    } else {
9453                        sendAdded = true;
9454                    }
9455                }
9456            }
9457            if (sendAdded) {
9458                sendPackageAddedForUser(packageName, pkgSetting, userId);
9459                return true;
9460            }
9461            if (sendRemoved) {
9462                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9463                        "hiding pkg");
9464                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9465            }
9466        } finally {
9467            Binder.restoreCallingIdentity(callingId);
9468        }
9469        return false;
9470    }
9471
9472    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9473            int userId) {
9474        final PackageRemovedInfo info = new PackageRemovedInfo();
9475        info.removedPackage = packageName;
9476        info.removedUsers = new int[] {userId};
9477        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9478        info.sendBroadcast(false, false, false);
9479    }
9480
9481    /**
9482     * Returns true if application is not found or there was an error. Otherwise it returns
9483     * the hidden state of the package for the given user.
9484     */
9485    @Override
9486    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9487        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9488        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9489                false, "getApplicationHidden for user " + userId);
9490        PackageSetting pkgSetting;
9491        long callingId = Binder.clearCallingIdentity();
9492        try {
9493            // writer
9494            synchronized (mPackages) {
9495                pkgSetting = mSettings.mPackages.get(packageName);
9496                if (pkgSetting == null) {
9497                    return true;
9498                }
9499                return pkgSetting.getHidden(userId);
9500            }
9501        } finally {
9502            Binder.restoreCallingIdentity(callingId);
9503        }
9504    }
9505
9506    /**
9507     * @hide
9508     */
9509    @Override
9510    public int installExistingPackageAsUser(String packageName, int userId) {
9511        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9512                null);
9513        PackageSetting pkgSetting;
9514        final int uid = Binder.getCallingUid();
9515        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9516                + userId);
9517        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9518            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9519        }
9520
9521        long callingId = Binder.clearCallingIdentity();
9522        try {
9523            boolean sendAdded = false;
9524
9525            // writer
9526            synchronized (mPackages) {
9527                pkgSetting = mSettings.mPackages.get(packageName);
9528                if (pkgSetting == null) {
9529                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9530                }
9531                if (!pkgSetting.getInstalled(userId)) {
9532                    pkgSetting.setInstalled(true, userId);
9533                    pkgSetting.setHidden(false, userId);
9534                    mSettings.writePackageRestrictionsLPr(userId);
9535                    sendAdded = true;
9536                }
9537            }
9538
9539            if (sendAdded) {
9540                sendPackageAddedForUser(packageName, pkgSetting, userId);
9541            }
9542        } finally {
9543            Binder.restoreCallingIdentity(callingId);
9544        }
9545
9546        return PackageManager.INSTALL_SUCCEEDED;
9547    }
9548
9549    boolean isUserRestricted(int userId, String restrictionKey) {
9550        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9551        if (restrictions.getBoolean(restrictionKey, false)) {
9552            Log.w(TAG, "User is restricted: " + restrictionKey);
9553            return true;
9554        }
9555        return false;
9556    }
9557
9558    @Override
9559    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9560        mContext.enforceCallingOrSelfPermission(
9561                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9562                "Only package verification agents can verify applications");
9563
9564        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9565        final PackageVerificationResponse response = new PackageVerificationResponse(
9566                verificationCode, Binder.getCallingUid());
9567        msg.arg1 = id;
9568        msg.obj = response;
9569        mHandler.sendMessage(msg);
9570    }
9571
9572    @Override
9573    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9574            long millisecondsToDelay) {
9575        mContext.enforceCallingOrSelfPermission(
9576                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9577                "Only package verification agents can extend verification timeouts");
9578
9579        final PackageVerificationState state = mPendingVerification.get(id);
9580        final PackageVerificationResponse response = new PackageVerificationResponse(
9581                verificationCodeAtTimeout, Binder.getCallingUid());
9582
9583        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9584            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9585        }
9586        if (millisecondsToDelay < 0) {
9587            millisecondsToDelay = 0;
9588        }
9589        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9590                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9591            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9592        }
9593
9594        if ((state != null) && !state.timeoutExtended()) {
9595            state.extendTimeout();
9596
9597            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9598            msg.arg1 = id;
9599            msg.obj = response;
9600            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9601        }
9602    }
9603
9604    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9605            int verificationCode, UserHandle user) {
9606        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9607        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9608        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9609        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9610        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9611
9612        mContext.sendBroadcastAsUser(intent, user,
9613                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9614    }
9615
9616    private ComponentName matchComponentForVerifier(String packageName,
9617            List<ResolveInfo> receivers) {
9618        ActivityInfo targetReceiver = null;
9619
9620        final int NR = receivers.size();
9621        for (int i = 0; i < NR; i++) {
9622            final ResolveInfo info = receivers.get(i);
9623            if (info.activityInfo == null) {
9624                continue;
9625            }
9626
9627            if (packageName.equals(info.activityInfo.packageName)) {
9628                targetReceiver = info.activityInfo;
9629                break;
9630            }
9631        }
9632
9633        if (targetReceiver == null) {
9634            return null;
9635        }
9636
9637        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9638    }
9639
9640    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9641            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9642        if (pkgInfo.verifiers.length == 0) {
9643            return null;
9644        }
9645
9646        final int N = pkgInfo.verifiers.length;
9647        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9648        for (int i = 0; i < N; i++) {
9649            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9650
9651            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9652                    receivers);
9653            if (comp == null) {
9654                continue;
9655            }
9656
9657            final int verifierUid = getUidForVerifier(verifierInfo);
9658            if (verifierUid == -1) {
9659                continue;
9660            }
9661
9662            if (DEBUG_VERIFY) {
9663                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9664                        + " with the correct signature");
9665            }
9666            sufficientVerifiers.add(comp);
9667            verificationState.addSufficientVerifier(verifierUid);
9668        }
9669
9670        return sufficientVerifiers;
9671    }
9672
9673    private int getUidForVerifier(VerifierInfo verifierInfo) {
9674        synchronized (mPackages) {
9675            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9676            if (pkg == null) {
9677                return -1;
9678            } else if (pkg.mSignatures.length != 1) {
9679                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9680                        + " has more than one signature; ignoring");
9681                return -1;
9682            }
9683
9684            /*
9685             * If the public key of the package's signature does not match
9686             * our expected public key, then this is a different package and
9687             * we should skip.
9688             */
9689
9690            final byte[] expectedPublicKey;
9691            try {
9692                final Signature verifierSig = pkg.mSignatures[0];
9693                final PublicKey publicKey = verifierSig.getPublicKey();
9694                expectedPublicKey = publicKey.getEncoded();
9695            } catch (CertificateException e) {
9696                return -1;
9697            }
9698
9699            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9700
9701            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9702                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9703                        + " does not have the expected public key; ignoring");
9704                return -1;
9705            }
9706
9707            return pkg.applicationInfo.uid;
9708        }
9709    }
9710
9711    @Override
9712    public void finishPackageInstall(int token) {
9713        enforceSystemOrRoot("Only the system is allowed to finish installs");
9714
9715        if (DEBUG_INSTALL) {
9716            Slog.v(TAG, "BM finishing package install for " + token);
9717        }
9718
9719        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9720        mHandler.sendMessage(msg);
9721    }
9722
9723    /**
9724     * Get the verification agent timeout.
9725     *
9726     * @return verification timeout in milliseconds
9727     */
9728    private long getVerificationTimeout() {
9729        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9730                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9731                DEFAULT_VERIFICATION_TIMEOUT);
9732    }
9733
9734    /**
9735     * Get the default verification agent response code.
9736     *
9737     * @return default verification response code
9738     */
9739    private int getDefaultVerificationResponse() {
9740        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9741                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9742                DEFAULT_VERIFICATION_RESPONSE);
9743    }
9744
9745    /**
9746     * Check whether or not package verification has been enabled.
9747     *
9748     * @return true if verification should be performed
9749     */
9750    private boolean isVerificationEnabled(int userId, int installFlags) {
9751        if (!DEFAULT_VERIFY_ENABLE) {
9752            return false;
9753        }
9754
9755        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9756
9757        // Check if installing from ADB
9758        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9759            // Do not run verification in a test harness environment
9760            if (ActivityManager.isRunningInTestHarness()) {
9761                return false;
9762            }
9763            if (ensureVerifyAppsEnabled) {
9764                return true;
9765            }
9766            // Check if the developer does not want package verification for ADB installs
9767            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9768                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9769                return false;
9770            }
9771        }
9772
9773        if (ensureVerifyAppsEnabled) {
9774            return true;
9775        }
9776
9777        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9778                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9779    }
9780
9781    @Override
9782    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9783            throws RemoteException {
9784        mContext.enforceCallingOrSelfPermission(
9785                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9786                "Only intentfilter verification agents can verify applications");
9787
9788        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9789        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9790                Binder.getCallingUid(), verificationCode, failedDomains);
9791        msg.arg1 = id;
9792        msg.obj = response;
9793        mHandler.sendMessage(msg);
9794    }
9795
9796    @Override
9797    public int getIntentVerificationStatus(String packageName, int userId) {
9798        synchronized (mPackages) {
9799            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9800        }
9801    }
9802
9803    @Override
9804    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9805        mContext.enforceCallingOrSelfPermission(
9806                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9807
9808        boolean result = false;
9809        synchronized (mPackages) {
9810            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9811        }
9812        if (result) {
9813            scheduleWritePackageRestrictionsLocked(userId);
9814        }
9815        return result;
9816    }
9817
9818    @Override
9819    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9820        synchronized (mPackages) {
9821            return mSettings.getIntentFilterVerificationsLPr(packageName);
9822        }
9823    }
9824
9825    @Override
9826    public List<IntentFilter> getAllIntentFilters(String packageName) {
9827        if (TextUtils.isEmpty(packageName)) {
9828            return Collections.<IntentFilter>emptyList();
9829        }
9830        synchronized (mPackages) {
9831            PackageParser.Package pkg = mPackages.get(packageName);
9832            if (pkg == null || pkg.activities == null) {
9833                return Collections.<IntentFilter>emptyList();
9834            }
9835            final int count = pkg.activities.size();
9836            ArrayList<IntentFilter> result = new ArrayList<>();
9837            for (int n=0; n<count; n++) {
9838                PackageParser.Activity activity = pkg.activities.get(n);
9839                if (activity.intents != null || activity.intents.size() > 0) {
9840                    result.addAll(activity.intents);
9841                }
9842            }
9843            return result;
9844        }
9845    }
9846
9847    @Override
9848    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9849        mContext.enforceCallingOrSelfPermission(
9850                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9851
9852        synchronized (mPackages) {
9853            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9854            if (packageName != null) {
9855                result |= updateIntentVerificationStatus(packageName,
9856                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9857                        UserHandle.myUserId());
9858                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9859                        packageName, userId);
9860            }
9861            return result;
9862        }
9863    }
9864
9865    @Override
9866    public String getDefaultBrowserPackageName(int userId) {
9867        synchronized (mPackages) {
9868            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9869        }
9870    }
9871
9872    /**
9873     * Get the "allow unknown sources" setting.
9874     *
9875     * @return the current "allow unknown sources" setting
9876     */
9877    private int getUnknownSourcesSettings() {
9878        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9879                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9880                -1);
9881    }
9882
9883    @Override
9884    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9885        final int uid = Binder.getCallingUid();
9886        // writer
9887        synchronized (mPackages) {
9888            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9889            if (targetPackageSetting == null) {
9890                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9891            }
9892
9893            PackageSetting installerPackageSetting;
9894            if (installerPackageName != null) {
9895                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9896                if (installerPackageSetting == null) {
9897                    throw new IllegalArgumentException("Unknown installer package: "
9898                            + installerPackageName);
9899                }
9900            } else {
9901                installerPackageSetting = null;
9902            }
9903
9904            Signature[] callerSignature;
9905            Object obj = mSettings.getUserIdLPr(uid);
9906            if (obj != null) {
9907                if (obj instanceof SharedUserSetting) {
9908                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9909                } else if (obj instanceof PackageSetting) {
9910                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9911                } else {
9912                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9913                }
9914            } else {
9915                throw new SecurityException("Unknown calling uid " + uid);
9916            }
9917
9918            // Verify: can't set installerPackageName to a package that is
9919            // not signed with the same cert as the caller.
9920            if (installerPackageSetting != null) {
9921                if (compareSignatures(callerSignature,
9922                        installerPackageSetting.signatures.mSignatures)
9923                        != PackageManager.SIGNATURE_MATCH) {
9924                    throw new SecurityException(
9925                            "Caller does not have same cert as new installer package "
9926                            + installerPackageName);
9927                }
9928            }
9929
9930            // Verify: if target already has an installer package, it must
9931            // be signed with the same cert as the caller.
9932            if (targetPackageSetting.installerPackageName != null) {
9933                PackageSetting setting = mSettings.mPackages.get(
9934                        targetPackageSetting.installerPackageName);
9935                // If the currently set package isn't valid, then it's always
9936                // okay to change it.
9937                if (setting != null) {
9938                    if (compareSignatures(callerSignature,
9939                            setting.signatures.mSignatures)
9940                            != PackageManager.SIGNATURE_MATCH) {
9941                        throw new SecurityException(
9942                                "Caller does not have same cert as old installer package "
9943                                + targetPackageSetting.installerPackageName);
9944                    }
9945                }
9946            }
9947
9948            // Okay!
9949            targetPackageSetting.installerPackageName = installerPackageName;
9950            scheduleWriteSettingsLocked();
9951        }
9952    }
9953
9954    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9955        // Queue up an async operation since the package installation may take a little while.
9956        mHandler.post(new Runnable() {
9957            public void run() {
9958                mHandler.removeCallbacks(this);
9959                 // Result object to be returned
9960                PackageInstalledInfo res = new PackageInstalledInfo();
9961                res.returnCode = currentStatus;
9962                res.uid = -1;
9963                res.pkg = null;
9964                res.removedInfo = new PackageRemovedInfo();
9965                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9966                    args.doPreInstall(res.returnCode);
9967                    synchronized (mInstallLock) {
9968                        installPackageLI(args, res);
9969                    }
9970                    args.doPostInstall(res.returnCode, res.uid);
9971                }
9972
9973                // A restore should be performed at this point if (a) the install
9974                // succeeded, (b) the operation is not an update, and (c) the new
9975                // package has not opted out of backup participation.
9976                final boolean update = res.removedInfo.removedPackage != null;
9977                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9978                boolean doRestore = !update
9979                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9980
9981                // Set up the post-install work request bookkeeping.  This will be used
9982                // and cleaned up by the post-install event handling regardless of whether
9983                // there's a restore pass performed.  Token values are >= 1.
9984                int token;
9985                if (mNextInstallToken < 0) mNextInstallToken = 1;
9986                token = mNextInstallToken++;
9987
9988                PostInstallData data = new PostInstallData(args, res);
9989                mRunningInstalls.put(token, data);
9990                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9991
9992                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9993                    // Pass responsibility to the Backup Manager.  It will perform a
9994                    // restore if appropriate, then pass responsibility back to the
9995                    // Package Manager to run the post-install observer callbacks
9996                    // and broadcasts.
9997                    IBackupManager bm = IBackupManager.Stub.asInterface(
9998                            ServiceManager.getService(Context.BACKUP_SERVICE));
9999                    if (bm != null) {
10000                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10001                                + " to BM for possible restore");
10002                        try {
10003                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10004                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10005                            } else {
10006                                doRestore = false;
10007                            }
10008                        } catch (RemoteException e) {
10009                            // can't happen; the backup manager is local
10010                        } catch (Exception e) {
10011                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10012                            doRestore = false;
10013                        }
10014                    } else {
10015                        Slog.e(TAG, "Backup Manager not found!");
10016                        doRestore = false;
10017                    }
10018                }
10019
10020                if (!doRestore) {
10021                    // No restore possible, or the Backup Manager was mysteriously not
10022                    // available -- just fire the post-install work request directly.
10023                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10024                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10025                    mHandler.sendMessage(msg);
10026                }
10027            }
10028        });
10029    }
10030
10031    private abstract class HandlerParams {
10032        private static final int MAX_RETRIES = 4;
10033
10034        /**
10035         * Number of times startCopy() has been attempted and had a non-fatal
10036         * error.
10037         */
10038        private int mRetries = 0;
10039
10040        /** User handle for the user requesting the information or installation. */
10041        private final UserHandle mUser;
10042
10043        HandlerParams(UserHandle user) {
10044            mUser = user;
10045        }
10046
10047        UserHandle getUser() {
10048            return mUser;
10049        }
10050
10051        final boolean startCopy() {
10052            boolean res;
10053            try {
10054                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10055
10056                if (++mRetries > MAX_RETRIES) {
10057                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10058                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10059                    handleServiceError();
10060                    return false;
10061                } else {
10062                    handleStartCopy();
10063                    res = true;
10064                }
10065            } catch (RemoteException e) {
10066                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10067                mHandler.sendEmptyMessage(MCS_RECONNECT);
10068                res = false;
10069            }
10070            handleReturnCode();
10071            return res;
10072        }
10073
10074        final void serviceError() {
10075            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10076            handleServiceError();
10077            handleReturnCode();
10078        }
10079
10080        abstract void handleStartCopy() throws RemoteException;
10081        abstract void handleServiceError();
10082        abstract void handleReturnCode();
10083    }
10084
10085    class MeasureParams extends HandlerParams {
10086        private final PackageStats mStats;
10087        private boolean mSuccess;
10088
10089        private final IPackageStatsObserver mObserver;
10090
10091        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10092            super(new UserHandle(stats.userHandle));
10093            mObserver = observer;
10094            mStats = stats;
10095        }
10096
10097        @Override
10098        public String toString() {
10099            return "MeasureParams{"
10100                + Integer.toHexString(System.identityHashCode(this))
10101                + " " + mStats.packageName + "}";
10102        }
10103
10104        @Override
10105        void handleStartCopy() throws RemoteException {
10106            synchronized (mInstallLock) {
10107                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10108            }
10109
10110            if (mSuccess) {
10111                final boolean mounted;
10112                if (Environment.isExternalStorageEmulated()) {
10113                    mounted = true;
10114                } else {
10115                    final String status = Environment.getExternalStorageState();
10116                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10117                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10118                }
10119
10120                if (mounted) {
10121                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10122
10123                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10124                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10125
10126                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10127                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10128
10129                    // Always subtract cache size, since it's a subdirectory
10130                    mStats.externalDataSize -= mStats.externalCacheSize;
10131
10132                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10133                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10134
10135                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10136                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10137                }
10138            }
10139        }
10140
10141        @Override
10142        void handleReturnCode() {
10143            if (mObserver != null) {
10144                try {
10145                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10146                } catch (RemoteException e) {
10147                    Slog.i(TAG, "Observer no longer exists.");
10148                }
10149            }
10150        }
10151
10152        @Override
10153        void handleServiceError() {
10154            Slog.e(TAG, "Could not measure application " + mStats.packageName
10155                            + " external storage");
10156        }
10157    }
10158
10159    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10160            throws RemoteException {
10161        long result = 0;
10162        for (File path : paths) {
10163            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10164        }
10165        return result;
10166    }
10167
10168    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10169        for (File path : paths) {
10170            try {
10171                mcs.clearDirectory(path.getAbsolutePath());
10172            } catch (RemoteException e) {
10173            }
10174        }
10175    }
10176
10177    static class OriginInfo {
10178        /**
10179         * Location where install is coming from, before it has been
10180         * copied/renamed into place. This could be a single monolithic APK
10181         * file, or a cluster directory. This location may be untrusted.
10182         */
10183        final File file;
10184        final String cid;
10185
10186        /**
10187         * Flag indicating that {@link #file} or {@link #cid} has already been
10188         * staged, meaning downstream users don't need to defensively copy the
10189         * contents.
10190         */
10191        final boolean staged;
10192
10193        /**
10194         * Flag indicating that {@link #file} or {@link #cid} is an already
10195         * installed app that is being moved.
10196         */
10197        final boolean existing;
10198
10199        final String resolvedPath;
10200        final File resolvedFile;
10201
10202        static OriginInfo fromNothing() {
10203            return new OriginInfo(null, null, false, false);
10204        }
10205
10206        static OriginInfo fromUntrustedFile(File file) {
10207            return new OriginInfo(file, null, false, false);
10208        }
10209
10210        static OriginInfo fromExistingFile(File file) {
10211            return new OriginInfo(file, null, false, true);
10212        }
10213
10214        static OriginInfo fromStagedFile(File file) {
10215            return new OriginInfo(file, null, true, false);
10216        }
10217
10218        static OriginInfo fromStagedContainer(String cid) {
10219            return new OriginInfo(null, cid, true, false);
10220        }
10221
10222        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10223            this.file = file;
10224            this.cid = cid;
10225            this.staged = staged;
10226            this.existing = existing;
10227
10228            if (cid != null) {
10229                resolvedPath = PackageHelper.getSdDir(cid);
10230                resolvedFile = new File(resolvedPath);
10231            } else if (file != null) {
10232                resolvedPath = file.getAbsolutePath();
10233                resolvedFile = file;
10234            } else {
10235                resolvedPath = null;
10236                resolvedFile = null;
10237            }
10238        }
10239    }
10240
10241    class MoveInfo {
10242        final int moveId;
10243        final String fromUuid;
10244        final String toUuid;
10245        final String packageName;
10246        final String dataAppName;
10247        final int appId;
10248        final String seinfo;
10249
10250        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10251                String dataAppName, int appId, String seinfo) {
10252            this.moveId = moveId;
10253            this.fromUuid = fromUuid;
10254            this.toUuid = toUuid;
10255            this.packageName = packageName;
10256            this.dataAppName = dataAppName;
10257            this.appId = appId;
10258            this.seinfo = seinfo;
10259        }
10260    }
10261
10262    class InstallParams extends HandlerParams {
10263        final OriginInfo origin;
10264        final MoveInfo move;
10265        final IPackageInstallObserver2 observer;
10266        int installFlags;
10267        final String installerPackageName;
10268        final String volumeUuid;
10269        final VerificationParams verificationParams;
10270        private InstallArgs mArgs;
10271        private int mRet;
10272        final String packageAbiOverride;
10273
10274        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10275                int installFlags, String installerPackageName, String volumeUuid,
10276                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10277            super(user);
10278            this.origin = origin;
10279            this.move = move;
10280            this.observer = observer;
10281            this.installFlags = installFlags;
10282            this.installerPackageName = installerPackageName;
10283            this.volumeUuid = volumeUuid;
10284            this.verificationParams = verificationParams;
10285            this.packageAbiOverride = packageAbiOverride;
10286        }
10287
10288        @Override
10289        public String toString() {
10290            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10291                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10292        }
10293
10294        public ManifestDigest getManifestDigest() {
10295            if (verificationParams == null) {
10296                return null;
10297            }
10298            return verificationParams.getManifestDigest();
10299        }
10300
10301        private int installLocationPolicy(PackageInfoLite pkgLite) {
10302            String packageName = pkgLite.packageName;
10303            int installLocation = pkgLite.installLocation;
10304            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10305            // reader
10306            synchronized (mPackages) {
10307                PackageParser.Package pkg = mPackages.get(packageName);
10308                if (pkg != null) {
10309                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10310                        // Check for downgrading.
10311                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10312                            try {
10313                                checkDowngrade(pkg, pkgLite);
10314                            } catch (PackageManagerException e) {
10315                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10316                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10317                            }
10318                        }
10319                        // Check for updated system application.
10320                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10321                            if (onSd) {
10322                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10323                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10324                            }
10325                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10326                        } else {
10327                            if (onSd) {
10328                                // Install flag overrides everything.
10329                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10330                            }
10331                            // If current upgrade specifies particular preference
10332                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10333                                // Application explicitly specified internal.
10334                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10335                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10336                                // App explictly prefers external. Let policy decide
10337                            } else {
10338                                // Prefer previous location
10339                                if (isExternal(pkg)) {
10340                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10341                                }
10342                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10343                            }
10344                        }
10345                    } else {
10346                        // Invalid install. Return error code
10347                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10348                    }
10349                }
10350            }
10351            // All the special cases have been taken care of.
10352            // Return result based on recommended install location.
10353            if (onSd) {
10354                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10355            }
10356            return pkgLite.recommendedInstallLocation;
10357        }
10358
10359        /*
10360         * Invoke remote method to get package information and install
10361         * location values. Override install location based on default
10362         * policy if needed and then create install arguments based
10363         * on the install location.
10364         */
10365        public void handleStartCopy() throws RemoteException {
10366            int ret = PackageManager.INSTALL_SUCCEEDED;
10367
10368            // If we're already staged, we've firmly committed to an install location
10369            if (origin.staged) {
10370                if (origin.file != null) {
10371                    installFlags |= PackageManager.INSTALL_INTERNAL;
10372                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10373                } else if (origin.cid != null) {
10374                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10375                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10376                } else {
10377                    throw new IllegalStateException("Invalid stage location");
10378                }
10379            }
10380
10381            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10382            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10383
10384            PackageInfoLite pkgLite = null;
10385
10386            if (onInt && onSd) {
10387                // Check if both bits are set.
10388                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10389                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10390            } else {
10391                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10392                        packageAbiOverride);
10393
10394                /*
10395                 * If we have too little free space, try to free cache
10396                 * before giving up.
10397                 */
10398                if (!origin.staged && pkgLite.recommendedInstallLocation
10399                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10400                    // TODO: focus freeing disk space on the target device
10401                    final StorageManager storage = StorageManager.from(mContext);
10402                    final long lowThreshold = storage.getStorageLowBytes(
10403                            Environment.getDataDirectory());
10404
10405                    final long sizeBytes = mContainerService.calculateInstalledSize(
10406                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10407
10408                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10409                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10410                                installFlags, packageAbiOverride);
10411                    }
10412
10413                    /*
10414                     * The cache free must have deleted the file we
10415                     * downloaded to install.
10416                     *
10417                     * TODO: fix the "freeCache" call to not delete
10418                     *       the file we care about.
10419                     */
10420                    if (pkgLite.recommendedInstallLocation
10421                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10422                        pkgLite.recommendedInstallLocation
10423                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10424                    }
10425                }
10426            }
10427
10428            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10429                int loc = pkgLite.recommendedInstallLocation;
10430                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10431                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10432                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10433                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10434                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10435                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10436                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10437                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10438                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10439                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10440                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10441                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10442                } else {
10443                    // Override with defaults if needed.
10444                    loc = installLocationPolicy(pkgLite);
10445                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10446                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10447                    } else if (!onSd && !onInt) {
10448                        // Override install location with flags
10449                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10450                            // Set the flag to install on external media.
10451                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10452                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10453                        } else {
10454                            // Make sure the flag for installing on external
10455                            // media is unset
10456                            installFlags |= PackageManager.INSTALL_INTERNAL;
10457                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10458                        }
10459                    }
10460                }
10461            }
10462
10463            final InstallArgs args = createInstallArgs(this);
10464            mArgs = args;
10465
10466            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10467                 /*
10468                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10469                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10470                 */
10471                int userIdentifier = getUser().getIdentifier();
10472                if (userIdentifier == UserHandle.USER_ALL
10473                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10474                    userIdentifier = UserHandle.USER_OWNER;
10475                }
10476
10477                /*
10478                 * Determine if we have any installed package verifiers. If we
10479                 * do, then we'll defer to them to verify the packages.
10480                 */
10481                final int requiredUid = mRequiredVerifierPackage == null ? -1
10482                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10483                if (!origin.existing && requiredUid != -1
10484                        && isVerificationEnabled(userIdentifier, installFlags)) {
10485                    final Intent verification = new Intent(
10486                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10487                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10488                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10489                            PACKAGE_MIME_TYPE);
10490                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10491
10492                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10493                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10494                            0 /* TODO: Which userId? */);
10495
10496                    if (DEBUG_VERIFY) {
10497                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10498                                + verification.toString() + " with " + pkgLite.verifiers.length
10499                                + " optional verifiers");
10500                    }
10501
10502                    final int verificationId = mPendingVerificationToken++;
10503
10504                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10505
10506                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10507                            installerPackageName);
10508
10509                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10510                            installFlags);
10511
10512                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10513                            pkgLite.packageName);
10514
10515                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10516                            pkgLite.versionCode);
10517
10518                    if (verificationParams != null) {
10519                        if (verificationParams.getVerificationURI() != null) {
10520                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10521                                 verificationParams.getVerificationURI());
10522                        }
10523                        if (verificationParams.getOriginatingURI() != null) {
10524                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10525                                  verificationParams.getOriginatingURI());
10526                        }
10527                        if (verificationParams.getReferrer() != null) {
10528                            verification.putExtra(Intent.EXTRA_REFERRER,
10529                                  verificationParams.getReferrer());
10530                        }
10531                        if (verificationParams.getOriginatingUid() >= 0) {
10532                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10533                                  verificationParams.getOriginatingUid());
10534                        }
10535                        if (verificationParams.getInstallerUid() >= 0) {
10536                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10537                                  verificationParams.getInstallerUid());
10538                        }
10539                    }
10540
10541                    final PackageVerificationState verificationState = new PackageVerificationState(
10542                            requiredUid, args);
10543
10544                    mPendingVerification.append(verificationId, verificationState);
10545
10546                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10547                            receivers, verificationState);
10548
10549                    /*
10550                     * If any sufficient verifiers were listed in the package
10551                     * manifest, attempt to ask them.
10552                     */
10553                    if (sufficientVerifiers != null) {
10554                        final int N = sufficientVerifiers.size();
10555                        if (N == 0) {
10556                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10557                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10558                        } else {
10559                            for (int i = 0; i < N; i++) {
10560                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10561
10562                                final Intent sufficientIntent = new Intent(verification);
10563                                sufficientIntent.setComponent(verifierComponent);
10564
10565                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10566                            }
10567                        }
10568                    }
10569
10570                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10571                            mRequiredVerifierPackage, receivers);
10572                    if (ret == PackageManager.INSTALL_SUCCEEDED
10573                            && mRequiredVerifierPackage != null) {
10574                        /*
10575                         * Send the intent to the required verification agent,
10576                         * but only start the verification timeout after the
10577                         * target BroadcastReceivers have run.
10578                         */
10579                        verification.setComponent(requiredVerifierComponent);
10580                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10581                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10582                                new BroadcastReceiver() {
10583                                    @Override
10584                                    public void onReceive(Context context, Intent intent) {
10585                                        final Message msg = mHandler
10586                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10587                                        msg.arg1 = verificationId;
10588                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10589                                    }
10590                                }, null, 0, null, null);
10591
10592                        /*
10593                         * We don't want the copy to proceed until verification
10594                         * succeeds, so null out this field.
10595                         */
10596                        mArgs = null;
10597                    }
10598                } else {
10599                    /*
10600                     * No package verification is enabled, so immediately start
10601                     * the remote call to initiate copy using temporary file.
10602                     */
10603                    ret = args.copyApk(mContainerService, true);
10604                }
10605            }
10606
10607            mRet = ret;
10608        }
10609
10610        @Override
10611        void handleReturnCode() {
10612            // If mArgs is null, then MCS couldn't be reached. When it
10613            // reconnects, it will try again to install. At that point, this
10614            // will succeed.
10615            if (mArgs != null) {
10616                processPendingInstall(mArgs, mRet);
10617            }
10618        }
10619
10620        @Override
10621        void handleServiceError() {
10622            mArgs = createInstallArgs(this);
10623            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10624        }
10625
10626        public boolean isForwardLocked() {
10627            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10628        }
10629    }
10630
10631    /**
10632     * Used during creation of InstallArgs
10633     *
10634     * @param installFlags package installation flags
10635     * @return true if should be installed on external storage
10636     */
10637    private static boolean installOnExternalAsec(int installFlags) {
10638        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10639            return false;
10640        }
10641        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10642            return true;
10643        }
10644        return false;
10645    }
10646
10647    /**
10648     * Used during creation of InstallArgs
10649     *
10650     * @param installFlags package installation flags
10651     * @return true if should be installed as forward locked
10652     */
10653    private static boolean installForwardLocked(int installFlags) {
10654        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10655    }
10656
10657    private InstallArgs createInstallArgs(InstallParams params) {
10658        if (params.move != null) {
10659            return new MoveInstallArgs(params);
10660        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10661            return new AsecInstallArgs(params);
10662        } else {
10663            return new FileInstallArgs(params);
10664        }
10665    }
10666
10667    /**
10668     * Create args that describe an existing installed package. Typically used
10669     * when cleaning up old installs, or used as a move source.
10670     */
10671    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10672            String resourcePath, String[] instructionSets) {
10673        final boolean isInAsec;
10674        if (installOnExternalAsec(installFlags)) {
10675            /* Apps on SD card are always in ASEC containers. */
10676            isInAsec = true;
10677        } else if (installForwardLocked(installFlags)
10678                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10679            /*
10680             * Forward-locked apps are only in ASEC containers if they're the
10681             * new style
10682             */
10683            isInAsec = true;
10684        } else {
10685            isInAsec = false;
10686        }
10687
10688        if (isInAsec) {
10689            return new AsecInstallArgs(codePath, instructionSets,
10690                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10691        } else {
10692            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10693        }
10694    }
10695
10696    static abstract class InstallArgs {
10697        /** @see InstallParams#origin */
10698        final OriginInfo origin;
10699        /** @see InstallParams#move */
10700        final MoveInfo move;
10701
10702        final IPackageInstallObserver2 observer;
10703        // Always refers to PackageManager flags only
10704        final int installFlags;
10705        final String installerPackageName;
10706        final String volumeUuid;
10707        final ManifestDigest manifestDigest;
10708        final UserHandle user;
10709        final String abiOverride;
10710
10711        // The list of instruction sets supported by this app. This is currently
10712        // only used during the rmdex() phase to clean up resources. We can get rid of this
10713        // if we move dex files under the common app path.
10714        /* nullable */ String[] instructionSets;
10715
10716        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10717                int installFlags, String installerPackageName, String volumeUuid,
10718                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10719                String abiOverride) {
10720            this.origin = origin;
10721            this.move = move;
10722            this.installFlags = installFlags;
10723            this.observer = observer;
10724            this.installerPackageName = installerPackageName;
10725            this.volumeUuid = volumeUuid;
10726            this.manifestDigest = manifestDigest;
10727            this.user = user;
10728            this.instructionSets = instructionSets;
10729            this.abiOverride = abiOverride;
10730        }
10731
10732        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10733        abstract int doPreInstall(int status);
10734
10735        /**
10736         * Rename package into final resting place. All paths on the given
10737         * scanned package should be updated to reflect the rename.
10738         */
10739        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10740        abstract int doPostInstall(int status, int uid);
10741
10742        /** @see PackageSettingBase#codePathString */
10743        abstract String getCodePath();
10744        /** @see PackageSettingBase#resourcePathString */
10745        abstract String getResourcePath();
10746
10747        // Need installer lock especially for dex file removal.
10748        abstract void cleanUpResourcesLI();
10749        abstract boolean doPostDeleteLI(boolean delete);
10750
10751        /**
10752         * Called before the source arguments are copied. This is used mostly
10753         * for MoveParams when it needs to read the source file to put it in the
10754         * destination.
10755         */
10756        int doPreCopy() {
10757            return PackageManager.INSTALL_SUCCEEDED;
10758        }
10759
10760        /**
10761         * Called after the source arguments are copied. This is used mostly for
10762         * MoveParams when it needs to read the source file to put it in the
10763         * destination.
10764         *
10765         * @return
10766         */
10767        int doPostCopy(int uid) {
10768            return PackageManager.INSTALL_SUCCEEDED;
10769        }
10770
10771        protected boolean isFwdLocked() {
10772            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10773        }
10774
10775        protected boolean isExternalAsec() {
10776            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10777        }
10778
10779        UserHandle getUser() {
10780            return user;
10781        }
10782    }
10783
10784    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10785        if (!allCodePaths.isEmpty()) {
10786            if (instructionSets == null) {
10787                throw new IllegalStateException("instructionSet == null");
10788            }
10789            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10790            for (String codePath : allCodePaths) {
10791                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10792                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10793                    if (retCode < 0) {
10794                        Slog.w(TAG, "Couldn't remove dex file for package: "
10795                                + " at location " + codePath + ", retcode=" + retCode);
10796                        // we don't consider this to be a failure of the core package deletion
10797                    }
10798                }
10799            }
10800        }
10801    }
10802
10803    /**
10804     * Logic to handle installation of non-ASEC applications, including copying
10805     * and renaming logic.
10806     */
10807    class FileInstallArgs extends InstallArgs {
10808        private File codeFile;
10809        private File resourceFile;
10810
10811        // Example topology:
10812        // /data/app/com.example/base.apk
10813        // /data/app/com.example/split_foo.apk
10814        // /data/app/com.example/lib/arm/libfoo.so
10815        // /data/app/com.example/lib/arm64/libfoo.so
10816        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10817
10818        /** New install */
10819        FileInstallArgs(InstallParams params) {
10820            super(params.origin, params.move, params.observer, params.installFlags,
10821                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10822                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10823            if (isFwdLocked()) {
10824                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10825            }
10826        }
10827
10828        /** Existing install */
10829        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10830            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10831                    null);
10832            this.codeFile = (codePath != null) ? new File(codePath) : null;
10833            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10834        }
10835
10836        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10837            if (origin.staged) {
10838                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10839                codeFile = origin.file;
10840                resourceFile = origin.file;
10841                return PackageManager.INSTALL_SUCCEEDED;
10842            }
10843
10844            try {
10845                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10846                codeFile = tempDir;
10847                resourceFile = tempDir;
10848            } catch (IOException e) {
10849                Slog.w(TAG, "Failed to create copy file: " + e);
10850                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10851            }
10852
10853            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10854                @Override
10855                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10856                    if (!FileUtils.isValidExtFilename(name)) {
10857                        throw new IllegalArgumentException("Invalid filename: " + name);
10858                    }
10859                    try {
10860                        final File file = new File(codeFile, name);
10861                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10862                                O_RDWR | O_CREAT, 0644);
10863                        Os.chmod(file.getAbsolutePath(), 0644);
10864                        return new ParcelFileDescriptor(fd);
10865                    } catch (ErrnoException e) {
10866                        throw new RemoteException("Failed to open: " + e.getMessage());
10867                    }
10868                }
10869            };
10870
10871            int ret = PackageManager.INSTALL_SUCCEEDED;
10872            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10873            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10874                Slog.e(TAG, "Failed to copy package");
10875                return ret;
10876            }
10877
10878            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10879            NativeLibraryHelper.Handle handle = null;
10880            try {
10881                handle = NativeLibraryHelper.Handle.create(codeFile);
10882                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10883                        abiOverride);
10884            } catch (IOException e) {
10885                Slog.e(TAG, "Copying native libraries failed", e);
10886                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10887            } finally {
10888                IoUtils.closeQuietly(handle);
10889            }
10890
10891            return ret;
10892        }
10893
10894        int doPreInstall(int status) {
10895            if (status != PackageManager.INSTALL_SUCCEEDED) {
10896                cleanUp();
10897            }
10898            return status;
10899        }
10900
10901        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10902            if (status != PackageManager.INSTALL_SUCCEEDED) {
10903                cleanUp();
10904                return false;
10905            }
10906
10907            final File targetDir = codeFile.getParentFile();
10908            final File beforeCodeFile = codeFile;
10909            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10910
10911            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10912            try {
10913                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10914            } catch (ErrnoException e) {
10915                Slog.w(TAG, "Failed to rename", e);
10916                return false;
10917            }
10918
10919            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10920                Slog.w(TAG, "Failed to restorecon");
10921                return false;
10922            }
10923
10924            // Reflect the rename internally
10925            codeFile = afterCodeFile;
10926            resourceFile = afterCodeFile;
10927
10928            // Reflect the rename in scanned details
10929            pkg.codePath = afterCodeFile.getAbsolutePath();
10930            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10931                    pkg.baseCodePath);
10932            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10933                    pkg.splitCodePaths);
10934
10935            // Reflect the rename in app info
10936            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10937            pkg.applicationInfo.setCodePath(pkg.codePath);
10938            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10939            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10940            pkg.applicationInfo.setResourcePath(pkg.codePath);
10941            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10942            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10943
10944            return true;
10945        }
10946
10947        int doPostInstall(int status, int uid) {
10948            if (status != PackageManager.INSTALL_SUCCEEDED) {
10949                cleanUp();
10950            }
10951            return status;
10952        }
10953
10954        @Override
10955        String getCodePath() {
10956            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10957        }
10958
10959        @Override
10960        String getResourcePath() {
10961            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10962        }
10963
10964        private boolean cleanUp() {
10965            if (codeFile == null || !codeFile.exists()) {
10966                return false;
10967            }
10968
10969            if (codeFile.isDirectory()) {
10970                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10971            } else {
10972                codeFile.delete();
10973            }
10974
10975            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10976                resourceFile.delete();
10977            }
10978
10979            return true;
10980        }
10981
10982        void cleanUpResourcesLI() {
10983            // Try enumerating all code paths before deleting
10984            List<String> allCodePaths = Collections.EMPTY_LIST;
10985            if (codeFile != null && codeFile.exists()) {
10986                try {
10987                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10988                    allCodePaths = pkg.getAllCodePaths();
10989                } catch (PackageParserException e) {
10990                    // Ignored; we tried our best
10991                }
10992            }
10993
10994            cleanUp();
10995            removeDexFiles(allCodePaths, instructionSets);
10996        }
10997
10998        boolean doPostDeleteLI(boolean delete) {
10999            // XXX err, shouldn't we respect the delete flag?
11000            cleanUpResourcesLI();
11001            return true;
11002        }
11003    }
11004
11005    private boolean isAsecExternal(String cid) {
11006        final String asecPath = PackageHelper.getSdFilesystem(cid);
11007        return !asecPath.startsWith(mAsecInternalPath);
11008    }
11009
11010    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11011            PackageManagerException {
11012        if (copyRet < 0) {
11013            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11014                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11015                throw new PackageManagerException(copyRet, message);
11016            }
11017        }
11018    }
11019
11020    /**
11021     * Extract the MountService "container ID" from the full code path of an
11022     * .apk.
11023     */
11024    static String cidFromCodePath(String fullCodePath) {
11025        int eidx = fullCodePath.lastIndexOf("/");
11026        String subStr1 = fullCodePath.substring(0, eidx);
11027        int sidx = subStr1.lastIndexOf("/");
11028        return subStr1.substring(sidx+1, eidx);
11029    }
11030
11031    /**
11032     * Logic to handle installation of ASEC applications, including copying and
11033     * renaming logic.
11034     */
11035    class AsecInstallArgs extends InstallArgs {
11036        static final String RES_FILE_NAME = "pkg.apk";
11037        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11038
11039        String cid;
11040        String packagePath;
11041        String resourcePath;
11042
11043        /** New install */
11044        AsecInstallArgs(InstallParams params) {
11045            super(params.origin, params.move, params.observer, params.installFlags,
11046                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11047                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11048        }
11049
11050        /** Existing install */
11051        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11052                        boolean isExternal, boolean isForwardLocked) {
11053            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11054                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11055                    instructionSets, null);
11056            // Hackily pretend we're still looking at a full code path
11057            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11058                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11059            }
11060
11061            // Extract cid from fullCodePath
11062            int eidx = fullCodePath.lastIndexOf("/");
11063            String subStr1 = fullCodePath.substring(0, eidx);
11064            int sidx = subStr1.lastIndexOf("/");
11065            cid = subStr1.substring(sidx+1, eidx);
11066            setMountPath(subStr1);
11067        }
11068
11069        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11070            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11071                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11072                    instructionSets, null);
11073            this.cid = cid;
11074            setMountPath(PackageHelper.getSdDir(cid));
11075        }
11076
11077        void createCopyFile() {
11078            cid = mInstallerService.allocateExternalStageCidLegacy();
11079        }
11080
11081        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11082            if (origin.staged) {
11083                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11084                cid = origin.cid;
11085                setMountPath(PackageHelper.getSdDir(cid));
11086                return PackageManager.INSTALL_SUCCEEDED;
11087            }
11088
11089            if (temp) {
11090                createCopyFile();
11091            } else {
11092                /*
11093                 * Pre-emptively destroy the container since it's destroyed if
11094                 * copying fails due to it existing anyway.
11095                 */
11096                PackageHelper.destroySdDir(cid);
11097            }
11098
11099            final String newMountPath = imcs.copyPackageToContainer(
11100                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11101                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11102
11103            if (newMountPath != null) {
11104                setMountPath(newMountPath);
11105                return PackageManager.INSTALL_SUCCEEDED;
11106            } else {
11107                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11108            }
11109        }
11110
11111        @Override
11112        String getCodePath() {
11113            return packagePath;
11114        }
11115
11116        @Override
11117        String getResourcePath() {
11118            return resourcePath;
11119        }
11120
11121        int doPreInstall(int status) {
11122            if (status != PackageManager.INSTALL_SUCCEEDED) {
11123                // Destroy container
11124                PackageHelper.destroySdDir(cid);
11125            } else {
11126                boolean mounted = PackageHelper.isContainerMounted(cid);
11127                if (!mounted) {
11128                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11129                            Process.SYSTEM_UID);
11130                    if (newMountPath != null) {
11131                        setMountPath(newMountPath);
11132                    } else {
11133                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11134                    }
11135                }
11136            }
11137            return status;
11138        }
11139
11140        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11141            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11142            String newMountPath = null;
11143            if (PackageHelper.isContainerMounted(cid)) {
11144                // Unmount the container
11145                if (!PackageHelper.unMountSdDir(cid)) {
11146                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11147                    return false;
11148                }
11149            }
11150            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11151                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11152                        " which might be stale. Will try to clean up.");
11153                // Clean up the stale container and proceed to recreate.
11154                if (!PackageHelper.destroySdDir(newCacheId)) {
11155                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11156                    return false;
11157                }
11158                // Successfully cleaned up stale container. Try to rename again.
11159                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11160                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11161                            + " inspite of cleaning it up.");
11162                    return false;
11163                }
11164            }
11165            if (!PackageHelper.isContainerMounted(newCacheId)) {
11166                Slog.w(TAG, "Mounting container " + newCacheId);
11167                newMountPath = PackageHelper.mountSdDir(newCacheId,
11168                        getEncryptKey(), Process.SYSTEM_UID);
11169            } else {
11170                newMountPath = PackageHelper.getSdDir(newCacheId);
11171            }
11172            if (newMountPath == null) {
11173                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11174                return false;
11175            }
11176            Log.i(TAG, "Succesfully renamed " + cid +
11177                    " to " + newCacheId +
11178                    " at new path: " + newMountPath);
11179            cid = newCacheId;
11180
11181            final File beforeCodeFile = new File(packagePath);
11182            setMountPath(newMountPath);
11183            final File afterCodeFile = new File(packagePath);
11184
11185            // Reflect the rename in scanned details
11186            pkg.codePath = afterCodeFile.getAbsolutePath();
11187            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11188                    pkg.baseCodePath);
11189            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11190                    pkg.splitCodePaths);
11191
11192            // Reflect the rename in app info
11193            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11194            pkg.applicationInfo.setCodePath(pkg.codePath);
11195            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11196            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11197            pkg.applicationInfo.setResourcePath(pkg.codePath);
11198            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11199            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11200
11201            return true;
11202        }
11203
11204        private void setMountPath(String mountPath) {
11205            final File mountFile = new File(mountPath);
11206
11207            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11208            if (monolithicFile.exists()) {
11209                packagePath = monolithicFile.getAbsolutePath();
11210                if (isFwdLocked()) {
11211                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11212                } else {
11213                    resourcePath = packagePath;
11214                }
11215            } else {
11216                packagePath = mountFile.getAbsolutePath();
11217                resourcePath = packagePath;
11218            }
11219        }
11220
11221        int doPostInstall(int status, int uid) {
11222            if (status != PackageManager.INSTALL_SUCCEEDED) {
11223                cleanUp();
11224            } else {
11225                final int groupOwner;
11226                final String protectedFile;
11227                if (isFwdLocked()) {
11228                    groupOwner = UserHandle.getSharedAppGid(uid);
11229                    protectedFile = RES_FILE_NAME;
11230                } else {
11231                    groupOwner = -1;
11232                    protectedFile = null;
11233                }
11234
11235                if (uid < Process.FIRST_APPLICATION_UID
11236                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11237                    Slog.e(TAG, "Failed to finalize " + cid);
11238                    PackageHelper.destroySdDir(cid);
11239                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11240                }
11241
11242                boolean mounted = PackageHelper.isContainerMounted(cid);
11243                if (!mounted) {
11244                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11245                }
11246            }
11247            return status;
11248        }
11249
11250        private void cleanUp() {
11251            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11252
11253            // Destroy secure container
11254            PackageHelper.destroySdDir(cid);
11255        }
11256
11257        private List<String> getAllCodePaths() {
11258            final File codeFile = new File(getCodePath());
11259            if (codeFile != null && codeFile.exists()) {
11260                try {
11261                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11262                    return pkg.getAllCodePaths();
11263                } catch (PackageParserException e) {
11264                    // Ignored; we tried our best
11265                }
11266            }
11267            return Collections.EMPTY_LIST;
11268        }
11269
11270        void cleanUpResourcesLI() {
11271            // Enumerate all code paths before deleting
11272            cleanUpResourcesLI(getAllCodePaths());
11273        }
11274
11275        private void cleanUpResourcesLI(List<String> allCodePaths) {
11276            cleanUp();
11277            removeDexFiles(allCodePaths, instructionSets);
11278        }
11279
11280        String getPackageName() {
11281            return getAsecPackageName(cid);
11282        }
11283
11284        boolean doPostDeleteLI(boolean delete) {
11285            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11286            final List<String> allCodePaths = getAllCodePaths();
11287            boolean mounted = PackageHelper.isContainerMounted(cid);
11288            if (mounted) {
11289                // Unmount first
11290                if (PackageHelper.unMountSdDir(cid)) {
11291                    mounted = false;
11292                }
11293            }
11294            if (!mounted && delete) {
11295                cleanUpResourcesLI(allCodePaths);
11296            }
11297            return !mounted;
11298        }
11299
11300        @Override
11301        int doPreCopy() {
11302            if (isFwdLocked()) {
11303                if (!PackageHelper.fixSdPermissions(cid,
11304                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11305                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11306                }
11307            }
11308
11309            return PackageManager.INSTALL_SUCCEEDED;
11310        }
11311
11312        @Override
11313        int doPostCopy(int uid) {
11314            if (isFwdLocked()) {
11315                if (uid < Process.FIRST_APPLICATION_UID
11316                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11317                                RES_FILE_NAME)) {
11318                    Slog.e(TAG, "Failed to finalize " + cid);
11319                    PackageHelper.destroySdDir(cid);
11320                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11321                }
11322            }
11323
11324            return PackageManager.INSTALL_SUCCEEDED;
11325        }
11326    }
11327
11328    /**
11329     * Logic to handle movement of existing installed applications.
11330     */
11331    class MoveInstallArgs extends InstallArgs {
11332        private File codeFile;
11333        private File resourceFile;
11334
11335        /** New install */
11336        MoveInstallArgs(InstallParams params) {
11337            super(params.origin, params.move, params.observer, params.installFlags,
11338                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11339                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11340        }
11341
11342        int copyApk(IMediaContainerService imcs, boolean temp) {
11343            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11344                    + move.fromUuid + " to " + move.toUuid);
11345            synchronized (mInstaller) {
11346                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11347                        move.dataAppName, move.appId, move.seinfo) != 0) {
11348                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11349                }
11350            }
11351
11352            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11353            resourceFile = codeFile;
11354            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11355
11356            return PackageManager.INSTALL_SUCCEEDED;
11357        }
11358
11359        int doPreInstall(int status) {
11360            if (status != PackageManager.INSTALL_SUCCEEDED) {
11361                cleanUp(move.toUuid);
11362            }
11363            return status;
11364        }
11365
11366        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11367            if (status != PackageManager.INSTALL_SUCCEEDED) {
11368                cleanUp(move.toUuid);
11369                return false;
11370            }
11371
11372            // Reflect the move in app info
11373            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11374            pkg.applicationInfo.setCodePath(pkg.codePath);
11375            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11376            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11377            pkg.applicationInfo.setResourcePath(pkg.codePath);
11378            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11379            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11380
11381            return true;
11382        }
11383
11384        int doPostInstall(int status, int uid) {
11385            if (status == PackageManager.INSTALL_SUCCEEDED) {
11386                cleanUp(move.fromUuid);
11387            } else {
11388                cleanUp(move.toUuid);
11389            }
11390            return status;
11391        }
11392
11393        @Override
11394        String getCodePath() {
11395            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11396        }
11397
11398        @Override
11399        String getResourcePath() {
11400            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11401        }
11402
11403        private boolean cleanUp(String volumeUuid) {
11404            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11405                    move.dataAppName);
11406            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11407            synchronized (mInstallLock) {
11408                // Clean up both app data and code
11409                removeDataDirsLI(volumeUuid, move.packageName);
11410                if (codeFile.isDirectory()) {
11411                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11412                } else {
11413                    codeFile.delete();
11414                }
11415            }
11416            return true;
11417        }
11418
11419        void cleanUpResourcesLI() {
11420            throw new UnsupportedOperationException();
11421        }
11422
11423        boolean doPostDeleteLI(boolean delete) {
11424            throw new UnsupportedOperationException();
11425        }
11426    }
11427
11428    static String getAsecPackageName(String packageCid) {
11429        int idx = packageCid.lastIndexOf("-");
11430        if (idx == -1) {
11431            return packageCid;
11432        }
11433        return packageCid.substring(0, idx);
11434    }
11435
11436    // Utility method used to create code paths based on package name and available index.
11437    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11438        String idxStr = "";
11439        int idx = 1;
11440        // Fall back to default value of idx=1 if prefix is not
11441        // part of oldCodePath
11442        if (oldCodePath != null) {
11443            String subStr = oldCodePath;
11444            // Drop the suffix right away
11445            if (suffix != null && subStr.endsWith(suffix)) {
11446                subStr = subStr.substring(0, subStr.length() - suffix.length());
11447            }
11448            // If oldCodePath already contains prefix find out the
11449            // ending index to either increment or decrement.
11450            int sidx = subStr.lastIndexOf(prefix);
11451            if (sidx != -1) {
11452                subStr = subStr.substring(sidx + prefix.length());
11453                if (subStr != null) {
11454                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11455                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11456                    }
11457                    try {
11458                        idx = Integer.parseInt(subStr);
11459                        if (idx <= 1) {
11460                            idx++;
11461                        } else {
11462                            idx--;
11463                        }
11464                    } catch(NumberFormatException e) {
11465                    }
11466                }
11467            }
11468        }
11469        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11470        return prefix + idxStr;
11471    }
11472
11473    private File getNextCodePath(File targetDir, String packageName) {
11474        int suffix = 1;
11475        File result;
11476        do {
11477            result = new File(targetDir, packageName + "-" + suffix);
11478            suffix++;
11479        } while (result.exists());
11480        return result;
11481    }
11482
11483    // Utility method that returns the relative package path with respect
11484    // to the installation directory. Like say for /data/data/com.test-1.apk
11485    // string com.test-1 is returned.
11486    static String deriveCodePathName(String codePath) {
11487        if (codePath == null) {
11488            return null;
11489        }
11490        final File codeFile = new File(codePath);
11491        final String name = codeFile.getName();
11492        if (codeFile.isDirectory()) {
11493            return name;
11494        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11495            final int lastDot = name.lastIndexOf('.');
11496            return name.substring(0, lastDot);
11497        } else {
11498            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11499            return null;
11500        }
11501    }
11502
11503    class PackageInstalledInfo {
11504        String name;
11505        int uid;
11506        // The set of users that originally had this package installed.
11507        int[] origUsers;
11508        // The set of users that now have this package installed.
11509        int[] newUsers;
11510        PackageParser.Package pkg;
11511        int returnCode;
11512        String returnMsg;
11513        PackageRemovedInfo removedInfo;
11514
11515        public void setError(int code, String msg) {
11516            returnCode = code;
11517            returnMsg = msg;
11518            Slog.w(TAG, msg);
11519        }
11520
11521        public void setError(String msg, PackageParserException e) {
11522            returnCode = e.error;
11523            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11524            Slog.w(TAG, msg, e);
11525        }
11526
11527        public void setError(String msg, PackageManagerException e) {
11528            returnCode = e.error;
11529            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11530            Slog.w(TAG, msg, e);
11531        }
11532
11533        // In some error cases we want to convey more info back to the observer
11534        String origPackage;
11535        String origPermission;
11536    }
11537
11538    /*
11539     * Install a non-existing package.
11540     */
11541    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11542            UserHandle user, String installerPackageName, String volumeUuid,
11543            PackageInstalledInfo res) {
11544        // Remember this for later, in case we need to rollback this install
11545        String pkgName = pkg.packageName;
11546
11547        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11548        final boolean dataDirExists = Environment
11549                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11550        synchronized(mPackages) {
11551            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11552                // A package with the same name is already installed, though
11553                // it has been renamed to an older name.  The package we
11554                // are trying to install should be installed as an update to
11555                // the existing one, but that has not been requested, so bail.
11556                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11557                        + " without first uninstalling package running as "
11558                        + mSettings.mRenamedPackages.get(pkgName));
11559                return;
11560            }
11561            if (mPackages.containsKey(pkgName)) {
11562                // Don't allow installation over an existing package with the same name.
11563                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11564                        + " without first uninstalling.");
11565                return;
11566            }
11567        }
11568
11569        try {
11570            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11571                    System.currentTimeMillis(), user);
11572
11573            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11574            // delete the partially installed application. the data directory will have to be
11575            // restored if it was already existing
11576            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11577                // remove package from internal structures.  Note that we want deletePackageX to
11578                // delete the package data and cache directories that it created in
11579                // scanPackageLocked, unless those directories existed before we even tried to
11580                // install.
11581                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11582                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11583                                res.removedInfo, true);
11584            }
11585
11586        } catch (PackageManagerException e) {
11587            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11588        }
11589    }
11590
11591    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11592        // Can't rotate keys during boot or if sharedUser.
11593        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11594                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11595            return false;
11596        }
11597        // app is using upgradeKeySets; make sure all are valid
11598        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11599        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11600        for (int i = 0; i < upgradeKeySets.length; i++) {
11601            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11602                Slog.wtf(TAG, "Package "
11603                         + (oldPs.name != null ? oldPs.name : "<null>")
11604                         + " contains upgrade-key-set reference to unknown key-set: "
11605                         + upgradeKeySets[i]
11606                         + " reverting to signatures check.");
11607                return false;
11608            }
11609        }
11610        return true;
11611    }
11612
11613    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11614        // Upgrade keysets are being used.  Determine if new package has a superset of the
11615        // required keys.
11616        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11617        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11618        for (int i = 0; i < upgradeKeySets.length; i++) {
11619            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11620            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11621                return true;
11622            }
11623        }
11624        return false;
11625    }
11626
11627    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11628            UserHandle user, String installerPackageName, String volumeUuid,
11629            PackageInstalledInfo res) {
11630        final PackageParser.Package oldPackage;
11631        final String pkgName = pkg.packageName;
11632        final int[] allUsers;
11633        final boolean[] perUserInstalled;
11634        final boolean weFroze;
11635
11636        // First find the old package info and check signatures
11637        synchronized(mPackages) {
11638            oldPackage = mPackages.get(pkgName);
11639            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11640            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11641            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11642                if(!checkUpgradeKeySetLP(ps, pkg)) {
11643                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11644                            "New package not signed by keys specified by upgrade-keysets: "
11645                            + pkgName);
11646                    return;
11647                }
11648            } else {
11649                // default to original signature matching
11650                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11651                    != PackageManager.SIGNATURE_MATCH) {
11652                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11653                            "New package has a different signature: " + pkgName);
11654                    return;
11655                }
11656            }
11657
11658            // In case of rollback, remember per-user/profile install state
11659            allUsers = sUserManager.getUserIds();
11660            perUserInstalled = new boolean[allUsers.length];
11661            for (int i = 0; i < allUsers.length; i++) {
11662                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11663            }
11664
11665            // Mark the app as frozen to prevent launching during the upgrade
11666            // process, and then kill all running instances
11667            if (!ps.frozen) {
11668                ps.frozen = true;
11669                weFroze = true;
11670            } else {
11671                weFroze = false;
11672            }
11673        }
11674
11675        // Now that we're guarded by frozen state, kill app during upgrade
11676        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11677
11678        try {
11679            boolean sysPkg = (isSystemApp(oldPackage));
11680            if (sysPkg) {
11681                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11682                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11683            } else {
11684                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11685                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11686            }
11687        } finally {
11688            // Regardless of success or failure of upgrade steps above, always
11689            // unfreeze the package if we froze it
11690            if (weFroze) {
11691                unfreezePackage(pkgName);
11692            }
11693        }
11694    }
11695
11696    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11697            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11698            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11699            String volumeUuid, PackageInstalledInfo res) {
11700        String pkgName = deletedPackage.packageName;
11701        boolean deletedPkg = true;
11702        boolean updatedSettings = false;
11703
11704        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11705                + deletedPackage);
11706        long origUpdateTime;
11707        if (pkg.mExtras != null) {
11708            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11709        } else {
11710            origUpdateTime = 0;
11711        }
11712
11713        // First delete the existing package while retaining the data directory
11714        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11715                res.removedInfo, true)) {
11716            // If the existing package wasn't successfully deleted
11717            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11718            deletedPkg = false;
11719        } else {
11720            // Successfully deleted the old package; proceed with replace.
11721
11722            // If deleted package lived in a container, give users a chance to
11723            // relinquish resources before killing.
11724            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11725                if (DEBUG_INSTALL) {
11726                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11727                }
11728                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11729                final ArrayList<String> pkgList = new ArrayList<String>(1);
11730                pkgList.add(deletedPackage.applicationInfo.packageName);
11731                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11732            }
11733
11734            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11735            try {
11736                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11737                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11738                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11739                        perUserInstalled, res, user);
11740                updatedSettings = true;
11741            } catch (PackageManagerException e) {
11742                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11743            }
11744        }
11745
11746        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11747            // remove package from internal structures.  Note that we want deletePackageX to
11748            // delete the package data and cache directories that it created in
11749            // scanPackageLocked, unless those directories existed before we even tried to
11750            // install.
11751            if(updatedSettings) {
11752                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11753                deletePackageLI(
11754                        pkgName, null, true, allUsers, perUserInstalled,
11755                        PackageManager.DELETE_KEEP_DATA,
11756                                res.removedInfo, true);
11757            }
11758            // Since we failed to install the new package we need to restore the old
11759            // package that we deleted.
11760            if (deletedPkg) {
11761                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11762                File restoreFile = new File(deletedPackage.codePath);
11763                // Parse old package
11764                boolean oldExternal = isExternal(deletedPackage);
11765                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11766                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11767                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11768                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11769                try {
11770                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11771                } catch (PackageManagerException e) {
11772                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11773                            + e.getMessage());
11774                    return;
11775                }
11776                // Restore of old package succeeded. Update permissions.
11777                // writer
11778                synchronized (mPackages) {
11779                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11780                            UPDATE_PERMISSIONS_ALL);
11781                    // can downgrade to reader
11782                    mSettings.writeLPr();
11783                }
11784                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11785            }
11786        }
11787    }
11788
11789    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11790            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11791            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11792            String volumeUuid, PackageInstalledInfo res) {
11793        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11794                + ", old=" + deletedPackage);
11795        boolean disabledSystem = false;
11796        boolean updatedSettings = false;
11797        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11798        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11799                != 0) {
11800            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11801        }
11802        String packageName = deletedPackage.packageName;
11803        if (packageName == null) {
11804            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11805                    "Attempt to delete null packageName.");
11806            return;
11807        }
11808        PackageParser.Package oldPkg;
11809        PackageSetting oldPkgSetting;
11810        // reader
11811        synchronized (mPackages) {
11812            oldPkg = mPackages.get(packageName);
11813            oldPkgSetting = mSettings.mPackages.get(packageName);
11814            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11815                    (oldPkgSetting == null)) {
11816                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11817                        "Couldn't find package:" + packageName + " information");
11818                return;
11819            }
11820        }
11821
11822        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11823        res.removedInfo.removedPackage = packageName;
11824        // Remove existing system package
11825        removePackageLI(oldPkgSetting, true);
11826        // writer
11827        synchronized (mPackages) {
11828            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11829            if (!disabledSystem && deletedPackage != null) {
11830                // We didn't need to disable the .apk as a current system package,
11831                // which means we are replacing another update that is already
11832                // installed.  We need to make sure to delete the older one's .apk.
11833                res.removedInfo.args = createInstallArgsForExisting(0,
11834                        deletedPackage.applicationInfo.getCodePath(),
11835                        deletedPackage.applicationInfo.getResourcePath(),
11836                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11837            } else {
11838                res.removedInfo.args = null;
11839            }
11840        }
11841
11842        // Successfully disabled the old package. Now proceed with re-installation
11843        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11844
11845        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11846        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11847
11848        PackageParser.Package newPackage = null;
11849        try {
11850            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11851            if (newPackage.mExtras != null) {
11852                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11853                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11854                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11855
11856                // is the update attempting to change shared user? that isn't going to work...
11857                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11858                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11859                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11860                            + " to " + newPkgSetting.sharedUser);
11861                    updatedSettings = true;
11862                }
11863            }
11864
11865            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11866                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11867                        perUserInstalled, res, user);
11868                updatedSettings = true;
11869            }
11870
11871        } catch (PackageManagerException e) {
11872            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11873        }
11874
11875        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11876            // Re installation failed. Restore old information
11877            // Remove new pkg information
11878            if (newPackage != null) {
11879                removeInstalledPackageLI(newPackage, true);
11880            }
11881            // Add back the old system package
11882            try {
11883                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11884            } catch (PackageManagerException e) {
11885                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11886            }
11887            // Restore the old system information in Settings
11888            synchronized (mPackages) {
11889                if (disabledSystem) {
11890                    mSettings.enableSystemPackageLPw(packageName);
11891                }
11892                if (updatedSettings) {
11893                    mSettings.setInstallerPackageName(packageName,
11894                            oldPkgSetting.installerPackageName);
11895                }
11896                mSettings.writeLPr();
11897            }
11898        }
11899    }
11900
11901    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11902            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11903            UserHandle user) {
11904        String pkgName = newPackage.packageName;
11905        synchronized (mPackages) {
11906            //write settings. the installStatus will be incomplete at this stage.
11907            //note that the new package setting would have already been
11908            //added to mPackages. It hasn't been persisted yet.
11909            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11910            mSettings.writeLPr();
11911        }
11912
11913        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11914
11915        synchronized (mPackages) {
11916            updatePermissionsLPw(newPackage.packageName, newPackage,
11917                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11918                            ? UPDATE_PERMISSIONS_ALL : 0));
11919            // For system-bundled packages, we assume that installing an upgraded version
11920            // of the package implies that the user actually wants to run that new code,
11921            // so we enable the package.
11922            PackageSetting ps = mSettings.mPackages.get(pkgName);
11923            if (ps != null) {
11924                if (isSystemApp(newPackage)) {
11925                    // NB: implicit assumption that system package upgrades apply to all users
11926                    if (DEBUG_INSTALL) {
11927                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11928                    }
11929                    if (res.origUsers != null) {
11930                        for (int userHandle : res.origUsers) {
11931                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11932                                    userHandle, installerPackageName);
11933                        }
11934                    }
11935                    // Also convey the prior install/uninstall state
11936                    if (allUsers != null && perUserInstalled != null) {
11937                        for (int i = 0; i < allUsers.length; i++) {
11938                            if (DEBUG_INSTALL) {
11939                                Slog.d(TAG, "    user " + allUsers[i]
11940                                        + " => " + perUserInstalled[i]);
11941                            }
11942                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11943                        }
11944                        // these install state changes will be persisted in the
11945                        // upcoming call to mSettings.writeLPr().
11946                    }
11947                }
11948                // It's implied that when a user requests installation, they want the app to be
11949                // installed and enabled.
11950                int userId = user.getIdentifier();
11951                if (userId != UserHandle.USER_ALL) {
11952                    ps.setInstalled(true, userId);
11953                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11954                }
11955            }
11956            res.name = pkgName;
11957            res.uid = newPackage.applicationInfo.uid;
11958            res.pkg = newPackage;
11959            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11960            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11961            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11962            //to update install status
11963            mSettings.writeLPr();
11964        }
11965    }
11966
11967    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11968        final int installFlags = args.installFlags;
11969        final String installerPackageName = args.installerPackageName;
11970        final String volumeUuid = args.volumeUuid;
11971        final File tmpPackageFile = new File(args.getCodePath());
11972        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11973        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11974                || (args.volumeUuid != null));
11975        boolean replace = false;
11976        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
11977        if (args.move != null) {
11978            // moving a complete application; perfom an initial scan on the new install location
11979            scanFlags |= SCAN_INITIAL;
11980        }
11981        // Result object to be returned
11982        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11983
11984        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11985        // Retrieve PackageSettings and parse package
11986        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11987                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11988                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11989        PackageParser pp = new PackageParser();
11990        pp.setSeparateProcesses(mSeparateProcesses);
11991        pp.setDisplayMetrics(mMetrics);
11992
11993        final PackageParser.Package pkg;
11994        try {
11995            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11996        } catch (PackageParserException e) {
11997            res.setError("Failed parse during installPackageLI", e);
11998            return;
11999        }
12000
12001        // Mark that we have an install time CPU ABI override.
12002        pkg.cpuAbiOverride = args.abiOverride;
12003
12004        String pkgName = res.name = pkg.packageName;
12005        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12006            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12007                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12008                return;
12009            }
12010        }
12011
12012        try {
12013            pp.collectCertificates(pkg, parseFlags);
12014            pp.collectManifestDigest(pkg);
12015        } catch (PackageParserException e) {
12016            res.setError("Failed collect during installPackageLI", e);
12017            return;
12018        }
12019
12020        /* If the installer passed in a manifest digest, compare it now. */
12021        if (args.manifestDigest != null) {
12022            if (DEBUG_INSTALL) {
12023                final String parsedManifest = pkg.manifestDigest == null ? "null"
12024                        : pkg.manifestDigest.toString();
12025                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12026                        + parsedManifest);
12027            }
12028
12029            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12030                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12031                return;
12032            }
12033        } else if (DEBUG_INSTALL) {
12034            final String parsedManifest = pkg.manifestDigest == null
12035                    ? "null" : pkg.manifestDigest.toString();
12036            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12037        }
12038
12039        // Get rid of all references to package scan path via parser.
12040        pp = null;
12041        String oldCodePath = null;
12042        boolean systemApp = false;
12043        synchronized (mPackages) {
12044            // Check if installing already existing package
12045            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12046                String oldName = mSettings.mRenamedPackages.get(pkgName);
12047                if (pkg.mOriginalPackages != null
12048                        && pkg.mOriginalPackages.contains(oldName)
12049                        && mPackages.containsKey(oldName)) {
12050                    // This package is derived from an original package,
12051                    // and this device has been updating from that original
12052                    // name.  We must continue using the original name, so
12053                    // rename the new package here.
12054                    pkg.setPackageName(oldName);
12055                    pkgName = pkg.packageName;
12056                    replace = true;
12057                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12058                            + oldName + " pkgName=" + pkgName);
12059                } else if (mPackages.containsKey(pkgName)) {
12060                    // This package, under its official name, already exists
12061                    // on the device; we should replace it.
12062                    replace = true;
12063                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12064                }
12065
12066                // Prevent apps opting out from runtime permissions
12067                if (replace) {
12068                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12069                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12070                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12071                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12072                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12073                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12074                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12075                                        + " doesn't support runtime permissions but the old"
12076                                        + " target SDK " + oldTargetSdk + " does.");
12077                        return;
12078                    }
12079                }
12080            }
12081
12082            PackageSetting ps = mSettings.mPackages.get(pkgName);
12083            if (ps != null) {
12084                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12085
12086                // Quick sanity check that we're signed correctly if updating;
12087                // we'll check this again later when scanning, but we want to
12088                // bail early here before tripping over redefined permissions.
12089                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12090                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12091                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12092                                + pkg.packageName + " upgrade keys do not match the "
12093                                + "previously installed version");
12094                        return;
12095                    }
12096                } else {
12097                    try {
12098                        verifySignaturesLP(ps, pkg);
12099                    } catch (PackageManagerException e) {
12100                        res.setError(e.error, e.getMessage());
12101                        return;
12102                    }
12103                }
12104
12105                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12106                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12107                    systemApp = (ps.pkg.applicationInfo.flags &
12108                            ApplicationInfo.FLAG_SYSTEM) != 0;
12109                }
12110                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12111            }
12112
12113            // Check whether the newly-scanned package wants to define an already-defined perm
12114            int N = pkg.permissions.size();
12115            for (int i = N-1; i >= 0; i--) {
12116                PackageParser.Permission perm = pkg.permissions.get(i);
12117                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12118                if (bp != null) {
12119                    // If the defining package is signed with our cert, it's okay.  This
12120                    // also includes the "updating the same package" case, of course.
12121                    // "updating same package" could also involve key-rotation.
12122                    final boolean sigsOk;
12123                    if (bp.sourcePackage.equals(pkg.packageName)
12124                            && (bp.packageSetting instanceof PackageSetting)
12125                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12126                                    scanFlags))) {
12127                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12128                    } else {
12129                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12130                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12131                    }
12132                    if (!sigsOk) {
12133                        // If the owning package is the system itself, we log but allow
12134                        // install to proceed; we fail the install on all other permission
12135                        // redefinitions.
12136                        if (!bp.sourcePackage.equals("android")) {
12137                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12138                                    + pkg.packageName + " attempting to redeclare permission "
12139                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12140                            res.origPermission = perm.info.name;
12141                            res.origPackage = bp.sourcePackage;
12142                            return;
12143                        } else {
12144                            Slog.w(TAG, "Package " + pkg.packageName
12145                                    + " attempting to redeclare system permission "
12146                                    + perm.info.name + "; ignoring new declaration");
12147                            pkg.permissions.remove(i);
12148                        }
12149                    }
12150                }
12151            }
12152
12153        }
12154
12155        if (systemApp && onExternal) {
12156            // Disable updates to system apps on sdcard
12157            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12158                    "Cannot install updates to system apps on sdcard");
12159            return;
12160        }
12161
12162        if (args.move != null) {
12163            // We did an in-place move, so dex is ready to roll
12164            scanFlags |= SCAN_NO_DEX;
12165            scanFlags |= SCAN_MOVE;
12166        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12167            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12168            scanFlags |= SCAN_NO_DEX;
12169
12170            try {
12171                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12172                        true /* extract libs */);
12173            } catch (PackageManagerException pme) {
12174                Slog.e(TAG, "Error deriving application ABI", pme);
12175                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12176                return;
12177            }
12178
12179            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12180            int result = mPackageDexOptimizer
12181                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12182                            false /* defer */, false /* inclDependencies */);
12183            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12184                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12185                return;
12186            }
12187        }
12188
12189        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12190            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12191            return;
12192        }
12193
12194        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12195
12196        if (replace) {
12197            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12198                    installerPackageName, volumeUuid, res);
12199        } else {
12200            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12201                    args.user, installerPackageName, volumeUuid, res);
12202        }
12203        synchronized (mPackages) {
12204            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12205            if (ps != null) {
12206                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12207            }
12208        }
12209    }
12210
12211    private void startIntentFilterVerifications(int userId, boolean replacing,
12212            PackageParser.Package pkg) {
12213        if (mIntentFilterVerifierComponent == null) {
12214            Slog.w(TAG, "No IntentFilter verification will not be done as "
12215                    + "there is no IntentFilterVerifier available!");
12216            return;
12217        }
12218
12219        final int verifierUid = getPackageUid(
12220                mIntentFilterVerifierComponent.getPackageName(),
12221                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12222
12223        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12224        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12225        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12226        mHandler.sendMessage(msg);
12227    }
12228
12229    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12230            PackageParser.Package pkg) {
12231        int size = pkg.activities.size();
12232        if (size == 0) {
12233            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12234                    "No activity, so no need to verify any IntentFilter!");
12235            return;
12236        }
12237
12238        final boolean hasDomainURLs = hasDomainURLs(pkg);
12239        if (!hasDomainURLs) {
12240            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12241                    "No domain URLs, so no need to verify any IntentFilter!");
12242            return;
12243        }
12244
12245        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12246                + " if any IntentFilter from the " + size
12247                + " Activities needs verification ...");
12248
12249        int count = 0;
12250        final String packageName = pkg.packageName;
12251
12252        synchronized (mPackages) {
12253            // If this is a new install and we see that we've already run verification for this
12254            // package, we have nothing to do: it means the state was restored from backup.
12255            if (!replacing) {
12256                IntentFilterVerificationInfo ivi =
12257                        mSettings.getIntentFilterVerificationLPr(packageName);
12258                if (ivi != null) {
12259                    if (DEBUG_DOMAIN_VERIFICATION) {
12260                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12261                                + ivi.getStatusString());
12262                    }
12263                    return;
12264                }
12265            }
12266
12267            // If any filters need to be verified, then all need to be.
12268            boolean needToVerify = false;
12269            for (PackageParser.Activity a : pkg.activities) {
12270                for (ActivityIntentInfo filter : a.intents) {
12271                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12272                        if (DEBUG_DOMAIN_VERIFICATION) {
12273                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12274                        }
12275                        needToVerify = true;
12276                        break;
12277                    }
12278                }
12279            }
12280
12281            if (needToVerify) {
12282                final int verificationId = mIntentFilterVerificationToken++;
12283                for (PackageParser.Activity a : pkg.activities) {
12284                    for (ActivityIntentInfo filter : a.intents) {
12285                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12286                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12287                                    "Verification needed for IntentFilter:" + filter.toString());
12288                            mIntentFilterVerifier.addOneIntentFilterVerification(
12289                                    verifierUid, userId, verificationId, filter, packageName);
12290                            count++;
12291                        }
12292                    }
12293                }
12294            }
12295        }
12296
12297        if (count > 0) {
12298            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12299                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12300                    +  " for userId:" + userId);
12301            mIntentFilterVerifier.startVerifications(userId);
12302        } else {
12303            if (DEBUG_DOMAIN_VERIFICATION) {
12304                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12305            }
12306        }
12307    }
12308
12309    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12310        final ComponentName cn  = filter.activity.getComponentName();
12311        final String packageName = cn.getPackageName();
12312
12313        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12314                packageName);
12315        if (ivi == null) {
12316            return true;
12317        }
12318        int status = ivi.getStatus();
12319        switch (status) {
12320            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12321            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12322                return true;
12323
12324            default:
12325                // Nothing to do
12326                return false;
12327        }
12328    }
12329
12330    private static boolean isMultiArch(PackageSetting ps) {
12331        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12332    }
12333
12334    private static boolean isMultiArch(ApplicationInfo info) {
12335        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12336    }
12337
12338    private static boolean isExternal(PackageParser.Package pkg) {
12339        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12340    }
12341
12342    private static boolean isExternal(PackageSetting ps) {
12343        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12344    }
12345
12346    private static boolean isExternal(ApplicationInfo info) {
12347        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12348    }
12349
12350    private static boolean isSystemApp(PackageParser.Package pkg) {
12351        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12352    }
12353
12354    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12355        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12356    }
12357
12358    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12359        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12360    }
12361
12362    private static boolean isSystemApp(PackageSetting ps) {
12363        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12364    }
12365
12366    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12367        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12368    }
12369
12370    private int packageFlagsToInstallFlags(PackageSetting ps) {
12371        int installFlags = 0;
12372        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12373            // This existing package was an external ASEC install when we have
12374            // the external flag without a UUID
12375            installFlags |= PackageManager.INSTALL_EXTERNAL;
12376        }
12377        if (ps.isForwardLocked()) {
12378            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12379        }
12380        return installFlags;
12381    }
12382
12383    private void deleteTempPackageFiles() {
12384        final FilenameFilter filter = new FilenameFilter() {
12385            public boolean accept(File dir, String name) {
12386                return name.startsWith("vmdl") && name.endsWith(".tmp");
12387            }
12388        };
12389        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12390            file.delete();
12391        }
12392    }
12393
12394    @Override
12395    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12396            int flags) {
12397        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12398                flags);
12399    }
12400
12401    @Override
12402    public void deletePackage(final String packageName,
12403            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12404        mContext.enforceCallingOrSelfPermission(
12405                android.Manifest.permission.DELETE_PACKAGES, null);
12406        Preconditions.checkNotNull(packageName);
12407        Preconditions.checkNotNull(observer);
12408        final int uid = Binder.getCallingUid();
12409        if (UserHandle.getUserId(uid) != userId) {
12410            mContext.enforceCallingPermission(
12411                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12412                    "deletePackage for user " + userId);
12413        }
12414        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12415            try {
12416                observer.onPackageDeleted(packageName,
12417                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12418            } catch (RemoteException re) {
12419            }
12420            return;
12421        }
12422
12423        boolean uninstallBlocked = false;
12424        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12425            int[] users = sUserManager.getUserIds();
12426            for (int i = 0; i < users.length; ++i) {
12427                if (getBlockUninstallForUser(packageName, users[i])) {
12428                    uninstallBlocked = true;
12429                    break;
12430                }
12431            }
12432        } else {
12433            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12434        }
12435        if (uninstallBlocked) {
12436            try {
12437                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12438                        null);
12439            } catch (RemoteException re) {
12440            }
12441            return;
12442        }
12443
12444        if (DEBUG_REMOVE) {
12445            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12446        }
12447        // Queue up an async operation since the package deletion may take a little while.
12448        mHandler.post(new Runnable() {
12449            public void run() {
12450                mHandler.removeCallbacks(this);
12451                final int returnCode = deletePackageX(packageName, userId, flags);
12452                if (observer != null) {
12453                    try {
12454                        observer.onPackageDeleted(packageName, returnCode, null);
12455                    } catch (RemoteException e) {
12456                        Log.i(TAG, "Observer no longer exists.");
12457                    } //end catch
12458                } //end if
12459            } //end run
12460        });
12461    }
12462
12463    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12464        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12465                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12466        try {
12467            if (dpm != null) {
12468                if (dpm.isDeviceOwner(packageName)) {
12469                    return true;
12470                }
12471                int[] users;
12472                if (userId == UserHandle.USER_ALL) {
12473                    users = sUserManager.getUserIds();
12474                } else {
12475                    users = new int[]{userId};
12476                }
12477                for (int i = 0; i < users.length; ++i) {
12478                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12479                        return true;
12480                    }
12481                }
12482            }
12483        } catch (RemoteException e) {
12484        }
12485        return false;
12486    }
12487
12488    /**
12489     *  This method is an internal method that could be get invoked either
12490     *  to delete an installed package or to clean up a failed installation.
12491     *  After deleting an installed package, a broadcast is sent to notify any
12492     *  listeners that the package has been installed. For cleaning up a failed
12493     *  installation, the broadcast is not necessary since the package's
12494     *  installation wouldn't have sent the initial broadcast either
12495     *  The key steps in deleting a package are
12496     *  deleting the package information in internal structures like mPackages,
12497     *  deleting the packages base directories through installd
12498     *  updating mSettings to reflect current status
12499     *  persisting settings for later use
12500     *  sending a broadcast if necessary
12501     */
12502    private int deletePackageX(String packageName, int userId, int flags) {
12503        final PackageRemovedInfo info = new PackageRemovedInfo();
12504        final boolean res;
12505
12506        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12507                ? UserHandle.ALL : new UserHandle(userId);
12508
12509        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12510            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12511            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12512        }
12513
12514        boolean removedForAllUsers = false;
12515        boolean systemUpdate = false;
12516
12517        // for the uninstall-updates case and restricted profiles, remember the per-
12518        // userhandle installed state
12519        int[] allUsers;
12520        boolean[] perUserInstalled;
12521        synchronized (mPackages) {
12522            PackageSetting ps = mSettings.mPackages.get(packageName);
12523            allUsers = sUserManager.getUserIds();
12524            perUserInstalled = new boolean[allUsers.length];
12525            for (int i = 0; i < allUsers.length; i++) {
12526                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12527            }
12528        }
12529
12530        synchronized (mInstallLock) {
12531            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12532            res = deletePackageLI(packageName, removeForUser,
12533                    true, allUsers, perUserInstalled,
12534                    flags | REMOVE_CHATTY, info, true);
12535            systemUpdate = info.isRemovedPackageSystemUpdate;
12536            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12537                removedForAllUsers = true;
12538            }
12539            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12540                    + " removedForAllUsers=" + removedForAllUsers);
12541        }
12542
12543        if (res) {
12544            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12545
12546            // If the removed package was a system update, the old system package
12547            // was re-enabled; we need to broadcast this information
12548            if (systemUpdate) {
12549                Bundle extras = new Bundle(1);
12550                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12551                        ? info.removedAppId : info.uid);
12552                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12553
12554                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12555                        extras, null, null, null);
12556                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12557                        extras, null, null, null);
12558                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12559                        null, packageName, null, null);
12560            }
12561        }
12562        // Force a gc here.
12563        Runtime.getRuntime().gc();
12564        // Delete the resources here after sending the broadcast to let
12565        // other processes clean up before deleting resources.
12566        if (info.args != null) {
12567            synchronized (mInstallLock) {
12568                info.args.doPostDeleteLI(true);
12569            }
12570        }
12571
12572        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12573    }
12574
12575    class PackageRemovedInfo {
12576        String removedPackage;
12577        int uid = -1;
12578        int removedAppId = -1;
12579        int[] removedUsers = null;
12580        boolean isRemovedPackageSystemUpdate = false;
12581        // Clean up resources deleted packages.
12582        InstallArgs args = null;
12583
12584        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12585            Bundle extras = new Bundle(1);
12586            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12587            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12588            if (replacing) {
12589                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12590            }
12591            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12592            if (removedPackage != null) {
12593                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12594                        extras, null, null, removedUsers);
12595                if (fullRemove && !replacing) {
12596                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12597                            extras, null, null, removedUsers);
12598                }
12599            }
12600            if (removedAppId >= 0) {
12601                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12602                        removedUsers);
12603            }
12604        }
12605    }
12606
12607    /*
12608     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12609     * flag is not set, the data directory is removed as well.
12610     * make sure this flag is set for partially installed apps. If not its meaningless to
12611     * delete a partially installed application.
12612     */
12613    private void removePackageDataLI(PackageSetting ps,
12614            int[] allUserHandles, boolean[] perUserInstalled,
12615            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12616        String packageName = ps.name;
12617        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12618        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12619        // Retrieve object to delete permissions for shared user later on
12620        final PackageSetting deletedPs;
12621        // reader
12622        synchronized (mPackages) {
12623            deletedPs = mSettings.mPackages.get(packageName);
12624            if (outInfo != null) {
12625                outInfo.removedPackage = packageName;
12626                outInfo.removedUsers = deletedPs != null
12627                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12628                        : null;
12629            }
12630        }
12631        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12632            removeDataDirsLI(ps.volumeUuid, packageName);
12633            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12634        }
12635        // writer
12636        synchronized (mPackages) {
12637            if (deletedPs != null) {
12638                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12639                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12640                    clearDefaultBrowserIfNeeded(packageName);
12641                    if (outInfo != null) {
12642                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12643                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12644                    }
12645                    updatePermissionsLPw(deletedPs.name, null, 0);
12646                    if (deletedPs.sharedUser != null) {
12647                        // Remove permissions associated with package. Since runtime
12648                        // permissions are per user we have to kill the removed package
12649                        // or packages running under the shared user of the removed
12650                        // package if revoking the permissions requested only by the removed
12651                        // package is successful and this causes a change in gids.
12652                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12653                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12654                                    userId);
12655                            if (userIdToKill == UserHandle.USER_ALL
12656                                    || userIdToKill >= UserHandle.USER_OWNER) {
12657                                // If gids changed for this user, kill all affected packages.
12658                                mHandler.post(new Runnable() {
12659                                    @Override
12660                                    public void run() {
12661                                        // This has to happen with no lock held.
12662                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12663                                                KILL_APP_REASON_GIDS_CHANGED);
12664                                    }
12665                                });
12666                            break;
12667                            }
12668                        }
12669                    }
12670                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12671                }
12672                // make sure to preserve per-user disabled state if this removal was just
12673                // a downgrade of a system app to the factory package
12674                if (allUserHandles != null && perUserInstalled != null) {
12675                    if (DEBUG_REMOVE) {
12676                        Slog.d(TAG, "Propagating install state across downgrade");
12677                    }
12678                    for (int i = 0; i < allUserHandles.length; i++) {
12679                        if (DEBUG_REMOVE) {
12680                            Slog.d(TAG, "    user " + allUserHandles[i]
12681                                    + " => " + perUserInstalled[i]);
12682                        }
12683                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12684                    }
12685                }
12686            }
12687            // can downgrade to reader
12688            if (writeSettings) {
12689                // Save settings now
12690                mSettings.writeLPr();
12691            }
12692        }
12693        if (outInfo != null) {
12694            // A user ID was deleted here. Go through all users and remove it
12695            // from KeyStore.
12696            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12697        }
12698    }
12699
12700    static boolean locationIsPrivileged(File path) {
12701        try {
12702            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12703                    .getCanonicalPath();
12704            return path.getCanonicalPath().startsWith(privilegedAppDir);
12705        } catch (IOException e) {
12706            Slog.e(TAG, "Unable to access code path " + path);
12707        }
12708        return false;
12709    }
12710
12711    /*
12712     * Tries to delete system package.
12713     */
12714    private boolean deleteSystemPackageLI(PackageSetting newPs,
12715            int[] allUserHandles, boolean[] perUserInstalled,
12716            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12717        final boolean applyUserRestrictions
12718                = (allUserHandles != null) && (perUserInstalled != null);
12719        PackageSetting disabledPs = null;
12720        // Confirm if the system package has been updated
12721        // An updated system app can be deleted. This will also have to restore
12722        // the system pkg from system partition
12723        // reader
12724        synchronized (mPackages) {
12725            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12726        }
12727        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12728                + " disabledPs=" + disabledPs);
12729        if (disabledPs == null) {
12730            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12731            return false;
12732        } else if (DEBUG_REMOVE) {
12733            Slog.d(TAG, "Deleting system pkg from data partition");
12734        }
12735        if (DEBUG_REMOVE) {
12736            if (applyUserRestrictions) {
12737                Slog.d(TAG, "Remembering install states:");
12738                for (int i = 0; i < allUserHandles.length; i++) {
12739                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12740                }
12741            }
12742        }
12743        // Delete the updated package
12744        outInfo.isRemovedPackageSystemUpdate = true;
12745        if (disabledPs.versionCode < newPs.versionCode) {
12746            // Delete data for downgrades
12747            flags &= ~PackageManager.DELETE_KEEP_DATA;
12748        } else {
12749            // Preserve data by setting flag
12750            flags |= PackageManager.DELETE_KEEP_DATA;
12751        }
12752        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12753                allUserHandles, perUserInstalled, outInfo, writeSettings);
12754        if (!ret) {
12755            return false;
12756        }
12757        // writer
12758        synchronized (mPackages) {
12759            // Reinstate the old system package
12760            mSettings.enableSystemPackageLPw(newPs.name);
12761            // Remove any native libraries from the upgraded package.
12762            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12763        }
12764        // Install the system package
12765        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12766        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12767        if (locationIsPrivileged(disabledPs.codePath)) {
12768            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12769        }
12770
12771        final PackageParser.Package newPkg;
12772        try {
12773            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12774        } catch (PackageManagerException e) {
12775            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12776            return false;
12777        }
12778
12779        // writer
12780        synchronized (mPackages) {
12781            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12782            updatePermissionsLPw(newPkg.packageName, newPkg,
12783                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12784            if (applyUserRestrictions) {
12785                if (DEBUG_REMOVE) {
12786                    Slog.d(TAG, "Propagating install state across reinstall");
12787                }
12788                for (int i = 0; i < allUserHandles.length; i++) {
12789                    if (DEBUG_REMOVE) {
12790                        Slog.d(TAG, "    user " + allUserHandles[i]
12791                                + " => " + perUserInstalled[i]);
12792                    }
12793                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12794                }
12795                // Regardless of writeSettings we need to ensure that this restriction
12796                // state propagation is persisted
12797                mSettings.writeAllUsersPackageRestrictionsLPr();
12798            }
12799            // can downgrade to reader here
12800            if (writeSettings) {
12801                mSettings.writeLPr();
12802            }
12803        }
12804        return true;
12805    }
12806
12807    private boolean deleteInstalledPackageLI(PackageSetting ps,
12808            boolean deleteCodeAndResources, int flags,
12809            int[] allUserHandles, boolean[] perUserInstalled,
12810            PackageRemovedInfo outInfo, boolean writeSettings) {
12811        if (outInfo != null) {
12812            outInfo.uid = ps.appId;
12813        }
12814
12815        // Delete package data from internal structures and also remove data if flag is set
12816        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12817
12818        // Delete application code and resources
12819        if (deleteCodeAndResources && (outInfo != null)) {
12820            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12821                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12822            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12823        }
12824        return true;
12825    }
12826
12827    @Override
12828    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12829            int userId) {
12830        mContext.enforceCallingOrSelfPermission(
12831                android.Manifest.permission.DELETE_PACKAGES, null);
12832        synchronized (mPackages) {
12833            PackageSetting ps = mSettings.mPackages.get(packageName);
12834            if (ps == null) {
12835                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12836                return false;
12837            }
12838            if (!ps.getInstalled(userId)) {
12839                // Can't block uninstall for an app that is not installed or enabled.
12840                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12841                return false;
12842            }
12843            ps.setBlockUninstall(blockUninstall, userId);
12844            mSettings.writePackageRestrictionsLPr(userId);
12845        }
12846        return true;
12847    }
12848
12849    @Override
12850    public boolean getBlockUninstallForUser(String packageName, int userId) {
12851        synchronized (mPackages) {
12852            PackageSetting ps = mSettings.mPackages.get(packageName);
12853            if (ps == null) {
12854                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12855                return false;
12856            }
12857            return ps.getBlockUninstall(userId);
12858        }
12859    }
12860
12861    /*
12862     * This method handles package deletion in general
12863     */
12864    private boolean deletePackageLI(String packageName, UserHandle user,
12865            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12866            int flags, PackageRemovedInfo outInfo,
12867            boolean writeSettings) {
12868        if (packageName == null) {
12869            Slog.w(TAG, "Attempt to delete null packageName.");
12870            return false;
12871        }
12872        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12873        PackageSetting ps;
12874        boolean dataOnly = false;
12875        int removeUser = -1;
12876        int appId = -1;
12877        synchronized (mPackages) {
12878            ps = mSettings.mPackages.get(packageName);
12879            if (ps == null) {
12880                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12881                return false;
12882            }
12883            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12884                    && user.getIdentifier() != UserHandle.USER_ALL) {
12885                // The caller is asking that the package only be deleted for a single
12886                // user.  To do this, we just mark its uninstalled state and delete
12887                // its data.  If this is a system app, we only allow this to happen if
12888                // they have set the special DELETE_SYSTEM_APP which requests different
12889                // semantics than normal for uninstalling system apps.
12890                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12891                ps.setUserState(user.getIdentifier(),
12892                        COMPONENT_ENABLED_STATE_DEFAULT,
12893                        false, //installed
12894                        true,  //stopped
12895                        true,  //notLaunched
12896                        false, //hidden
12897                        null, null, null,
12898                        false, // blockUninstall
12899                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12900                if (!isSystemApp(ps)) {
12901                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12902                        // Other user still have this package installed, so all
12903                        // we need to do is clear this user's data and save that
12904                        // it is uninstalled.
12905                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12906                        removeUser = user.getIdentifier();
12907                        appId = ps.appId;
12908                        scheduleWritePackageRestrictionsLocked(removeUser);
12909                    } else {
12910                        // We need to set it back to 'installed' so the uninstall
12911                        // broadcasts will be sent correctly.
12912                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12913                        ps.setInstalled(true, user.getIdentifier());
12914                    }
12915                } else {
12916                    // This is a system app, so we assume that the
12917                    // other users still have this package installed, so all
12918                    // we need to do is clear this user's data and save that
12919                    // it is uninstalled.
12920                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12921                    removeUser = user.getIdentifier();
12922                    appId = ps.appId;
12923                    scheduleWritePackageRestrictionsLocked(removeUser);
12924                }
12925            }
12926        }
12927
12928        if (removeUser >= 0) {
12929            // From above, we determined that we are deleting this only
12930            // for a single user.  Continue the work here.
12931            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12932            if (outInfo != null) {
12933                outInfo.removedPackage = packageName;
12934                outInfo.removedAppId = appId;
12935                outInfo.removedUsers = new int[] {removeUser};
12936            }
12937            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12938            removeKeystoreDataIfNeeded(removeUser, appId);
12939            schedulePackageCleaning(packageName, removeUser, false);
12940            synchronized (mPackages) {
12941                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12942                    scheduleWritePackageRestrictionsLocked(removeUser);
12943                }
12944                revokeRuntimePermissionsAndClearAllFlagsLocked(ps.getPermissionsState(),
12945                        removeUser);
12946            }
12947            return true;
12948        }
12949
12950        if (dataOnly) {
12951            // Delete application data first
12952            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12953            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12954            return true;
12955        }
12956
12957        boolean ret = false;
12958        if (isSystemApp(ps)) {
12959            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12960            // When an updated system application is deleted we delete the existing resources as well and
12961            // fall back to existing code in system partition
12962            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12963                    flags, outInfo, writeSettings);
12964        } else {
12965            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12966            // Kill application pre-emptively especially for apps on sd.
12967            killApplication(packageName, ps.appId, "uninstall pkg");
12968            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12969                    allUserHandles, perUserInstalled,
12970                    outInfo, writeSettings);
12971        }
12972
12973        return ret;
12974    }
12975
12976    private final class ClearStorageConnection implements ServiceConnection {
12977        IMediaContainerService mContainerService;
12978
12979        @Override
12980        public void onServiceConnected(ComponentName name, IBinder service) {
12981            synchronized (this) {
12982                mContainerService = IMediaContainerService.Stub.asInterface(service);
12983                notifyAll();
12984            }
12985        }
12986
12987        @Override
12988        public void onServiceDisconnected(ComponentName name) {
12989        }
12990    }
12991
12992    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12993        final boolean mounted;
12994        if (Environment.isExternalStorageEmulated()) {
12995            mounted = true;
12996        } else {
12997            final String status = Environment.getExternalStorageState();
12998
12999            mounted = status.equals(Environment.MEDIA_MOUNTED)
13000                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13001        }
13002
13003        if (!mounted) {
13004            return;
13005        }
13006
13007        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13008        int[] users;
13009        if (userId == UserHandle.USER_ALL) {
13010            users = sUserManager.getUserIds();
13011        } else {
13012            users = new int[] { userId };
13013        }
13014        final ClearStorageConnection conn = new ClearStorageConnection();
13015        if (mContext.bindServiceAsUser(
13016                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13017            try {
13018                for (int curUser : users) {
13019                    long timeout = SystemClock.uptimeMillis() + 5000;
13020                    synchronized (conn) {
13021                        long now = SystemClock.uptimeMillis();
13022                        while (conn.mContainerService == null && now < timeout) {
13023                            try {
13024                                conn.wait(timeout - now);
13025                            } catch (InterruptedException e) {
13026                            }
13027                        }
13028                    }
13029                    if (conn.mContainerService == null) {
13030                        return;
13031                    }
13032
13033                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13034                    clearDirectory(conn.mContainerService,
13035                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13036                    if (allData) {
13037                        clearDirectory(conn.mContainerService,
13038                                userEnv.buildExternalStorageAppDataDirs(packageName));
13039                        clearDirectory(conn.mContainerService,
13040                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13041                    }
13042                }
13043            } finally {
13044                mContext.unbindService(conn);
13045            }
13046        }
13047    }
13048
13049    @Override
13050    public void clearApplicationUserData(final String packageName,
13051            final IPackageDataObserver observer, final int userId) {
13052        mContext.enforceCallingOrSelfPermission(
13053                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13054        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13055        // Queue up an async operation since the package deletion may take a little while.
13056        mHandler.post(new Runnable() {
13057            public void run() {
13058                mHandler.removeCallbacks(this);
13059                final boolean succeeded;
13060                synchronized (mInstallLock) {
13061                    succeeded = clearApplicationUserDataLI(packageName, userId);
13062                }
13063                clearExternalStorageDataSync(packageName, userId, true);
13064                if (succeeded) {
13065                    // invoke DeviceStorageMonitor's update method to clear any notifications
13066                    DeviceStorageMonitorInternal
13067                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13068                    if (dsm != null) {
13069                        dsm.checkMemory();
13070                    }
13071                }
13072                if(observer != null) {
13073                    try {
13074                        observer.onRemoveCompleted(packageName, succeeded);
13075                    } catch (RemoteException e) {
13076                        Log.i(TAG, "Observer no longer exists.");
13077                    }
13078                } //end if observer
13079            } //end run
13080        });
13081    }
13082
13083    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13084        if (packageName == null) {
13085            Slog.w(TAG, "Attempt to delete null packageName.");
13086            return false;
13087        }
13088
13089        // Try finding details about the requested package
13090        PackageParser.Package pkg;
13091        synchronized (mPackages) {
13092            pkg = mPackages.get(packageName);
13093            if (pkg == null) {
13094                final PackageSetting ps = mSettings.mPackages.get(packageName);
13095                if (ps != null) {
13096                    pkg = ps.pkg;
13097                }
13098            }
13099
13100            if (pkg == null) {
13101                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13102                return false;
13103            }
13104
13105            PackageSetting ps = (PackageSetting) pkg.mExtras;
13106            PermissionsState permissionsState = ps.getPermissionsState();
13107            revokeRuntimePermissionsAndClearUserSetFlagsLocked(permissionsState, userId);
13108        }
13109
13110        // Always delete data directories for package, even if we found no other
13111        // record of app. This helps users recover from UID mismatches without
13112        // resorting to a full data wipe.
13113        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13114        if (retCode < 0) {
13115            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13116            return false;
13117        }
13118
13119        final int appId = pkg.applicationInfo.uid;
13120        removeKeystoreDataIfNeeded(userId, appId);
13121
13122        // Create a native library symlink only if we have native libraries
13123        // and if the native libraries are 32 bit libraries. We do not provide
13124        // this symlink for 64 bit libraries.
13125        if (pkg.applicationInfo.primaryCpuAbi != null &&
13126                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13127            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13128            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13129                    nativeLibPath, userId) < 0) {
13130                Slog.w(TAG, "Failed linking native library dir");
13131                return false;
13132            }
13133        }
13134
13135        return true;
13136    }
13137
13138
13139    /**
13140     * Revokes granted runtime permissions and clears resettable flags
13141     * which are flags that can be set by a user interaction.
13142     *
13143     * @param permissionsState The permission state to reset.
13144     * @param userId The device user for which to do a reset.
13145     */
13146    private void revokeRuntimePermissionsAndClearUserSetFlagsLocked(
13147            PermissionsState permissionsState, int userId) {
13148        final int userSetFlags = PackageManager.FLAG_PERMISSION_USER_SET
13149                | PackageManager.FLAG_PERMISSION_USER_FIXED
13150                | PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13151
13152        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId, userSetFlags);
13153    }
13154
13155    /**
13156     * Revokes granted runtime permissions and clears all flags.
13157     *
13158     * @param permissionsState The permission state to reset.
13159     * @param userId The device user for which to do a reset.
13160     */
13161    private void revokeRuntimePermissionsAndClearAllFlagsLocked(
13162            PermissionsState permissionsState, int userId) {
13163        revokeRuntimePermissionsAndClearFlagsLocked(permissionsState, userId,
13164                PackageManager.MASK_PERMISSION_FLAGS);
13165    }
13166
13167    /**
13168     * Revokes granted runtime permissions and clears certain flags.
13169     *
13170     * @param permissionsState The permission state to reset.
13171     * @param userId The device user for which to do a reset.
13172     * @param flags The flags that is going to be reset.
13173     */
13174    private void revokeRuntimePermissionsAndClearFlagsLocked(
13175            PermissionsState permissionsState, final int userId, int flags) {
13176        boolean needsWrite = false;
13177
13178        for (PermissionState state : permissionsState.getRuntimePermissionStates(userId)) {
13179            BasePermission bp = mSettings.mPermissions.get(state.getName());
13180            if (bp != null) {
13181                permissionsState.revokeRuntimePermission(bp, userId);
13182                permissionsState.updatePermissionFlags(bp, userId, flags, 0);
13183                needsWrite = true;
13184            }
13185        }
13186
13187        // Ensure default permissions are never cleared.
13188        mHandler.post(new Runnable() {
13189            @Override
13190            public void run() {
13191                mDefaultPermissionPolicy.grantDefaultPermissions(userId);
13192            }
13193        });
13194
13195        if (needsWrite) {
13196            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13197        }
13198    }
13199
13200    /**
13201     * Remove entries from the keystore daemon. Will only remove it if the
13202     * {@code appId} is valid.
13203     */
13204    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13205        if (appId < 0) {
13206            return;
13207        }
13208
13209        final KeyStore keyStore = KeyStore.getInstance();
13210        if (keyStore != null) {
13211            if (userId == UserHandle.USER_ALL) {
13212                for (final int individual : sUserManager.getUserIds()) {
13213                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13214                }
13215            } else {
13216                keyStore.clearUid(UserHandle.getUid(userId, appId));
13217            }
13218        } else {
13219            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13220        }
13221    }
13222
13223    @Override
13224    public void deleteApplicationCacheFiles(final String packageName,
13225            final IPackageDataObserver observer) {
13226        mContext.enforceCallingOrSelfPermission(
13227                android.Manifest.permission.DELETE_CACHE_FILES, null);
13228        // Queue up an async operation since the package deletion may take a little while.
13229        final int userId = UserHandle.getCallingUserId();
13230        mHandler.post(new Runnable() {
13231            public void run() {
13232                mHandler.removeCallbacks(this);
13233                final boolean succeded;
13234                synchronized (mInstallLock) {
13235                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13236                }
13237                clearExternalStorageDataSync(packageName, userId, false);
13238                if (observer != null) {
13239                    try {
13240                        observer.onRemoveCompleted(packageName, succeded);
13241                    } catch (RemoteException e) {
13242                        Log.i(TAG, "Observer no longer exists.");
13243                    }
13244                } //end if observer
13245            } //end run
13246        });
13247    }
13248
13249    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13250        if (packageName == null) {
13251            Slog.w(TAG, "Attempt to delete null packageName.");
13252            return false;
13253        }
13254        PackageParser.Package p;
13255        synchronized (mPackages) {
13256            p = mPackages.get(packageName);
13257        }
13258        if (p == null) {
13259            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13260            return false;
13261        }
13262        final ApplicationInfo applicationInfo = p.applicationInfo;
13263        if (applicationInfo == null) {
13264            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13265            return false;
13266        }
13267        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13268        if (retCode < 0) {
13269            Slog.w(TAG, "Couldn't remove cache files for package: "
13270                       + packageName + " u" + userId);
13271            return false;
13272        }
13273        return true;
13274    }
13275
13276    @Override
13277    public void getPackageSizeInfo(final String packageName, int userHandle,
13278            final IPackageStatsObserver observer) {
13279        mContext.enforceCallingOrSelfPermission(
13280                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13281        if (packageName == null) {
13282            throw new IllegalArgumentException("Attempt to get size of null packageName");
13283        }
13284
13285        PackageStats stats = new PackageStats(packageName, userHandle);
13286
13287        /*
13288         * Queue up an async operation since the package measurement may take a
13289         * little while.
13290         */
13291        Message msg = mHandler.obtainMessage(INIT_COPY);
13292        msg.obj = new MeasureParams(stats, observer);
13293        mHandler.sendMessage(msg);
13294    }
13295
13296    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13297            PackageStats pStats) {
13298        if (packageName == null) {
13299            Slog.w(TAG, "Attempt to get size of null packageName.");
13300            return false;
13301        }
13302        PackageParser.Package p;
13303        boolean dataOnly = false;
13304        String libDirRoot = null;
13305        String asecPath = null;
13306        PackageSetting ps = null;
13307        synchronized (mPackages) {
13308            p = mPackages.get(packageName);
13309            ps = mSettings.mPackages.get(packageName);
13310            if(p == null) {
13311                dataOnly = true;
13312                if((ps == null) || (ps.pkg == null)) {
13313                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13314                    return false;
13315                }
13316                p = ps.pkg;
13317            }
13318            if (ps != null) {
13319                libDirRoot = ps.legacyNativeLibraryPathString;
13320            }
13321            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13322                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13323                if (secureContainerId != null) {
13324                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13325                }
13326            }
13327        }
13328        String publicSrcDir = null;
13329        if(!dataOnly) {
13330            final ApplicationInfo applicationInfo = p.applicationInfo;
13331            if (applicationInfo == null) {
13332                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13333                return false;
13334            }
13335            if (p.isForwardLocked()) {
13336                publicSrcDir = applicationInfo.getBaseResourcePath();
13337            }
13338        }
13339        // TODO: extend to measure size of split APKs
13340        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13341        // not just the first level.
13342        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13343        // just the primary.
13344        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13345        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13346                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13347        if (res < 0) {
13348            return false;
13349        }
13350
13351        // Fix-up for forward-locked applications in ASEC containers.
13352        if (!isExternal(p)) {
13353            pStats.codeSize += pStats.externalCodeSize;
13354            pStats.externalCodeSize = 0L;
13355        }
13356
13357        return true;
13358    }
13359
13360
13361    @Override
13362    public void addPackageToPreferred(String packageName) {
13363        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13364    }
13365
13366    @Override
13367    public void removePackageFromPreferred(String packageName) {
13368        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13369    }
13370
13371    @Override
13372    public List<PackageInfo> getPreferredPackages(int flags) {
13373        return new ArrayList<PackageInfo>();
13374    }
13375
13376    private int getUidTargetSdkVersionLockedLPr(int uid) {
13377        Object obj = mSettings.getUserIdLPr(uid);
13378        if (obj instanceof SharedUserSetting) {
13379            final SharedUserSetting sus = (SharedUserSetting) obj;
13380            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13381            final Iterator<PackageSetting> it = sus.packages.iterator();
13382            while (it.hasNext()) {
13383                final PackageSetting ps = it.next();
13384                if (ps.pkg != null) {
13385                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13386                    if (v < vers) vers = v;
13387                }
13388            }
13389            return vers;
13390        } else if (obj instanceof PackageSetting) {
13391            final PackageSetting ps = (PackageSetting) obj;
13392            if (ps.pkg != null) {
13393                return ps.pkg.applicationInfo.targetSdkVersion;
13394            }
13395        }
13396        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13397    }
13398
13399    @Override
13400    public void addPreferredActivity(IntentFilter filter, int match,
13401            ComponentName[] set, ComponentName activity, int userId) {
13402        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13403                "Adding preferred");
13404    }
13405
13406    private void addPreferredActivityInternal(IntentFilter filter, int match,
13407            ComponentName[] set, ComponentName activity, boolean always, int userId,
13408            String opname) {
13409        // writer
13410        int callingUid = Binder.getCallingUid();
13411        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13412        if (filter.countActions() == 0) {
13413            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13414            return;
13415        }
13416        synchronized (mPackages) {
13417            if (mContext.checkCallingOrSelfPermission(
13418                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13419                    != PackageManager.PERMISSION_GRANTED) {
13420                if (getUidTargetSdkVersionLockedLPr(callingUid)
13421                        < Build.VERSION_CODES.FROYO) {
13422                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13423                            + callingUid);
13424                    return;
13425                }
13426                mContext.enforceCallingOrSelfPermission(
13427                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13428            }
13429
13430            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13431            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13432                    + userId + ":");
13433            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13434            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13435            scheduleWritePackageRestrictionsLocked(userId);
13436        }
13437    }
13438
13439    @Override
13440    public void replacePreferredActivity(IntentFilter filter, int match,
13441            ComponentName[] set, ComponentName activity, int userId) {
13442        if (filter.countActions() != 1) {
13443            throw new IllegalArgumentException(
13444                    "replacePreferredActivity expects filter to have only 1 action.");
13445        }
13446        if (filter.countDataAuthorities() != 0
13447                || filter.countDataPaths() != 0
13448                || filter.countDataSchemes() > 1
13449                || filter.countDataTypes() != 0) {
13450            throw new IllegalArgumentException(
13451                    "replacePreferredActivity expects filter to have no data authorities, " +
13452                    "paths, or types; and at most one scheme.");
13453        }
13454
13455        final int callingUid = Binder.getCallingUid();
13456        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13457        synchronized (mPackages) {
13458            if (mContext.checkCallingOrSelfPermission(
13459                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13460                    != PackageManager.PERMISSION_GRANTED) {
13461                if (getUidTargetSdkVersionLockedLPr(callingUid)
13462                        < Build.VERSION_CODES.FROYO) {
13463                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13464                            + Binder.getCallingUid());
13465                    return;
13466                }
13467                mContext.enforceCallingOrSelfPermission(
13468                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13469            }
13470
13471            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13472            if (pir != null) {
13473                // Get all of the existing entries that exactly match this filter.
13474                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13475                if (existing != null && existing.size() == 1) {
13476                    PreferredActivity cur = existing.get(0);
13477                    if (DEBUG_PREFERRED) {
13478                        Slog.i(TAG, "Checking replace of preferred:");
13479                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13480                        if (!cur.mPref.mAlways) {
13481                            Slog.i(TAG, "  -- CUR; not mAlways!");
13482                        } else {
13483                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13484                            Slog.i(TAG, "  -- CUR: mSet="
13485                                    + Arrays.toString(cur.mPref.mSetComponents));
13486                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13487                            Slog.i(TAG, "  -- NEW: mMatch="
13488                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13489                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13490                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13491                        }
13492                    }
13493                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13494                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13495                            && cur.mPref.sameSet(set)) {
13496                        // Setting the preferred activity to what it happens to be already
13497                        if (DEBUG_PREFERRED) {
13498                            Slog.i(TAG, "Replacing with same preferred activity "
13499                                    + cur.mPref.mShortComponent + " for user "
13500                                    + userId + ":");
13501                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13502                        }
13503                        return;
13504                    }
13505                }
13506
13507                if (existing != null) {
13508                    if (DEBUG_PREFERRED) {
13509                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13510                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13511                    }
13512                    for (int i = 0; i < existing.size(); i++) {
13513                        PreferredActivity pa = existing.get(i);
13514                        if (DEBUG_PREFERRED) {
13515                            Slog.i(TAG, "Removing existing preferred activity "
13516                                    + pa.mPref.mComponent + ":");
13517                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13518                        }
13519                        pir.removeFilter(pa);
13520                    }
13521                }
13522            }
13523            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13524                    "Replacing preferred");
13525        }
13526    }
13527
13528    @Override
13529    public void clearPackagePreferredActivities(String packageName) {
13530        final int uid = Binder.getCallingUid();
13531        // writer
13532        synchronized (mPackages) {
13533            PackageParser.Package pkg = mPackages.get(packageName);
13534            if (pkg == null || pkg.applicationInfo.uid != uid) {
13535                if (mContext.checkCallingOrSelfPermission(
13536                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13537                        != PackageManager.PERMISSION_GRANTED) {
13538                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13539                            < Build.VERSION_CODES.FROYO) {
13540                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13541                                + Binder.getCallingUid());
13542                        return;
13543                    }
13544                    mContext.enforceCallingOrSelfPermission(
13545                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13546                }
13547            }
13548
13549            int user = UserHandle.getCallingUserId();
13550            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13551                scheduleWritePackageRestrictionsLocked(user);
13552            }
13553        }
13554    }
13555
13556    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13557    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13558        ArrayList<PreferredActivity> removed = null;
13559        boolean changed = false;
13560        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13561            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13562            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13563            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13564                continue;
13565            }
13566            Iterator<PreferredActivity> it = pir.filterIterator();
13567            while (it.hasNext()) {
13568                PreferredActivity pa = it.next();
13569                // Mark entry for removal only if it matches the package name
13570                // and the entry is of type "always".
13571                if (packageName == null ||
13572                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13573                                && pa.mPref.mAlways)) {
13574                    if (removed == null) {
13575                        removed = new ArrayList<PreferredActivity>();
13576                    }
13577                    removed.add(pa);
13578                }
13579            }
13580            if (removed != null) {
13581                for (int j=0; j<removed.size(); j++) {
13582                    PreferredActivity pa = removed.get(j);
13583                    pir.removeFilter(pa);
13584                }
13585                changed = true;
13586            }
13587        }
13588        return changed;
13589    }
13590
13591    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13592    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13593        if (userId == UserHandle.USER_ALL) {
13594            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13595                    sUserManager.getUserIds())) {
13596                for (int oneUserId : sUserManager.getUserIds()) {
13597                    scheduleWritePackageRestrictionsLocked(oneUserId);
13598                }
13599            }
13600        } else {
13601            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13602                scheduleWritePackageRestrictionsLocked(userId);
13603            }
13604        }
13605    }
13606
13607
13608    void clearDefaultBrowserIfNeeded(String packageName) {
13609        for (int oneUserId : sUserManager.getUserIds()) {
13610            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13611            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13612            if (packageName.equals(defaultBrowserPackageName)) {
13613                setDefaultBrowserPackageName(null, oneUserId);
13614            }
13615        }
13616    }
13617
13618    @Override
13619    public void resetPreferredActivities(int userId) {
13620        mContext.enforceCallingOrSelfPermission(
13621                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13622        // writer
13623        synchronized (mPackages) {
13624            clearPackagePreferredActivitiesLPw(null, userId);
13625            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13626            applyFactoryDefaultBrowserLPw(userId);
13627
13628            scheduleWritePackageRestrictionsLocked(userId);
13629        }
13630    }
13631
13632    @Override
13633    public int getPreferredActivities(List<IntentFilter> outFilters,
13634            List<ComponentName> outActivities, String packageName) {
13635
13636        int num = 0;
13637        final int userId = UserHandle.getCallingUserId();
13638        // reader
13639        synchronized (mPackages) {
13640            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13641            if (pir != null) {
13642                final Iterator<PreferredActivity> it = pir.filterIterator();
13643                while (it.hasNext()) {
13644                    final PreferredActivity pa = it.next();
13645                    if (packageName == null
13646                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13647                                    && pa.mPref.mAlways)) {
13648                        if (outFilters != null) {
13649                            outFilters.add(new IntentFilter(pa));
13650                        }
13651                        if (outActivities != null) {
13652                            outActivities.add(pa.mPref.mComponent);
13653                        }
13654                    }
13655                }
13656            }
13657        }
13658
13659        return num;
13660    }
13661
13662    @Override
13663    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13664            int userId) {
13665        int callingUid = Binder.getCallingUid();
13666        if (callingUid != Process.SYSTEM_UID) {
13667            throw new SecurityException(
13668                    "addPersistentPreferredActivity can only be run by the system");
13669        }
13670        if (filter.countActions() == 0) {
13671            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13672            return;
13673        }
13674        synchronized (mPackages) {
13675            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13676                    " :");
13677            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13678            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13679                    new PersistentPreferredActivity(filter, activity));
13680            scheduleWritePackageRestrictionsLocked(userId);
13681        }
13682    }
13683
13684    @Override
13685    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13686        int callingUid = Binder.getCallingUid();
13687        if (callingUid != Process.SYSTEM_UID) {
13688            throw new SecurityException(
13689                    "clearPackagePersistentPreferredActivities can only be run by the system");
13690        }
13691        ArrayList<PersistentPreferredActivity> removed = null;
13692        boolean changed = false;
13693        synchronized (mPackages) {
13694            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13695                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13696                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13697                        .valueAt(i);
13698                if (userId != thisUserId) {
13699                    continue;
13700                }
13701                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13702                while (it.hasNext()) {
13703                    PersistentPreferredActivity ppa = it.next();
13704                    // Mark entry for removal only if it matches the package name.
13705                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13706                        if (removed == null) {
13707                            removed = new ArrayList<PersistentPreferredActivity>();
13708                        }
13709                        removed.add(ppa);
13710                    }
13711                }
13712                if (removed != null) {
13713                    for (int j=0; j<removed.size(); j++) {
13714                        PersistentPreferredActivity ppa = removed.get(j);
13715                        ppir.removeFilter(ppa);
13716                    }
13717                    changed = true;
13718                }
13719            }
13720
13721            if (changed) {
13722                scheduleWritePackageRestrictionsLocked(userId);
13723            }
13724        }
13725    }
13726
13727    /**
13728     * Common machinery for picking apart a restored XML blob and passing
13729     * it to a caller-supplied functor to be applied to the running system.
13730     */
13731    private void restoreFromXml(XmlPullParser parser, int userId,
13732            String expectedStartTag, BlobXmlRestorer functor)
13733            throws IOException, XmlPullParserException {
13734        int type;
13735        while ((type = parser.next()) != XmlPullParser.START_TAG
13736                && type != XmlPullParser.END_DOCUMENT) {
13737        }
13738        if (type != XmlPullParser.START_TAG) {
13739            // oops didn't find a start tag?!
13740            if (DEBUG_BACKUP) {
13741                Slog.e(TAG, "Didn't find start tag during restore");
13742            }
13743            return;
13744        }
13745
13746        // this is supposed to be TAG_PREFERRED_BACKUP
13747        if (!expectedStartTag.equals(parser.getName())) {
13748            if (DEBUG_BACKUP) {
13749                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13750            }
13751            return;
13752        }
13753
13754        // skip interfering stuff, then we're aligned with the backing implementation
13755        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13756        functor.apply(parser, userId);
13757    }
13758
13759    private interface BlobXmlRestorer {
13760        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13761    }
13762
13763    /**
13764     * Non-Binder method, support for the backup/restore mechanism: write the
13765     * full set of preferred activities in its canonical XML format.  Returns the
13766     * XML output as a byte array, or null if there is none.
13767     */
13768    @Override
13769    public byte[] getPreferredActivityBackup(int userId) {
13770        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13771            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13772        }
13773
13774        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13775        try {
13776            final XmlSerializer serializer = new FastXmlSerializer();
13777            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13778            serializer.startDocument(null, true);
13779            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13780
13781            synchronized (mPackages) {
13782                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13783            }
13784
13785            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13786            serializer.endDocument();
13787            serializer.flush();
13788        } catch (Exception e) {
13789            if (DEBUG_BACKUP) {
13790                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13791            }
13792            return null;
13793        }
13794
13795        return dataStream.toByteArray();
13796    }
13797
13798    @Override
13799    public void restorePreferredActivities(byte[] backup, int userId) {
13800        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13801            throw new SecurityException("Only the system may call restorePreferredActivities()");
13802        }
13803
13804        try {
13805            final XmlPullParser parser = Xml.newPullParser();
13806            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13807            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13808                    new BlobXmlRestorer() {
13809                        @Override
13810                        public void apply(XmlPullParser parser, int userId)
13811                                throws XmlPullParserException, IOException {
13812                            synchronized (mPackages) {
13813                                mSettings.readPreferredActivitiesLPw(parser, userId);
13814                            }
13815                        }
13816                    } );
13817        } catch (Exception e) {
13818            if (DEBUG_BACKUP) {
13819                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13820            }
13821        }
13822    }
13823
13824    /**
13825     * Non-Binder method, support for the backup/restore mechanism: write the
13826     * default browser (etc) settings in its canonical XML format.  Returns the default
13827     * browser XML representation as a byte array, or null if there is none.
13828     */
13829    @Override
13830    public byte[] getDefaultAppsBackup(int userId) {
13831        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13832            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13833        }
13834
13835        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13836        try {
13837            final XmlSerializer serializer = new FastXmlSerializer();
13838            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13839            serializer.startDocument(null, true);
13840            serializer.startTag(null, TAG_DEFAULT_APPS);
13841
13842            synchronized (mPackages) {
13843                mSettings.writeDefaultAppsLPr(serializer, userId);
13844            }
13845
13846            serializer.endTag(null, TAG_DEFAULT_APPS);
13847            serializer.endDocument();
13848            serializer.flush();
13849        } catch (Exception e) {
13850            if (DEBUG_BACKUP) {
13851                Slog.e(TAG, "Unable to write default apps for backup", e);
13852            }
13853            return null;
13854        }
13855
13856        return dataStream.toByteArray();
13857    }
13858
13859    @Override
13860    public void restoreDefaultApps(byte[] backup, int userId) {
13861        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13862            throw new SecurityException("Only the system may call restoreDefaultApps()");
13863        }
13864
13865        try {
13866            final XmlPullParser parser = Xml.newPullParser();
13867            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13868            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13869                    new BlobXmlRestorer() {
13870                        @Override
13871                        public void apply(XmlPullParser parser, int userId)
13872                                throws XmlPullParserException, IOException {
13873                            synchronized (mPackages) {
13874                                mSettings.readDefaultAppsLPw(parser, userId);
13875                            }
13876                        }
13877                    } );
13878        } catch (Exception e) {
13879            if (DEBUG_BACKUP) {
13880                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13881            }
13882        }
13883    }
13884
13885    @Override
13886    public byte[] getIntentFilterVerificationBackup(int userId) {
13887        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13888            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
13889        }
13890
13891        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13892        try {
13893            final XmlSerializer serializer = new FastXmlSerializer();
13894            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13895            serializer.startDocument(null, true);
13896            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
13897
13898            synchronized (mPackages) {
13899                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
13900            }
13901
13902            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
13903            serializer.endDocument();
13904            serializer.flush();
13905        } catch (Exception e) {
13906            if (DEBUG_BACKUP) {
13907                Slog.e(TAG, "Unable to write default apps for backup", e);
13908            }
13909            return null;
13910        }
13911
13912        return dataStream.toByteArray();
13913    }
13914
13915    @Override
13916    public void restoreIntentFilterVerification(byte[] backup, int userId) {
13917        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13918            throw new SecurityException("Only the system may call restorePreferredActivities()");
13919        }
13920
13921        try {
13922            final XmlPullParser parser = Xml.newPullParser();
13923            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13924            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
13925                    new BlobXmlRestorer() {
13926                        @Override
13927                        public void apply(XmlPullParser parser, int userId)
13928                                throws XmlPullParserException, IOException {
13929                            synchronized (mPackages) {
13930                                mSettings.readAllDomainVerificationsLPr(parser, userId);
13931                                mSettings.writeLPr();
13932                            }
13933                        }
13934                    } );
13935        } catch (Exception e) {
13936            if (DEBUG_BACKUP) {
13937                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13938            }
13939        }
13940    }
13941
13942    @Override
13943    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13944            int sourceUserId, int targetUserId, int flags) {
13945        mContext.enforceCallingOrSelfPermission(
13946                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13947        int callingUid = Binder.getCallingUid();
13948        enforceOwnerRights(ownerPackage, callingUid);
13949        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13950        if (intentFilter.countActions() == 0) {
13951            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13952            return;
13953        }
13954        synchronized (mPackages) {
13955            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13956                    ownerPackage, targetUserId, flags);
13957            CrossProfileIntentResolver resolver =
13958                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13959            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13960            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13961            if (existing != null) {
13962                int size = existing.size();
13963                for (int i = 0; i < size; i++) {
13964                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13965                        return;
13966                    }
13967                }
13968            }
13969            resolver.addFilter(newFilter);
13970            scheduleWritePackageRestrictionsLocked(sourceUserId);
13971        }
13972    }
13973
13974    @Override
13975    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13976        mContext.enforceCallingOrSelfPermission(
13977                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13978        int callingUid = Binder.getCallingUid();
13979        enforceOwnerRights(ownerPackage, callingUid);
13980        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13981        synchronized (mPackages) {
13982            CrossProfileIntentResolver resolver =
13983                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13984            ArraySet<CrossProfileIntentFilter> set =
13985                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13986            for (CrossProfileIntentFilter filter : set) {
13987                if (filter.getOwnerPackage().equals(ownerPackage)) {
13988                    resolver.removeFilter(filter);
13989                }
13990            }
13991            scheduleWritePackageRestrictionsLocked(sourceUserId);
13992        }
13993    }
13994
13995    // Enforcing that callingUid is owning pkg on userId
13996    private void enforceOwnerRights(String pkg, int callingUid) {
13997        // The system owns everything.
13998        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13999            return;
14000        }
14001        int callingUserId = UserHandle.getUserId(callingUid);
14002        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14003        if (pi == null) {
14004            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14005                    + callingUserId);
14006        }
14007        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14008            throw new SecurityException("Calling uid " + callingUid
14009                    + " does not own package " + pkg);
14010        }
14011    }
14012
14013    @Override
14014    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14015        Intent intent = new Intent(Intent.ACTION_MAIN);
14016        intent.addCategory(Intent.CATEGORY_HOME);
14017
14018        final int callingUserId = UserHandle.getCallingUserId();
14019        List<ResolveInfo> list = queryIntentActivities(intent, null,
14020                PackageManager.GET_META_DATA, callingUserId);
14021        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14022                true, false, false, callingUserId);
14023
14024        allHomeCandidates.clear();
14025        if (list != null) {
14026            for (ResolveInfo ri : list) {
14027                allHomeCandidates.add(ri);
14028            }
14029        }
14030        return (preferred == null || preferred.activityInfo == null)
14031                ? null
14032                : new ComponentName(preferred.activityInfo.packageName,
14033                        preferred.activityInfo.name);
14034    }
14035
14036    @Override
14037    public void setApplicationEnabledSetting(String appPackageName,
14038            int newState, int flags, int userId, String callingPackage) {
14039        if (!sUserManager.exists(userId)) return;
14040        if (callingPackage == null) {
14041            callingPackage = Integer.toString(Binder.getCallingUid());
14042        }
14043        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14044    }
14045
14046    @Override
14047    public void setComponentEnabledSetting(ComponentName componentName,
14048            int newState, int flags, int userId) {
14049        if (!sUserManager.exists(userId)) return;
14050        setEnabledSetting(componentName.getPackageName(),
14051                componentName.getClassName(), newState, flags, userId, null);
14052    }
14053
14054    private void setEnabledSetting(final String packageName, String className, int newState,
14055            final int flags, int userId, String callingPackage) {
14056        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14057              || newState == COMPONENT_ENABLED_STATE_ENABLED
14058              || newState == COMPONENT_ENABLED_STATE_DISABLED
14059              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14060              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14061            throw new IllegalArgumentException("Invalid new component state: "
14062                    + newState);
14063        }
14064        PackageSetting pkgSetting;
14065        final int uid = Binder.getCallingUid();
14066        final int permission = mContext.checkCallingOrSelfPermission(
14067                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14068        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14069        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14070        boolean sendNow = false;
14071        boolean isApp = (className == null);
14072        String componentName = isApp ? packageName : className;
14073        int packageUid = -1;
14074        ArrayList<String> components;
14075
14076        // writer
14077        synchronized (mPackages) {
14078            pkgSetting = mSettings.mPackages.get(packageName);
14079            if (pkgSetting == null) {
14080                if (className == null) {
14081                    throw new IllegalArgumentException(
14082                            "Unknown package: " + packageName);
14083                }
14084                throw new IllegalArgumentException(
14085                        "Unknown component: " + packageName
14086                        + "/" + className);
14087            }
14088            // Allow root and verify that userId is not being specified by a different user
14089            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14090                throw new SecurityException(
14091                        "Permission Denial: attempt to change component state from pid="
14092                        + Binder.getCallingPid()
14093                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14094            }
14095            if (className == null) {
14096                // We're dealing with an application/package level state change
14097                if (pkgSetting.getEnabled(userId) == newState) {
14098                    // Nothing to do
14099                    return;
14100                }
14101                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14102                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14103                    // Don't care about who enables an app.
14104                    callingPackage = null;
14105                }
14106                pkgSetting.setEnabled(newState, userId, callingPackage);
14107                // pkgSetting.pkg.mSetEnabled = newState;
14108            } else {
14109                // We're dealing with a component level state change
14110                // First, verify that this is a valid class name.
14111                PackageParser.Package pkg = pkgSetting.pkg;
14112                if (pkg == null || !pkg.hasComponentClassName(className)) {
14113                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14114                        throw new IllegalArgumentException("Component class " + className
14115                                + " does not exist in " + packageName);
14116                    } else {
14117                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14118                                + className + " does not exist in " + packageName);
14119                    }
14120                }
14121                switch (newState) {
14122                case COMPONENT_ENABLED_STATE_ENABLED:
14123                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14124                        return;
14125                    }
14126                    break;
14127                case COMPONENT_ENABLED_STATE_DISABLED:
14128                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14129                        return;
14130                    }
14131                    break;
14132                case COMPONENT_ENABLED_STATE_DEFAULT:
14133                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14134                        return;
14135                    }
14136                    break;
14137                default:
14138                    Slog.e(TAG, "Invalid new component state: " + newState);
14139                    return;
14140                }
14141            }
14142            scheduleWritePackageRestrictionsLocked(userId);
14143            components = mPendingBroadcasts.get(userId, packageName);
14144            final boolean newPackage = components == null;
14145            if (newPackage) {
14146                components = new ArrayList<String>();
14147            }
14148            if (!components.contains(componentName)) {
14149                components.add(componentName);
14150            }
14151            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14152                sendNow = true;
14153                // Purge entry from pending broadcast list if another one exists already
14154                // since we are sending one right away.
14155                mPendingBroadcasts.remove(userId, packageName);
14156            } else {
14157                if (newPackage) {
14158                    mPendingBroadcasts.put(userId, packageName, components);
14159                }
14160                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14161                    // Schedule a message
14162                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14163                }
14164            }
14165        }
14166
14167        long callingId = Binder.clearCallingIdentity();
14168        try {
14169            if (sendNow) {
14170                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14171                sendPackageChangedBroadcast(packageName,
14172                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14173            }
14174        } finally {
14175            Binder.restoreCallingIdentity(callingId);
14176        }
14177    }
14178
14179    private void sendPackageChangedBroadcast(String packageName,
14180            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14181        if (DEBUG_INSTALL)
14182            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14183                    + componentNames);
14184        Bundle extras = new Bundle(4);
14185        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14186        String nameList[] = new String[componentNames.size()];
14187        componentNames.toArray(nameList);
14188        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14189        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14190        extras.putInt(Intent.EXTRA_UID, packageUid);
14191        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14192                new int[] {UserHandle.getUserId(packageUid)});
14193    }
14194
14195    @Override
14196    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14197        if (!sUserManager.exists(userId)) return;
14198        final int uid = Binder.getCallingUid();
14199        final int permission = mContext.checkCallingOrSelfPermission(
14200                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14201        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14202        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14203        // writer
14204        synchronized (mPackages) {
14205            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14206                    allowedByPermission, uid, userId)) {
14207                scheduleWritePackageRestrictionsLocked(userId);
14208            }
14209        }
14210    }
14211
14212    @Override
14213    public String getInstallerPackageName(String packageName) {
14214        // reader
14215        synchronized (mPackages) {
14216            return mSettings.getInstallerPackageNameLPr(packageName);
14217        }
14218    }
14219
14220    @Override
14221    public int getApplicationEnabledSetting(String packageName, int userId) {
14222        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14223        int uid = Binder.getCallingUid();
14224        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14225        // reader
14226        synchronized (mPackages) {
14227            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14228        }
14229    }
14230
14231    @Override
14232    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14233        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14234        int uid = Binder.getCallingUid();
14235        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14236        // reader
14237        synchronized (mPackages) {
14238            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14239        }
14240    }
14241
14242    @Override
14243    public void enterSafeMode() {
14244        enforceSystemOrRoot("Only the system can request entering safe mode");
14245
14246        if (!mSystemReady) {
14247            mSafeMode = true;
14248        }
14249    }
14250
14251    @Override
14252    public void systemReady() {
14253        mSystemReady = true;
14254
14255        // Read the compatibilty setting when the system is ready.
14256        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14257                mContext.getContentResolver(),
14258                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14259        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14260        if (DEBUG_SETTINGS) {
14261            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14262        }
14263
14264        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14265
14266        synchronized (mPackages) {
14267            // Verify that all of the preferred activity components actually
14268            // exist.  It is possible for applications to be updated and at
14269            // that point remove a previously declared activity component that
14270            // had been set as a preferred activity.  We try to clean this up
14271            // the next time we encounter that preferred activity, but it is
14272            // possible for the user flow to never be able to return to that
14273            // situation so here we do a sanity check to make sure we haven't
14274            // left any junk around.
14275            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14276            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14277                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14278                removed.clear();
14279                for (PreferredActivity pa : pir.filterSet()) {
14280                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14281                        removed.add(pa);
14282                    }
14283                }
14284                if (removed.size() > 0) {
14285                    for (int r=0; r<removed.size(); r++) {
14286                        PreferredActivity pa = removed.get(r);
14287                        Slog.w(TAG, "Removing dangling preferred activity: "
14288                                + pa.mPref.mComponent);
14289                        pir.removeFilter(pa);
14290                    }
14291                    mSettings.writePackageRestrictionsLPr(
14292                            mSettings.mPreferredActivities.keyAt(i));
14293                }
14294            }
14295
14296            for (int userId : UserManagerService.getInstance().getUserIds()) {
14297                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14298                    grantPermissionsUserIds = ArrayUtils.appendInt(
14299                            grantPermissionsUserIds, userId);
14300                }
14301            }
14302        }
14303        sUserManager.systemReady();
14304
14305        // If we upgraded grant all default permissions before kicking off.
14306        for (int userId : grantPermissionsUserIds) {
14307            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14308        }
14309
14310        // Kick off any messages waiting for system ready
14311        if (mPostSystemReadyMessages != null) {
14312            for (Message msg : mPostSystemReadyMessages) {
14313                msg.sendToTarget();
14314            }
14315            mPostSystemReadyMessages = null;
14316        }
14317
14318        // Watch for external volumes that come and go over time
14319        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14320        storage.registerListener(mStorageListener);
14321
14322        mInstallerService.systemReady();
14323        mPackageDexOptimizer.systemReady();
14324    }
14325
14326    @Override
14327    public boolean isSafeMode() {
14328        return mSafeMode;
14329    }
14330
14331    @Override
14332    public boolean hasSystemUidErrors() {
14333        return mHasSystemUidErrors;
14334    }
14335
14336    static String arrayToString(int[] array) {
14337        StringBuffer buf = new StringBuffer(128);
14338        buf.append('[');
14339        if (array != null) {
14340            for (int i=0; i<array.length; i++) {
14341                if (i > 0) buf.append(", ");
14342                buf.append(array[i]);
14343            }
14344        }
14345        buf.append(']');
14346        return buf.toString();
14347    }
14348
14349    static class DumpState {
14350        public static final int DUMP_LIBS = 1 << 0;
14351        public static final int DUMP_FEATURES = 1 << 1;
14352        public static final int DUMP_RESOLVERS = 1 << 2;
14353        public static final int DUMP_PERMISSIONS = 1 << 3;
14354        public static final int DUMP_PACKAGES = 1 << 4;
14355        public static final int DUMP_SHARED_USERS = 1 << 5;
14356        public static final int DUMP_MESSAGES = 1 << 6;
14357        public static final int DUMP_PROVIDERS = 1 << 7;
14358        public static final int DUMP_VERIFIERS = 1 << 8;
14359        public static final int DUMP_PREFERRED = 1 << 9;
14360        public static final int DUMP_PREFERRED_XML = 1 << 10;
14361        public static final int DUMP_KEYSETS = 1 << 11;
14362        public static final int DUMP_VERSION = 1 << 12;
14363        public static final int DUMP_INSTALLS = 1 << 13;
14364        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14365        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14366
14367        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14368
14369        private int mTypes;
14370
14371        private int mOptions;
14372
14373        private boolean mTitlePrinted;
14374
14375        private SharedUserSetting mSharedUser;
14376
14377        public boolean isDumping(int type) {
14378            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14379                return true;
14380            }
14381
14382            return (mTypes & type) != 0;
14383        }
14384
14385        public void setDump(int type) {
14386            mTypes |= type;
14387        }
14388
14389        public boolean isOptionEnabled(int option) {
14390            return (mOptions & option) != 0;
14391        }
14392
14393        public void setOptionEnabled(int option) {
14394            mOptions |= option;
14395        }
14396
14397        public boolean onTitlePrinted() {
14398            final boolean printed = mTitlePrinted;
14399            mTitlePrinted = true;
14400            return printed;
14401        }
14402
14403        public boolean getTitlePrinted() {
14404            return mTitlePrinted;
14405        }
14406
14407        public void setTitlePrinted(boolean enabled) {
14408            mTitlePrinted = enabled;
14409        }
14410
14411        public SharedUserSetting getSharedUser() {
14412            return mSharedUser;
14413        }
14414
14415        public void setSharedUser(SharedUserSetting user) {
14416            mSharedUser = user;
14417        }
14418    }
14419
14420    @Override
14421    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14422        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14423                != PackageManager.PERMISSION_GRANTED) {
14424            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14425                    + Binder.getCallingPid()
14426                    + ", uid=" + Binder.getCallingUid()
14427                    + " without permission "
14428                    + android.Manifest.permission.DUMP);
14429            return;
14430        }
14431
14432        DumpState dumpState = new DumpState();
14433        boolean fullPreferred = false;
14434        boolean checkin = false;
14435
14436        String packageName = null;
14437        ArraySet<String> permissionNames = null;
14438
14439        int opti = 0;
14440        while (opti < args.length) {
14441            String opt = args[opti];
14442            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14443                break;
14444            }
14445            opti++;
14446
14447            if ("-a".equals(opt)) {
14448                // Right now we only know how to print all.
14449            } else if ("-h".equals(opt)) {
14450                pw.println("Package manager dump options:");
14451                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14452                pw.println("    --checkin: dump for a checkin");
14453                pw.println("    -f: print details of intent filters");
14454                pw.println("    -h: print this help");
14455                pw.println("  cmd may be one of:");
14456                pw.println("    l[ibraries]: list known shared libraries");
14457                pw.println("    f[ibraries]: list device features");
14458                pw.println("    k[eysets]: print known keysets");
14459                pw.println("    r[esolvers]: dump intent resolvers");
14460                pw.println("    perm[issions]: dump permissions");
14461                pw.println("    permission [name ...]: dump declaration and use of given permission");
14462                pw.println("    pref[erred]: print preferred package settings");
14463                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14464                pw.println("    prov[iders]: dump content providers");
14465                pw.println("    p[ackages]: dump installed packages");
14466                pw.println("    s[hared-users]: dump shared user IDs");
14467                pw.println("    m[essages]: print collected runtime messages");
14468                pw.println("    v[erifiers]: print package verifier info");
14469                pw.println("    version: print database version info");
14470                pw.println("    write: write current settings now");
14471                pw.println("    <package.name>: info about given package");
14472                pw.println("    installs: details about install sessions");
14473                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14474                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14475                return;
14476            } else if ("--checkin".equals(opt)) {
14477                checkin = true;
14478            } else if ("-f".equals(opt)) {
14479                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14480            } else {
14481                pw.println("Unknown argument: " + opt + "; use -h for help");
14482            }
14483        }
14484
14485        // Is the caller requesting to dump a particular piece of data?
14486        if (opti < args.length) {
14487            String cmd = args[opti];
14488            opti++;
14489            // Is this a package name?
14490            if ("android".equals(cmd) || cmd.contains(".")) {
14491                packageName = cmd;
14492                // When dumping a single package, we always dump all of its
14493                // filter information since the amount of data will be reasonable.
14494                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14495            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14496                dumpState.setDump(DumpState.DUMP_LIBS);
14497            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14498                dumpState.setDump(DumpState.DUMP_FEATURES);
14499            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14500                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14501            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14502                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14503            } else if ("permission".equals(cmd)) {
14504                if (opti >= args.length) {
14505                    pw.println("Error: permission requires permission name");
14506                    return;
14507                }
14508                permissionNames = new ArraySet<>();
14509                while (opti < args.length) {
14510                    permissionNames.add(args[opti]);
14511                    opti++;
14512                }
14513                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14514                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14515            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14516                dumpState.setDump(DumpState.DUMP_PREFERRED);
14517            } else if ("preferred-xml".equals(cmd)) {
14518                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14519                if (opti < args.length && "--full".equals(args[opti])) {
14520                    fullPreferred = true;
14521                    opti++;
14522                }
14523            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14524                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14525            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14526                dumpState.setDump(DumpState.DUMP_PACKAGES);
14527            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14528                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14529            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14530                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14531            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14532                dumpState.setDump(DumpState.DUMP_MESSAGES);
14533            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14534                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14535            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14536                    || "intent-filter-verifiers".equals(cmd)) {
14537                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14538            } else if ("version".equals(cmd)) {
14539                dumpState.setDump(DumpState.DUMP_VERSION);
14540            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14541                dumpState.setDump(DumpState.DUMP_KEYSETS);
14542            } else if ("installs".equals(cmd)) {
14543                dumpState.setDump(DumpState.DUMP_INSTALLS);
14544            } else if ("write".equals(cmd)) {
14545                synchronized (mPackages) {
14546                    mSettings.writeLPr();
14547                    pw.println("Settings written.");
14548                    return;
14549                }
14550            }
14551        }
14552
14553        if (checkin) {
14554            pw.println("vers,1");
14555        }
14556
14557        // reader
14558        synchronized (mPackages) {
14559            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14560                if (!checkin) {
14561                    if (dumpState.onTitlePrinted())
14562                        pw.println();
14563                    pw.println("Database versions:");
14564                    pw.print("  SDK Version:");
14565                    pw.print(" internal=");
14566                    pw.print(mSettings.mInternalSdkPlatform);
14567                    pw.print(" external=");
14568                    pw.println(mSettings.mExternalSdkPlatform);
14569                    pw.print("  DB Version:");
14570                    pw.print(" internal=");
14571                    pw.print(mSettings.mInternalDatabaseVersion);
14572                    pw.print(" external=");
14573                    pw.println(mSettings.mExternalDatabaseVersion);
14574                }
14575            }
14576
14577            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14578                if (!checkin) {
14579                    if (dumpState.onTitlePrinted())
14580                        pw.println();
14581                    pw.println("Verifiers:");
14582                    pw.print("  Required: ");
14583                    pw.print(mRequiredVerifierPackage);
14584                    pw.print(" (uid=");
14585                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14586                    pw.println(")");
14587                } else if (mRequiredVerifierPackage != null) {
14588                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14589                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14590                }
14591            }
14592
14593            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14594                    packageName == null) {
14595                if (mIntentFilterVerifierComponent != null) {
14596                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14597                    if (!checkin) {
14598                        if (dumpState.onTitlePrinted())
14599                            pw.println();
14600                        pw.println("Intent Filter Verifier:");
14601                        pw.print("  Using: ");
14602                        pw.print(verifierPackageName);
14603                        pw.print(" (uid=");
14604                        pw.print(getPackageUid(verifierPackageName, 0));
14605                        pw.println(")");
14606                    } else if (verifierPackageName != null) {
14607                        pw.print("ifv,"); pw.print(verifierPackageName);
14608                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14609                    }
14610                } else {
14611                    pw.println();
14612                    pw.println("No Intent Filter Verifier available!");
14613                }
14614            }
14615
14616            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14617                boolean printedHeader = false;
14618                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14619                while (it.hasNext()) {
14620                    String name = it.next();
14621                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14622                    if (!checkin) {
14623                        if (!printedHeader) {
14624                            if (dumpState.onTitlePrinted())
14625                                pw.println();
14626                            pw.println("Libraries:");
14627                            printedHeader = true;
14628                        }
14629                        pw.print("  ");
14630                    } else {
14631                        pw.print("lib,");
14632                    }
14633                    pw.print(name);
14634                    if (!checkin) {
14635                        pw.print(" -> ");
14636                    }
14637                    if (ent.path != null) {
14638                        if (!checkin) {
14639                            pw.print("(jar) ");
14640                            pw.print(ent.path);
14641                        } else {
14642                            pw.print(",jar,");
14643                            pw.print(ent.path);
14644                        }
14645                    } else {
14646                        if (!checkin) {
14647                            pw.print("(apk) ");
14648                            pw.print(ent.apk);
14649                        } else {
14650                            pw.print(",apk,");
14651                            pw.print(ent.apk);
14652                        }
14653                    }
14654                    pw.println();
14655                }
14656            }
14657
14658            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14659                if (dumpState.onTitlePrinted())
14660                    pw.println();
14661                if (!checkin) {
14662                    pw.println("Features:");
14663                }
14664                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14665                while (it.hasNext()) {
14666                    String name = it.next();
14667                    if (!checkin) {
14668                        pw.print("  ");
14669                    } else {
14670                        pw.print("feat,");
14671                    }
14672                    pw.println(name);
14673                }
14674            }
14675
14676            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14677                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14678                        : "Activity Resolver Table:", "  ", packageName,
14679                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14680                    dumpState.setTitlePrinted(true);
14681                }
14682                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14683                        : "Receiver Resolver Table:", "  ", packageName,
14684                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14685                    dumpState.setTitlePrinted(true);
14686                }
14687                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14688                        : "Service Resolver Table:", "  ", packageName,
14689                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14690                    dumpState.setTitlePrinted(true);
14691                }
14692                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14693                        : "Provider Resolver Table:", "  ", packageName,
14694                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14695                    dumpState.setTitlePrinted(true);
14696                }
14697            }
14698
14699            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14700                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14701                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14702                    int user = mSettings.mPreferredActivities.keyAt(i);
14703                    if (pir.dump(pw,
14704                            dumpState.getTitlePrinted()
14705                                ? "\nPreferred Activities User " + user + ":"
14706                                : "Preferred Activities User " + user + ":", "  ",
14707                            packageName, true, false)) {
14708                        dumpState.setTitlePrinted(true);
14709                    }
14710                }
14711            }
14712
14713            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14714                pw.flush();
14715                FileOutputStream fout = new FileOutputStream(fd);
14716                BufferedOutputStream str = new BufferedOutputStream(fout);
14717                XmlSerializer serializer = new FastXmlSerializer();
14718                try {
14719                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14720                    serializer.startDocument(null, true);
14721                    serializer.setFeature(
14722                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14723                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14724                    serializer.endDocument();
14725                    serializer.flush();
14726                } catch (IllegalArgumentException e) {
14727                    pw.println("Failed writing: " + e);
14728                } catch (IllegalStateException e) {
14729                    pw.println("Failed writing: " + e);
14730                } catch (IOException e) {
14731                    pw.println("Failed writing: " + e);
14732                }
14733            }
14734
14735            if (!checkin
14736                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14737                    && packageName == null) {
14738                pw.println();
14739                int count = mSettings.mPackages.size();
14740                if (count == 0) {
14741                    pw.println("No domain preferred apps!");
14742                    pw.println();
14743                } else {
14744                    final String prefix = "  ";
14745                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14746                    if (allPackageSettings.size() == 0) {
14747                        pw.println("No domain preferred apps!");
14748                        pw.println();
14749                    } else {
14750                        pw.println("Domain preferred apps status:");
14751                        pw.println();
14752                        count = 0;
14753                        for (PackageSetting ps : allPackageSettings) {
14754                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14755                            if (ivi == null || ivi.getPackageName() == null) continue;
14756                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
14757                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14758                            pw.println(prefix + "Status: " + ivi.getStatusString());
14759                            pw.println();
14760                            count++;
14761                        }
14762                        if (count == 0) {
14763                            pw.println(prefix + "No domain preferred app status!");
14764                            pw.println();
14765                        }
14766                        for (int userId : sUserManager.getUserIds()) {
14767                            pw.println("Domain preferred apps for User " + userId + ":");
14768                            pw.println();
14769                            count = 0;
14770                            for (PackageSetting ps : allPackageSettings) {
14771                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14772                                if (ivi == null || ivi.getPackageName() == null) {
14773                                    continue;
14774                                }
14775                                final int status = ps.getDomainVerificationStatusForUser(userId);
14776                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14777                                    continue;
14778                                }
14779                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
14780                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
14781                                String statusStr = IntentFilterVerificationInfo.
14782                                        getStatusStringFromValue(status);
14783                                pw.println(prefix + "Status: " + statusStr);
14784                                pw.println();
14785                                count++;
14786                            }
14787                            if (count == 0) {
14788                                pw.println(prefix + "No domain preferred apps!");
14789                                pw.println();
14790                            }
14791                        }
14792                    }
14793                }
14794            }
14795
14796            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14797                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14798                if (packageName == null && permissionNames == null) {
14799                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14800                        if (iperm == 0) {
14801                            if (dumpState.onTitlePrinted())
14802                                pw.println();
14803                            pw.println("AppOp Permissions:");
14804                        }
14805                        pw.print("  AppOp Permission ");
14806                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14807                        pw.println(":");
14808                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14809                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14810                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14811                        }
14812                    }
14813                }
14814            }
14815
14816            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14817                boolean printedSomething = false;
14818                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14819                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14820                        continue;
14821                    }
14822                    if (!printedSomething) {
14823                        if (dumpState.onTitlePrinted())
14824                            pw.println();
14825                        pw.println("Registered ContentProviders:");
14826                        printedSomething = true;
14827                    }
14828                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14829                    pw.print("    "); pw.println(p.toString());
14830                }
14831                printedSomething = false;
14832                for (Map.Entry<String, PackageParser.Provider> entry :
14833                        mProvidersByAuthority.entrySet()) {
14834                    PackageParser.Provider p = entry.getValue();
14835                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14836                        continue;
14837                    }
14838                    if (!printedSomething) {
14839                        if (dumpState.onTitlePrinted())
14840                            pw.println();
14841                        pw.println("ContentProvider Authorities:");
14842                        printedSomething = true;
14843                    }
14844                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14845                    pw.print("    "); pw.println(p.toString());
14846                    if (p.info != null && p.info.applicationInfo != null) {
14847                        final String appInfo = p.info.applicationInfo.toString();
14848                        pw.print("      applicationInfo="); pw.println(appInfo);
14849                    }
14850                }
14851            }
14852
14853            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14854                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14855            }
14856
14857            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14858                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14859            }
14860
14861            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14862                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14863            }
14864
14865            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14866                // XXX should handle packageName != null by dumping only install data that
14867                // the given package is involved with.
14868                if (dumpState.onTitlePrinted()) pw.println();
14869                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14870            }
14871
14872            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14873                if (dumpState.onTitlePrinted()) pw.println();
14874                mSettings.dumpReadMessagesLPr(pw, dumpState);
14875
14876                pw.println();
14877                pw.println("Package warning messages:");
14878                BufferedReader in = null;
14879                String line = null;
14880                try {
14881                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14882                    while ((line = in.readLine()) != null) {
14883                        if (line.contains("ignored: updated version")) continue;
14884                        pw.println(line);
14885                    }
14886                } catch (IOException ignored) {
14887                } finally {
14888                    IoUtils.closeQuietly(in);
14889                }
14890            }
14891
14892            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14893                BufferedReader in = null;
14894                String line = null;
14895                try {
14896                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14897                    while ((line = in.readLine()) != null) {
14898                        if (line.contains("ignored: updated version")) continue;
14899                        pw.print("msg,");
14900                        pw.println(line);
14901                    }
14902                } catch (IOException ignored) {
14903                } finally {
14904                    IoUtils.closeQuietly(in);
14905                }
14906            }
14907        }
14908    }
14909
14910    // ------- apps on sdcard specific code -------
14911    static final boolean DEBUG_SD_INSTALL = false;
14912
14913    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14914
14915    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14916
14917    private boolean mMediaMounted = false;
14918
14919    static String getEncryptKey() {
14920        try {
14921            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14922                    SD_ENCRYPTION_KEYSTORE_NAME);
14923            if (sdEncKey == null) {
14924                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14925                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14926                if (sdEncKey == null) {
14927                    Slog.e(TAG, "Failed to create encryption keys");
14928                    return null;
14929                }
14930            }
14931            return sdEncKey;
14932        } catch (NoSuchAlgorithmException nsae) {
14933            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14934            return null;
14935        } catch (IOException ioe) {
14936            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14937            return null;
14938        }
14939    }
14940
14941    /*
14942     * Update media status on PackageManager.
14943     */
14944    @Override
14945    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14946        int callingUid = Binder.getCallingUid();
14947        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14948            throw new SecurityException("Media status can only be updated by the system");
14949        }
14950        // reader; this apparently protects mMediaMounted, but should probably
14951        // be a different lock in that case.
14952        synchronized (mPackages) {
14953            Log.i(TAG, "Updating external media status from "
14954                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14955                    + (mediaStatus ? "mounted" : "unmounted"));
14956            if (DEBUG_SD_INSTALL)
14957                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14958                        + ", mMediaMounted=" + mMediaMounted);
14959            if (mediaStatus == mMediaMounted) {
14960                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14961                        : 0, -1);
14962                mHandler.sendMessage(msg);
14963                return;
14964            }
14965            mMediaMounted = mediaStatus;
14966        }
14967        // Queue up an async operation since the package installation may take a
14968        // little while.
14969        mHandler.post(new Runnable() {
14970            public void run() {
14971                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14972            }
14973        });
14974    }
14975
14976    /**
14977     * Called by MountService when the initial ASECs to scan are available.
14978     * Should block until all the ASEC containers are finished being scanned.
14979     */
14980    public void scanAvailableAsecs() {
14981        updateExternalMediaStatusInner(true, false, false);
14982        if (mShouldRestoreconData) {
14983            SELinuxMMAC.setRestoreconDone();
14984            mShouldRestoreconData = false;
14985        }
14986    }
14987
14988    /*
14989     * Collect information of applications on external media, map them against
14990     * existing containers and update information based on current mount status.
14991     * Please note that we always have to report status if reportStatus has been
14992     * set to true especially when unloading packages.
14993     */
14994    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14995            boolean externalStorage) {
14996        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14997        int[] uidArr = EmptyArray.INT;
14998
14999        final String[] list = PackageHelper.getSecureContainerList();
15000        if (ArrayUtils.isEmpty(list)) {
15001            Log.i(TAG, "No secure containers found");
15002        } else {
15003            // Process list of secure containers and categorize them
15004            // as active or stale based on their package internal state.
15005
15006            // reader
15007            synchronized (mPackages) {
15008                for (String cid : list) {
15009                    // Leave stages untouched for now; installer service owns them
15010                    if (PackageInstallerService.isStageName(cid)) continue;
15011
15012                    if (DEBUG_SD_INSTALL)
15013                        Log.i(TAG, "Processing container " + cid);
15014                    String pkgName = getAsecPackageName(cid);
15015                    if (pkgName == null) {
15016                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15017                        continue;
15018                    }
15019                    if (DEBUG_SD_INSTALL)
15020                        Log.i(TAG, "Looking for pkg : " + pkgName);
15021
15022                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15023                    if (ps == null) {
15024                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15025                        continue;
15026                    }
15027
15028                    /*
15029                     * Skip packages that are not external if we're unmounting
15030                     * external storage.
15031                     */
15032                    if (externalStorage && !isMounted && !isExternal(ps)) {
15033                        continue;
15034                    }
15035
15036                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15037                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15038                    // The package status is changed only if the code path
15039                    // matches between settings and the container id.
15040                    if (ps.codePathString != null
15041                            && ps.codePathString.startsWith(args.getCodePath())) {
15042                        if (DEBUG_SD_INSTALL) {
15043                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15044                                    + " at code path: " + ps.codePathString);
15045                        }
15046
15047                        // We do have a valid package installed on sdcard
15048                        processCids.put(args, ps.codePathString);
15049                        final int uid = ps.appId;
15050                        if (uid != -1) {
15051                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15052                        }
15053                    } else {
15054                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15055                                + ps.codePathString);
15056                    }
15057                }
15058            }
15059
15060            Arrays.sort(uidArr);
15061        }
15062
15063        // Process packages with valid entries.
15064        if (isMounted) {
15065            if (DEBUG_SD_INSTALL)
15066                Log.i(TAG, "Loading packages");
15067            loadMediaPackages(processCids, uidArr);
15068            startCleaningPackages();
15069            mInstallerService.onSecureContainersAvailable();
15070        } else {
15071            if (DEBUG_SD_INSTALL)
15072                Log.i(TAG, "Unloading packages");
15073            unloadMediaPackages(processCids, uidArr, reportStatus);
15074        }
15075    }
15076
15077    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15078            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15079        final int size = infos.size();
15080        final String[] packageNames = new String[size];
15081        final int[] packageUids = new int[size];
15082        for (int i = 0; i < size; i++) {
15083            final ApplicationInfo info = infos.get(i);
15084            packageNames[i] = info.packageName;
15085            packageUids[i] = info.uid;
15086        }
15087        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15088                finishedReceiver);
15089    }
15090
15091    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15092            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15093        sendResourcesChangedBroadcast(mediaStatus, replacing,
15094                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15095    }
15096
15097    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15098            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15099        int size = pkgList.length;
15100        if (size > 0) {
15101            // Send broadcasts here
15102            Bundle extras = new Bundle();
15103            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15104            if (uidArr != null) {
15105                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15106            }
15107            if (replacing) {
15108                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15109            }
15110            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15111                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15112            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15113        }
15114    }
15115
15116   /*
15117     * Look at potentially valid container ids from processCids If package
15118     * information doesn't match the one on record or package scanning fails,
15119     * the cid is added to list of removeCids. We currently don't delete stale
15120     * containers.
15121     */
15122    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15123        ArrayList<String> pkgList = new ArrayList<String>();
15124        Set<AsecInstallArgs> keys = processCids.keySet();
15125
15126        for (AsecInstallArgs args : keys) {
15127            String codePath = processCids.get(args);
15128            if (DEBUG_SD_INSTALL)
15129                Log.i(TAG, "Loading container : " + args.cid);
15130            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15131            try {
15132                // Make sure there are no container errors first.
15133                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15134                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15135                            + " when installing from sdcard");
15136                    continue;
15137                }
15138                // Check code path here.
15139                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15140                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15141                            + " does not match one in settings " + codePath);
15142                    continue;
15143                }
15144                // Parse package
15145                int parseFlags = mDefParseFlags;
15146                if (args.isExternalAsec()) {
15147                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15148                }
15149                if (args.isFwdLocked()) {
15150                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15151                }
15152
15153                synchronized (mInstallLock) {
15154                    PackageParser.Package pkg = null;
15155                    try {
15156                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15157                    } catch (PackageManagerException e) {
15158                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15159                    }
15160                    // Scan the package
15161                    if (pkg != null) {
15162                        /*
15163                         * TODO why is the lock being held? doPostInstall is
15164                         * called in other places without the lock. This needs
15165                         * to be straightened out.
15166                         */
15167                        // writer
15168                        synchronized (mPackages) {
15169                            retCode = PackageManager.INSTALL_SUCCEEDED;
15170                            pkgList.add(pkg.packageName);
15171                            // Post process args
15172                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15173                                    pkg.applicationInfo.uid);
15174                        }
15175                    } else {
15176                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15177                    }
15178                }
15179
15180            } finally {
15181                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15182                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15183                }
15184            }
15185        }
15186        // writer
15187        synchronized (mPackages) {
15188            // If the platform SDK has changed since the last time we booted,
15189            // we need to re-grant app permission to catch any new ones that
15190            // appear. This is really a hack, and means that apps can in some
15191            // cases get permissions that the user didn't initially explicitly
15192            // allow... it would be nice to have some better way to handle
15193            // this situation.
15194            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15195            if (regrantPermissions)
15196                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15197                        + mSdkVersion + "; regranting permissions for external storage");
15198            mSettings.mExternalSdkPlatform = mSdkVersion;
15199
15200            // Make sure group IDs have been assigned, and any permission
15201            // changes in other apps are accounted for
15202            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15203                    | (regrantPermissions
15204                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15205                            : 0));
15206
15207            mSettings.updateExternalDatabaseVersion();
15208
15209            // can downgrade to reader
15210            // Persist settings
15211            mSettings.writeLPr();
15212        }
15213        // Send a broadcast to let everyone know we are done processing
15214        if (pkgList.size() > 0) {
15215            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15216        }
15217    }
15218
15219   /*
15220     * Utility method to unload a list of specified containers
15221     */
15222    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15223        // Just unmount all valid containers.
15224        for (AsecInstallArgs arg : cidArgs) {
15225            synchronized (mInstallLock) {
15226                arg.doPostDeleteLI(false);
15227           }
15228       }
15229   }
15230
15231    /*
15232     * Unload packages mounted on external media. This involves deleting package
15233     * data from internal structures, sending broadcasts about diabled packages,
15234     * gc'ing to free up references, unmounting all secure containers
15235     * corresponding to packages on external media, and posting a
15236     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15237     * that we always have to post this message if status has been requested no
15238     * matter what.
15239     */
15240    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15241            final boolean reportStatus) {
15242        if (DEBUG_SD_INSTALL)
15243            Log.i(TAG, "unloading media packages");
15244        ArrayList<String> pkgList = new ArrayList<String>();
15245        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15246        final Set<AsecInstallArgs> keys = processCids.keySet();
15247        for (AsecInstallArgs args : keys) {
15248            String pkgName = args.getPackageName();
15249            if (DEBUG_SD_INSTALL)
15250                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15251            // Delete package internally
15252            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15253            synchronized (mInstallLock) {
15254                boolean res = deletePackageLI(pkgName, null, false, null, null,
15255                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15256                if (res) {
15257                    pkgList.add(pkgName);
15258                } else {
15259                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15260                    failedList.add(args);
15261                }
15262            }
15263        }
15264
15265        // reader
15266        synchronized (mPackages) {
15267            // We didn't update the settings after removing each package;
15268            // write them now for all packages.
15269            mSettings.writeLPr();
15270        }
15271
15272        // We have to absolutely send UPDATED_MEDIA_STATUS only
15273        // after confirming that all the receivers processed the ordered
15274        // broadcast when packages get disabled, force a gc to clean things up.
15275        // and unload all the containers.
15276        if (pkgList.size() > 0) {
15277            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15278                    new IIntentReceiver.Stub() {
15279                public void performReceive(Intent intent, int resultCode, String data,
15280                        Bundle extras, boolean ordered, boolean sticky,
15281                        int sendingUser) throws RemoteException {
15282                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15283                            reportStatus ? 1 : 0, 1, keys);
15284                    mHandler.sendMessage(msg);
15285                }
15286            });
15287        } else {
15288            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15289                    keys);
15290            mHandler.sendMessage(msg);
15291        }
15292    }
15293
15294    private void loadPrivatePackages(VolumeInfo vol) {
15295        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15296        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15297        synchronized (mInstallLock) {
15298        synchronized (mPackages) {
15299            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15300            for (PackageSetting ps : packages) {
15301                final PackageParser.Package pkg;
15302                try {
15303                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15304                    loaded.add(pkg.applicationInfo);
15305                } catch (PackageManagerException e) {
15306                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15307                }
15308            }
15309
15310            // TODO: regrant any permissions that changed based since original install
15311
15312            mSettings.writeLPr();
15313        }
15314        }
15315
15316        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15317        sendResourcesChangedBroadcast(true, false, loaded, null);
15318    }
15319
15320    private void unloadPrivatePackages(VolumeInfo vol) {
15321        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15322        synchronized (mInstallLock) {
15323        synchronized (mPackages) {
15324            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15325            for (PackageSetting ps : packages) {
15326                if (ps.pkg == null) continue;
15327
15328                final ApplicationInfo info = ps.pkg.applicationInfo;
15329                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15330                if (deletePackageLI(ps.name, null, false, null, null,
15331                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15332                    unloaded.add(info);
15333                } else {
15334                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15335                }
15336            }
15337
15338            mSettings.writeLPr();
15339        }
15340        }
15341
15342        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15343        sendResourcesChangedBroadcast(false, false, unloaded, null);
15344    }
15345
15346    /**
15347     * Examine all users present on given mounted volume, and destroy data
15348     * belonging to users that are no longer valid, or whose user ID has been
15349     * recycled.
15350     */
15351    private void reconcileUsers(String volumeUuid) {
15352        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15353        if (ArrayUtils.isEmpty(files)) {
15354            Slog.d(TAG, "No users found on " + volumeUuid);
15355            return;
15356        }
15357
15358        for (File file : files) {
15359            if (!file.isDirectory()) continue;
15360
15361            final int userId;
15362            final UserInfo info;
15363            try {
15364                userId = Integer.parseInt(file.getName());
15365                info = sUserManager.getUserInfo(userId);
15366            } catch (NumberFormatException e) {
15367                Slog.w(TAG, "Invalid user directory " + file);
15368                continue;
15369            }
15370
15371            boolean destroyUser = false;
15372            if (info == null) {
15373                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15374                        + " because no matching user was found");
15375                destroyUser = true;
15376            } else {
15377                try {
15378                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15379                } catch (IOException e) {
15380                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15381                            + " because we failed to enforce serial number: " + e);
15382                    destroyUser = true;
15383                }
15384            }
15385
15386            if (destroyUser) {
15387                synchronized (mInstallLock) {
15388                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15389                }
15390            }
15391        }
15392
15393        final UserManager um = mContext.getSystemService(UserManager.class);
15394        for (UserInfo user : um.getUsers()) {
15395            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15396            if (userDir.exists()) continue;
15397
15398            try {
15399                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15400                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15401            } catch (IOException e) {
15402                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15403            }
15404        }
15405    }
15406
15407    /**
15408     * Examine all apps present on given mounted volume, and destroy apps that
15409     * aren't expected, either due to uninstallation or reinstallation on
15410     * another volume.
15411     */
15412    private void reconcileApps(String volumeUuid) {
15413        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15414        if (ArrayUtils.isEmpty(files)) {
15415            Slog.d(TAG, "No apps found on " + volumeUuid);
15416            return;
15417        }
15418
15419        for (File file : files) {
15420            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15421                    && !PackageInstallerService.isStageName(file.getName());
15422            if (!isPackage) {
15423                // Ignore entries which are not packages
15424                continue;
15425            }
15426
15427            boolean destroyApp = false;
15428            String packageName = null;
15429            try {
15430                final PackageLite pkg = PackageParser.parsePackageLite(file,
15431                        PackageParser.PARSE_MUST_BE_APK);
15432                packageName = pkg.packageName;
15433
15434                synchronized (mPackages) {
15435                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15436                    if (ps == null) {
15437                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15438                                + volumeUuid + " because we found no install record");
15439                        destroyApp = true;
15440                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15441                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15442                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15443                        destroyApp = true;
15444                    }
15445                }
15446
15447            } catch (PackageParserException e) {
15448                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15449                destroyApp = true;
15450            }
15451
15452            if (destroyApp) {
15453                synchronized (mInstallLock) {
15454                    if (packageName != null) {
15455                        removeDataDirsLI(volumeUuid, packageName);
15456                    }
15457                    if (file.isDirectory()) {
15458                        mInstaller.rmPackageDir(file.getAbsolutePath());
15459                    } else {
15460                        file.delete();
15461                    }
15462                }
15463            }
15464        }
15465    }
15466
15467    private void unfreezePackage(String packageName) {
15468        synchronized (mPackages) {
15469            final PackageSetting ps = mSettings.mPackages.get(packageName);
15470            if (ps != null) {
15471                ps.frozen = false;
15472            }
15473        }
15474    }
15475
15476    @Override
15477    public int movePackage(final String packageName, final String volumeUuid) {
15478        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15479
15480        final int moveId = mNextMoveId.getAndIncrement();
15481        try {
15482            movePackageInternal(packageName, volumeUuid, moveId);
15483        } catch (PackageManagerException e) {
15484            Slog.w(TAG, "Failed to move " + packageName, e);
15485            mMoveCallbacks.notifyStatusChanged(moveId,
15486                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15487        }
15488        return moveId;
15489    }
15490
15491    private void movePackageInternal(final String packageName, final String volumeUuid,
15492            final int moveId) throws PackageManagerException {
15493        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15494        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15495        final PackageManager pm = mContext.getPackageManager();
15496
15497        final boolean currentAsec;
15498        final String currentVolumeUuid;
15499        final File codeFile;
15500        final String installerPackageName;
15501        final String packageAbiOverride;
15502        final int appId;
15503        final String seinfo;
15504        final String label;
15505
15506        // reader
15507        synchronized (mPackages) {
15508            final PackageParser.Package pkg = mPackages.get(packageName);
15509            final PackageSetting ps = mSettings.mPackages.get(packageName);
15510            if (pkg == null || ps == null) {
15511                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15512            }
15513
15514            if (pkg.applicationInfo.isSystemApp()) {
15515                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15516                        "Cannot move system application");
15517            }
15518
15519            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15520                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15521                        "Package already moved to " + volumeUuid);
15522            }
15523
15524            final File probe = new File(pkg.codePath);
15525            final File probeOat = new File(probe, "oat");
15526            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15527                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15528                        "Move only supported for modern cluster style installs");
15529            }
15530
15531            if (ps.frozen) {
15532                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15533                        "Failed to move already frozen package");
15534            }
15535            ps.frozen = true;
15536
15537            currentAsec = pkg.applicationInfo.isForwardLocked()
15538                    || pkg.applicationInfo.isExternalAsec();
15539            currentVolumeUuid = ps.volumeUuid;
15540            codeFile = new File(pkg.codePath);
15541            installerPackageName = ps.installerPackageName;
15542            packageAbiOverride = ps.cpuAbiOverrideString;
15543            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15544            seinfo = pkg.applicationInfo.seinfo;
15545            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15546        }
15547
15548        // Now that we're guarded by frozen state, kill app during move
15549        killApplication(packageName, appId, "move pkg");
15550
15551        final Bundle extras = new Bundle();
15552        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15553        extras.putString(Intent.EXTRA_TITLE, label);
15554        mMoveCallbacks.notifyCreated(moveId, extras);
15555
15556        int installFlags;
15557        final boolean moveCompleteApp;
15558        final File measurePath;
15559
15560        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15561            installFlags = INSTALL_INTERNAL;
15562            moveCompleteApp = !currentAsec;
15563            measurePath = Environment.getDataAppDirectory(volumeUuid);
15564        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15565            installFlags = INSTALL_EXTERNAL;
15566            moveCompleteApp = false;
15567            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15568        } else {
15569            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15570            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15571                    || !volume.isMountedWritable()) {
15572                unfreezePackage(packageName);
15573                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15574                        "Move location not mounted private volume");
15575            }
15576
15577            Preconditions.checkState(!currentAsec);
15578
15579            installFlags = INSTALL_INTERNAL;
15580            moveCompleteApp = true;
15581            measurePath = Environment.getDataAppDirectory(volumeUuid);
15582        }
15583
15584        final PackageStats stats = new PackageStats(null, -1);
15585        synchronized (mInstaller) {
15586            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15587                unfreezePackage(packageName);
15588                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15589                        "Failed to measure package size");
15590            }
15591        }
15592
15593        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15594                + stats.dataSize);
15595
15596        final long startFreeBytes = measurePath.getFreeSpace();
15597        final long sizeBytes;
15598        if (moveCompleteApp) {
15599            sizeBytes = stats.codeSize + stats.dataSize;
15600        } else {
15601            sizeBytes = stats.codeSize;
15602        }
15603
15604        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15605            unfreezePackage(packageName);
15606            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15607                    "Not enough free space to move");
15608        }
15609
15610        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15611
15612        final CountDownLatch installedLatch = new CountDownLatch(1);
15613        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15614            @Override
15615            public void onUserActionRequired(Intent intent) throws RemoteException {
15616                throw new IllegalStateException();
15617            }
15618
15619            @Override
15620            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15621                    Bundle extras) throws RemoteException {
15622                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15623                        + PackageManager.installStatusToString(returnCode, msg));
15624
15625                installedLatch.countDown();
15626
15627                // Regardless of success or failure of the move operation,
15628                // always unfreeze the package
15629                unfreezePackage(packageName);
15630
15631                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15632                switch (status) {
15633                    case PackageInstaller.STATUS_SUCCESS:
15634                        mMoveCallbacks.notifyStatusChanged(moveId,
15635                                PackageManager.MOVE_SUCCEEDED);
15636                        break;
15637                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15638                        mMoveCallbacks.notifyStatusChanged(moveId,
15639                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15640                        break;
15641                    default:
15642                        mMoveCallbacks.notifyStatusChanged(moveId,
15643                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15644                        break;
15645                }
15646            }
15647        };
15648
15649        final MoveInfo move;
15650        if (moveCompleteApp) {
15651            // Kick off a thread to report progress estimates
15652            new Thread() {
15653                @Override
15654                public void run() {
15655                    while (true) {
15656                        try {
15657                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15658                                break;
15659                            }
15660                        } catch (InterruptedException ignored) {
15661                        }
15662
15663                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15664                        final int progress = 10 + (int) MathUtils.constrain(
15665                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15666                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15667                    }
15668                }
15669            }.start();
15670
15671            final String dataAppName = codeFile.getName();
15672            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15673                    dataAppName, appId, seinfo);
15674        } else {
15675            move = null;
15676        }
15677
15678        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15679
15680        final Message msg = mHandler.obtainMessage(INIT_COPY);
15681        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15682        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15683                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15684        mHandler.sendMessage(msg);
15685    }
15686
15687    @Override
15688    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15689        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15690
15691        final int realMoveId = mNextMoveId.getAndIncrement();
15692        final Bundle extras = new Bundle();
15693        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15694        mMoveCallbacks.notifyCreated(realMoveId, extras);
15695
15696        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15697            @Override
15698            public void onCreated(int moveId, Bundle extras) {
15699                // Ignored
15700            }
15701
15702            @Override
15703            public void onStatusChanged(int moveId, int status, long estMillis) {
15704                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15705            }
15706        };
15707
15708        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15709        storage.setPrimaryStorageUuid(volumeUuid, callback);
15710        return realMoveId;
15711    }
15712
15713    @Override
15714    public int getMoveStatus(int moveId) {
15715        mContext.enforceCallingOrSelfPermission(
15716                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15717        return mMoveCallbacks.mLastStatus.get(moveId);
15718    }
15719
15720    @Override
15721    public void registerMoveCallback(IPackageMoveObserver callback) {
15722        mContext.enforceCallingOrSelfPermission(
15723                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15724        mMoveCallbacks.register(callback);
15725    }
15726
15727    @Override
15728    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15729        mContext.enforceCallingOrSelfPermission(
15730                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15731        mMoveCallbacks.unregister(callback);
15732    }
15733
15734    @Override
15735    public boolean setInstallLocation(int loc) {
15736        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15737                null);
15738        if (getInstallLocation() == loc) {
15739            return true;
15740        }
15741        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15742                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15743            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15744                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15745            return true;
15746        }
15747        return false;
15748   }
15749
15750    @Override
15751    public int getInstallLocation() {
15752        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15753                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15754                PackageHelper.APP_INSTALL_AUTO);
15755    }
15756
15757    /** Called by UserManagerService */
15758    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15759        mDirtyUsers.remove(userHandle);
15760        mSettings.removeUserLPw(userHandle);
15761        mPendingBroadcasts.remove(userHandle);
15762        if (mInstaller != null) {
15763            // Technically, we shouldn't be doing this with the package lock
15764            // held.  However, this is very rare, and there is already so much
15765            // other disk I/O going on, that we'll let it slide for now.
15766            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15767            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15768                final String volumeUuid = vol.getFsUuid();
15769                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15770                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15771            }
15772        }
15773        mUserNeedsBadging.delete(userHandle);
15774        removeUnusedPackagesLILPw(userManager, userHandle);
15775    }
15776
15777    /**
15778     * We're removing userHandle and would like to remove any downloaded packages
15779     * that are no longer in use by any other user.
15780     * @param userHandle the user being removed
15781     */
15782    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15783        final boolean DEBUG_CLEAN_APKS = false;
15784        int [] users = userManager.getUserIdsLPr();
15785        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15786        while (psit.hasNext()) {
15787            PackageSetting ps = psit.next();
15788            if (ps.pkg == null) {
15789                continue;
15790            }
15791            final String packageName = ps.pkg.packageName;
15792            // Skip over if system app
15793            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15794                continue;
15795            }
15796            if (DEBUG_CLEAN_APKS) {
15797                Slog.i(TAG, "Checking package " + packageName);
15798            }
15799            boolean keep = false;
15800            for (int i = 0; i < users.length; i++) {
15801                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15802                    keep = true;
15803                    if (DEBUG_CLEAN_APKS) {
15804                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15805                                + users[i]);
15806                    }
15807                    break;
15808                }
15809            }
15810            if (!keep) {
15811                if (DEBUG_CLEAN_APKS) {
15812                    Slog.i(TAG, "  Removing package " + packageName);
15813                }
15814                mHandler.post(new Runnable() {
15815                    public void run() {
15816                        deletePackageX(packageName, userHandle, 0);
15817                    } //end run
15818                });
15819            }
15820        }
15821    }
15822
15823    /** Called by UserManagerService */
15824    void createNewUserLILPw(int userHandle) {
15825        if (mInstaller != null) {
15826            mInstaller.createUserConfig(userHandle);
15827            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15828            applyFactoryDefaultBrowserLPw(userHandle);
15829        }
15830    }
15831
15832    void newUserCreatedLILPw(final int userHandle) {
15833        // We cannot grant the default permissions with a lock held as
15834        // we query providers from other components for default handlers
15835        // such as enabled IMEs, etc.
15836        mHandler.post(new Runnable() {
15837            @Override
15838            public void run() {
15839                mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15840            }
15841        });
15842    }
15843
15844    @Override
15845    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15846        mContext.enforceCallingOrSelfPermission(
15847                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15848                "Only package verification agents can read the verifier device identity");
15849
15850        synchronized (mPackages) {
15851            return mSettings.getVerifierDeviceIdentityLPw();
15852        }
15853    }
15854
15855    @Override
15856    public void setPermissionEnforced(String permission, boolean enforced) {
15857        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15858        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15859            synchronized (mPackages) {
15860                if (mSettings.mReadExternalStorageEnforced == null
15861                        || mSettings.mReadExternalStorageEnforced != enforced) {
15862                    mSettings.mReadExternalStorageEnforced = enforced;
15863                    mSettings.writeLPr();
15864                }
15865            }
15866            // kill any non-foreground processes so we restart them and
15867            // grant/revoke the GID.
15868            final IActivityManager am = ActivityManagerNative.getDefault();
15869            if (am != null) {
15870                final long token = Binder.clearCallingIdentity();
15871                try {
15872                    am.killProcessesBelowForeground("setPermissionEnforcement");
15873                } catch (RemoteException e) {
15874                } finally {
15875                    Binder.restoreCallingIdentity(token);
15876                }
15877            }
15878        } else {
15879            throw new IllegalArgumentException("No selective enforcement for " + permission);
15880        }
15881    }
15882
15883    @Override
15884    @Deprecated
15885    public boolean isPermissionEnforced(String permission) {
15886        return true;
15887    }
15888
15889    @Override
15890    public boolean isStorageLow() {
15891        final long token = Binder.clearCallingIdentity();
15892        try {
15893            final DeviceStorageMonitorInternal
15894                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
15895            if (dsm != null) {
15896                return dsm.isMemoryLow();
15897            } else {
15898                return false;
15899            }
15900        } finally {
15901            Binder.restoreCallingIdentity(token);
15902        }
15903    }
15904
15905    @Override
15906    public IPackageInstaller getPackageInstaller() {
15907        return mInstallerService;
15908    }
15909
15910    private boolean userNeedsBadging(int userId) {
15911        int index = mUserNeedsBadging.indexOfKey(userId);
15912        if (index < 0) {
15913            final UserInfo userInfo;
15914            final long token = Binder.clearCallingIdentity();
15915            try {
15916                userInfo = sUserManager.getUserInfo(userId);
15917            } finally {
15918                Binder.restoreCallingIdentity(token);
15919            }
15920            final boolean b;
15921            if (userInfo != null && userInfo.isManagedProfile()) {
15922                b = true;
15923            } else {
15924                b = false;
15925            }
15926            mUserNeedsBadging.put(userId, b);
15927            return b;
15928        }
15929        return mUserNeedsBadging.valueAt(index);
15930    }
15931
15932    @Override
15933    public KeySet getKeySetByAlias(String packageName, String alias) {
15934        if (packageName == null || alias == null) {
15935            return null;
15936        }
15937        synchronized(mPackages) {
15938            final PackageParser.Package pkg = mPackages.get(packageName);
15939            if (pkg == null) {
15940                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15941                throw new IllegalArgumentException("Unknown package: " + packageName);
15942            }
15943            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15944            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
15945        }
15946    }
15947
15948    @Override
15949    public KeySet getSigningKeySet(String packageName) {
15950        if (packageName == null) {
15951            return null;
15952        }
15953        synchronized(mPackages) {
15954            final PackageParser.Package pkg = mPackages.get(packageName);
15955            if (pkg == null) {
15956                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15957                throw new IllegalArgumentException("Unknown package: " + packageName);
15958            }
15959            if (pkg.applicationInfo.uid != Binder.getCallingUid()
15960                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
15961                throw new SecurityException("May not access signing KeySet of other apps.");
15962            }
15963            KeySetManagerService ksms = mSettings.mKeySetManagerService;
15964            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
15965        }
15966    }
15967
15968    @Override
15969    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
15970        if (packageName == null || ks == null) {
15971            return false;
15972        }
15973        synchronized(mPackages) {
15974            final PackageParser.Package pkg = mPackages.get(packageName);
15975            if (pkg == null) {
15976                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15977                throw new IllegalArgumentException("Unknown package: " + packageName);
15978            }
15979            IBinder ksh = ks.getToken();
15980            if (ksh instanceof KeySetHandle) {
15981                KeySetManagerService ksms = mSettings.mKeySetManagerService;
15982                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
15983            }
15984            return false;
15985        }
15986    }
15987
15988    @Override
15989    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
15990        if (packageName == null || ks == null) {
15991            return false;
15992        }
15993        synchronized(mPackages) {
15994            final PackageParser.Package pkg = mPackages.get(packageName);
15995            if (pkg == null) {
15996                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
15997                throw new IllegalArgumentException("Unknown package: " + packageName);
15998            }
15999            IBinder ksh = ks.getToken();
16000            if (ksh instanceof KeySetHandle) {
16001                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16002                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16003            }
16004            return false;
16005        }
16006    }
16007
16008    public void getUsageStatsIfNoPackageUsageInfo() {
16009        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16010            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16011            if (usm == null) {
16012                throw new IllegalStateException("UsageStatsManager must be initialized");
16013            }
16014            long now = System.currentTimeMillis();
16015            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16016            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16017                String packageName = entry.getKey();
16018                PackageParser.Package pkg = mPackages.get(packageName);
16019                if (pkg == null) {
16020                    continue;
16021                }
16022                UsageStats usage = entry.getValue();
16023                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16024                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16025            }
16026        }
16027    }
16028
16029    /**
16030     * Check and throw if the given before/after packages would be considered a
16031     * downgrade.
16032     */
16033    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16034            throws PackageManagerException {
16035        if (after.versionCode < before.mVersionCode) {
16036            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16037                    "Update version code " + after.versionCode + " is older than current "
16038                    + before.mVersionCode);
16039        } else if (after.versionCode == before.mVersionCode) {
16040            if (after.baseRevisionCode < before.baseRevisionCode) {
16041                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16042                        "Update base revision code " + after.baseRevisionCode
16043                        + " is older than current " + before.baseRevisionCode);
16044            }
16045
16046            if (!ArrayUtils.isEmpty(after.splitNames)) {
16047                for (int i = 0; i < after.splitNames.length; i++) {
16048                    final String splitName = after.splitNames[i];
16049                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16050                    if (j != -1) {
16051                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16052                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16053                                    "Update split " + splitName + " revision code "
16054                                    + after.splitRevisionCodes[i] + " is older than current "
16055                                    + before.splitRevisionCodes[j]);
16056                        }
16057                    }
16058                }
16059            }
16060        }
16061    }
16062
16063    private static class MoveCallbacks extends Handler {
16064        private static final int MSG_CREATED = 1;
16065        private static final int MSG_STATUS_CHANGED = 2;
16066
16067        private final RemoteCallbackList<IPackageMoveObserver>
16068                mCallbacks = new RemoteCallbackList<>();
16069
16070        private final SparseIntArray mLastStatus = new SparseIntArray();
16071
16072        public MoveCallbacks(Looper looper) {
16073            super(looper);
16074        }
16075
16076        public void register(IPackageMoveObserver callback) {
16077            mCallbacks.register(callback);
16078        }
16079
16080        public void unregister(IPackageMoveObserver callback) {
16081            mCallbacks.unregister(callback);
16082        }
16083
16084        @Override
16085        public void handleMessage(Message msg) {
16086            final SomeArgs args = (SomeArgs) msg.obj;
16087            final int n = mCallbacks.beginBroadcast();
16088            for (int i = 0; i < n; i++) {
16089                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16090                try {
16091                    invokeCallback(callback, msg.what, args);
16092                } catch (RemoteException ignored) {
16093                }
16094            }
16095            mCallbacks.finishBroadcast();
16096            args.recycle();
16097        }
16098
16099        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16100                throws RemoteException {
16101            switch (what) {
16102                case MSG_CREATED: {
16103                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16104                    break;
16105                }
16106                case MSG_STATUS_CHANGED: {
16107                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16108                    break;
16109                }
16110            }
16111        }
16112
16113        private void notifyCreated(int moveId, Bundle extras) {
16114            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16115
16116            final SomeArgs args = SomeArgs.obtain();
16117            args.argi1 = moveId;
16118            args.arg2 = extras;
16119            obtainMessage(MSG_CREATED, args).sendToTarget();
16120        }
16121
16122        private void notifyStatusChanged(int moveId, int status) {
16123            notifyStatusChanged(moveId, status, -1);
16124        }
16125
16126        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16127            Slog.v(TAG, "Move " + moveId + " status " + status);
16128
16129            final SomeArgs args = SomeArgs.obtain();
16130            args.argi1 = moveId;
16131            args.argi2 = status;
16132            args.arg3 = estMillis;
16133            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16134
16135            synchronized (mLastStatus) {
16136                mLastStatus.put(moveId, status);
16137            }
16138        }
16139    }
16140
16141    private final class OnPermissionChangeListeners extends Handler {
16142        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16143
16144        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16145                new RemoteCallbackList<>();
16146
16147        public OnPermissionChangeListeners(Looper looper) {
16148            super(looper);
16149        }
16150
16151        @Override
16152        public void handleMessage(Message msg) {
16153            switch (msg.what) {
16154                case MSG_ON_PERMISSIONS_CHANGED: {
16155                    final int uid = msg.arg1;
16156                    handleOnPermissionsChanged(uid);
16157                } break;
16158            }
16159        }
16160
16161        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16162            mPermissionListeners.register(listener);
16163
16164        }
16165
16166        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16167            mPermissionListeners.unregister(listener);
16168        }
16169
16170        public void onPermissionsChanged(int uid) {
16171            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16172                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16173            }
16174        }
16175
16176        private void handleOnPermissionsChanged(int uid) {
16177            final int count = mPermissionListeners.beginBroadcast();
16178            try {
16179                for (int i = 0; i < count; i++) {
16180                    IOnPermissionsChangeListener callback = mPermissionListeners
16181                            .getBroadcastItem(i);
16182                    try {
16183                        callback.onPermissionsChanged(uid);
16184                    } catch (RemoteException e) {
16185                        Log.e(TAG, "Permission listener is dead", e);
16186                    }
16187                }
16188            } finally {
16189                mPermissionListeners.finishBroadcast();
16190            }
16191        }
16192    }
16193
16194    private class PackageManagerInternalImpl extends PackageManagerInternal {
16195        @Override
16196        public void setLocationPackagesProvider(PackagesProvider provider) {
16197            synchronized (mPackages) {
16198                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16199            }
16200        }
16201
16202        @Override
16203        public void setImePackagesProvider(PackagesProvider provider) {
16204            synchronized (mPackages) {
16205                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16206            }
16207        }
16208
16209        @Override
16210        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16211            synchronized (mPackages) {
16212                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16213            }
16214        }
16215
16216        @Override
16217        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16218            synchronized (mPackages) {
16219                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16220            }
16221        }
16222
16223        @Override
16224        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16225            synchronized (mPackages) {
16226                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16227            }
16228        }
16229
16230        @Override
16231        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16232            synchronized (mPackages) {
16233                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16234            }
16235        }
16236
16237        @Override
16238        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16239            synchronized (mPackages) {
16240                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16241                        packageName, userId);
16242            }
16243        }
16244
16245        @Override
16246        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16247            synchronized (mPackages) {
16248                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16249                        packageName, userId);
16250            }
16251        }
16252    }
16253
16254    @Override
16255    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16256        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16257        synchronized (mPackages) {
16258            final long identity = Binder.clearCallingIdentity();
16259            try {
16260                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16261                        packageNames, userId);
16262            } finally {
16263                Binder.restoreCallingIdentity(identity);
16264            }
16265        }
16266    }
16267
16268    private static void enforceSystemOrPhoneCaller(String tag) {
16269        int callingUid = Binder.getCallingUid();
16270        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16271            throw new SecurityException(
16272                    "Cannot call " + tag + " from UID " + callingUid);
16273        }
16274    }
16275}
16276