PackageManagerService.java revision 5cc9a7a801f3a1995cbb2a7dae3f9a716d51df0e
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.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
62import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
63import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
64import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
65import static android.content.pm.PackageManager.PERMISSION_GRANTED;
66import static android.content.pm.PackageParser.isApkFile;
67import static android.os.Process.PACKAGE_INFO_GID;
68import static android.os.Process.SYSTEM_UID;
69import static android.system.OsConstants.O_CREAT;
70import static android.system.OsConstants.O_RDWR;
71import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
72import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
73import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
74import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
75import static com.android.internal.util.ArrayUtils.appendInt;
76import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
77import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
78import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
79import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
80import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
81import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
82import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
83import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
84
85import android.Manifest;
86import android.app.ActivityManager;
87import android.app.ActivityManagerNative;
88import android.app.AppGlobals;
89import android.app.IActivityManager;
90import android.app.admin.IDevicePolicyManager;
91import android.app.backup.IBackupManager;
92import android.app.usage.UsageStats;
93import android.app.usage.UsageStatsManager;
94import android.content.BroadcastReceiver;
95import android.content.ComponentName;
96import android.content.Context;
97import android.content.IIntentReceiver;
98import android.content.Intent;
99import android.content.IntentFilter;
100import android.content.IntentSender;
101import android.content.IntentSender.SendIntentException;
102import android.content.ServiceConnection;
103import android.content.pm.ActivityInfo;
104import android.content.pm.ApplicationInfo;
105import android.content.pm.FeatureInfo;
106import android.content.pm.IOnPermissionsChangeListener;
107import android.content.pm.IPackageDataObserver;
108import android.content.pm.IPackageDeleteObserver;
109import android.content.pm.IPackageDeleteObserver2;
110import android.content.pm.IPackageInstallObserver2;
111import android.content.pm.IPackageInstaller;
112import android.content.pm.IPackageManager;
113import android.content.pm.IPackageMoveObserver;
114import android.content.pm.IPackageStatsObserver;
115import android.content.pm.InstrumentationInfo;
116import android.content.pm.IntentFilterVerificationInfo;
117import android.content.pm.KeySet;
118import android.content.pm.ManifestDigest;
119import android.content.pm.PackageCleanItem;
120import android.content.pm.PackageInfo;
121import android.content.pm.PackageInfoLite;
122import android.content.pm.PackageInstaller;
123import android.content.pm.PackageManager;
124import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
125import android.content.pm.PackageManagerInternal;
126import android.content.pm.PackageParser;
127import android.content.pm.PackageParser.ActivityIntentInfo;
128import android.content.pm.PackageParser.PackageLite;
129import android.content.pm.PackageParser.PackageParserException;
130import android.content.pm.PackageStats;
131import android.content.pm.PackageUserState;
132import android.content.pm.ParceledListSlice;
133import android.content.pm.PermissionGroupInfo;
134import android.content.pm.PermissionInfo;
135import android.content.pm.ProviderInfo;
136import android.content.pm.ResolveInfo;
137import android.content.pm.ServiceInfo;
138import android.content.pm.Signature;
139import android.content.pm.UserInfo;
140import android.content.pm.VerificationParams;
141import android.content.pm.VerifierDeviceIdentity;
142import android.content.pm.VerifierInfo;
143import android.content.res.Resources;
144import android.hardware.display.DisplayManager;
145import android.net.Uri;
146import android.os.Binder;
147import android.os.Build;
148import android.os.Bundle;
149import android.os.Debug;
150import android.os.Environment;
151import android.os.Environment.UserEnvironment;
152import android.os.FileUtils;
153import android.os.Handler;
154import android.os.IBinder;
155import android.os.Looper;
156import android.os.Message;
157import android.os.Parcel;
158import android.os.ParcelFileDescriptor;
159import android.os.Process;
160import android.os.RemoteCallbackList;
161import android.os.RemoteException;
162import android.os.SELinux;
163import android.os.ServiceManager;
164import android.os.SystemClock;
165import android.os.SystemProperties;
166import android.os.UserHandle;
167import android.os.UserManager;
168import android.os.storage.IMountService;
169import android.os.storage.StorageEventListener;
170import android.os.storage.StorageManager;
171import android.os.storage.VolumeInfo;
172import android.os.storage.VolumeRecord;
173import android.security.KeyStore;
174import android.security.SystemKeyStore;
175import android.system.ErrnoException;
176import android.system.Os;
177import android.system.StructStat;
178import android.text.TextUtils;
179import android.text.format.DateUtils;
180import android.util.ArrayMap;
181import android.util.ArraySet;
182import android.util.AtomicFile;
183import android.util.DisplayMetrics;
184import android.util.EventLog;
185import android.util.ExceptionUtils;
186import android.util.Log;
187import android.util.LogPrinter;
188import android.util.MathUtils;
189import android.util.PrintStreamPrinter;
190import android.util.Slog;
191import android.util.SparseArray;
192import android.util.SparseBooleanArray;
193import android.util.SparseIntArray;
194import android.util.Xml;
195import android.view.Display;
196
197import dalvik.system.DexFile;
198import dalvik.system.VMRuntime;
199
200import libcore.io.IoUtils;
201import libcore.util.EmptyArray;
202
203import com.android.internal.R;
204import com.android.internal.annotations.GuardedBy;
205import com.android.internal.app.IMediaContainerService;
206import com.android.internal.app.ResolverActivity;
207import com.android.internal.content.NativeLibraryHelper;
208import com.android.internal.content.PackageHelper;
209import com.android.internal.os.IParcelFileDescriptorFactory;
210import com.android.internal.os.SomeArgs;
211import com.android.internal.os.Zygote;
212import com.android.internal.util.ArrayUtils;
213import com.android.internal.util.FastPrintWriter;
214import com.android.internal.util.FastXmlSerializer;
215import com.android.internal.util.IndentingPrintWriter;
216import com.android.internal.util.Preconditions;
217import com.android.server.EventLogTags;
218import com.android.server.FgThread;
219import com.android.server.IntentResolver;
220import com.android.server.LocalServices;
221import com.android.server.ServiceThread;
222import com.android.server.SystemConfig;
223import com.android.server.Watchdog;
224import com.android.server.pm.PermissionsState.PermissionState;
225import com.android.server.pm.Settings.DatabaseVersion;
226import com.android.server.storage.DeviceStorageMonitorInternal;
227
228import org.xmlpull.v1.XmlPullParser;
229import org.xmlpull.v1.XmlPullParserException;
230import org.xmlpull.v1.XmlSerializer;
231
232import java.io.BufferedInputStream;
233import java.io.BufferedOutputStream;
234import java.io.BufferedReader;
235import java.io.ByteArrayInputStream;
236import java.io.ByteArrayOutputStream;
237import java.io.File;
238import java.io.FileDescriptor;
239import java.io.FileNotFoundException;
240import java.io.FileOutputStream;
241import java.io.FileReader;
242import java.io.FilenameFilter;
243import java.io.IOException;
244import java.io.InputStream;
245import java.io.PrintWriter;
246import java.nio.charset.StandardCharsets;
247import java.security.NoSuchAlgorithmException;
248import java.security.PublicKey;
249import java.security.cert.CertificateEncodingException;
250import java.security.cert.CertificateException;
251import java.text.SimpleDateFormat;
252import java.util.ArrayList;
253import java.util.Arrays;
254import java.util.Collection;
255import java.util.Collections;
256import java.util.Comparator;
257import java.util.Date;
258import java.util.Iterator;
259import java.util.List;
260import java.util.Map;
261import java.util.Objects;
262import java.util.Set;
263import java.util.concurrent.CountDownLatch;
264import java.util.concurrent.TimeUnit;
265import java.util.concurrent.atomic.AtomicBoolean;
266import java.util.concurrent.atomic.AtomicInteger;
267import java.util.concurrent.atomic.AtomicLong;
268
269/**
270 * Keep track of all those .apks everywhere.
271 *
272 * This is very central to the platform's security; please run the unit
273 * tests whenever making modifications here:
274 *
275runtest -c android.content.pm.PackageManagerTests frameworks-core
276 *
277 * {@hide}
278 */
279public class PackageManagerService extends IPackageManager.Stub {
280    static final String TAG = "PackageManager";
281    static final boolean DEBUG_SETTINGS = false;
282    static final boolean DEBUG_PREFERRED = false;
283    static final boolean DEBUG_UPGRADE = false;
284    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
285    private static final boolean DEBUG_BACKUP = true;
286    private static final boolean DEBUG_INSTALL = false;
287    private static final boolean DEBUG_REMOVE = false;
288    private static final boolean DEBUG_BROADCASTS = false;
289    private static final boolean DEBUG_SHOW_INFO = false;
290    private static final boolean DEBUG_PACKAGE_INFO = false;
291    private static final boolean DEBUG_INTENT_MATCHING = false;
292    private static final boolean DEBUG_PACKAGE_SCANNING = false;
293    private static final boolean DEBUG_VERIFY = false;
294    private static final boolean DEBUG_DEXOPT = false;
295    private static final boolean DEBUG_ABI_SELECTION = false;
296
297    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = Build.IS_DEBUGGABLE;
298
299    private static final int RADIO_UID = Process.PHONE_UID;
300    private static final int LOG_UID = Process.LOG_UID;
301    private static final int NFC_UID = Process.NFC_UID;
302    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
303    private static final int SHELL_UID = Process.SHELL_UID;
304
305    // Cap the size of permission trees that 3rd party apps can define
306    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
307
308    // Suffix used during package installation when copying/moving
309    // package apks to install directory.
310    private static final String INSTALL_PACKAGE_SUFFIX = "-";
311
312    static final int SCAN_NO_DEX = 1<<1;
313    static final int SCAN_FORCE_DEX = 1<<2;
314    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
315    static final int SCAN_NEW_INSTALL = 1<<4;
316    static final int SCAN_NO_PATHS = 1<<5;
317    static final int SCAN_UPDATE_TIME = 1<<6;
318    static final int SCAN_DEFER_DEX = 1<<7;
319    static final int SCAN_BOOTING = 1<<8;
320    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
321    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
322    static final int SCAN_REQUIRE_KNOWN = 1<<12;
323    static final int SCAN_MOVE = 1<<13;
324    static final int SCAN_INITIAL = 1<<14;
325
326    static final int REMOVE_CHATTY = 1<<16;
327
328    private static final int[] EMPTY_INT_ARRAY = new int[0];
329
330    /**
331     * Timeout (in milliseconds) after which the watchdog should declare that
332     * our handler thread is wedged.  The usual default for such things is one
333     * minute but we sometimes do very lengthy I/O operations on this thread,
334     * such as installing multi-gigabyte applications, so ours needs to be longer.
335     */
336    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
337
338    /**
339     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
340     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
341     * settings entry if available, otherwise we use the hardcoded default.  If it's been
342     * more than this long since the last fstrim, we force one during the boot sequence.
343     *
344     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
345     * one gets run at the next available charging+idle time.  This final mandatory
346     * no-fstrim check kicks in only of the other scheduling criteria is never met.
347     */
348    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
349
350    /**
351     * Whether verification is enabled by default.
352     */
353    private static final boolean DEFAULT_VERIFY_ENABLE = true;
354
355    /**
356     * The default maximum time to wait for the verification agent to return in
357     * milliseconds.
358     */
359    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
360
361    /**
362     * The default response for package verification timeout.
363     *
364     * This can be either PackageManager.VERIFICATION_ALLOW or
365     * PackageManager.VERIFICATION_REJECT.
366     */
367    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
368
369    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
370
371    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
372            DEFAULT_CONTAINER_PACKAGE,
373            "com.android.defcontainer.DefaultContainerService");
374
375    private static final String KILL_APP_REASON_GIDS_CHANGED =
376            "permission grant or revoke changed gids";
377
378    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
379            "permissions revoked";
380
381    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
382
383    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
384
385    /** Permission grant: not grant the permission. */
386    private static final int GRANT_DENIED = 1;
387
388    /** Permission grant: grant the permission as an install permission. */
389    private static final int GRANT_INSTALL = 2;
390
391    /** Permission grant: grant the permission as an install permission for a legacy app. */
392    private static final int GRANT_INSTALL_LEGACY = 3;
393
394    /** Permission grant: grant the permission as a runtime one. */
395    private static final int GRANT_RUNTIME = 4;
396
397    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
398    private static final int GRANT_UPGRADE = 5;
399
400    /** Canonical intent used to identify what counts as a "web browser" app */
401    private static final Intent sBrowserIntent;
402    static {
403        sBrowserIntent = new Intent();
404        sBrowserIntent.setAction(Intent.ACTION_VIEW);
405        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
406        sBrowserIntent.setData(Uri.parse("http:"));
407    }
408
409    final ServiceThread mHandlerThread;
410
411    final PackageHandler mHandler;
412
413    /**
414     * Messages for {@link #mHandler} that need to wait for system ready before
415     * being dispatched.
416     */
417    private ArrayList<Message> mPostSystemReadyMessages;
418
419    final int mSdkVersion = Build.VERSION.SDK_INT;
420
421    final Context mContext;
422    final boolean mFactoryTest;
423    final boolean mOnlyCore;
424    final boolean mLazyDexOpt;
425    final long mDexOptLRUThresholdInMills;
426    final DisplayMetrics mMetrics;
427    final int mDefParseFlags;
428    final String[] mSeparateProcesses;
429    final boolean mIsUpgrade;
430
431    // This is where all application persistent data goes.
432    final File mAppDataDir;
433
434    // This is where all application persistent data goes for secondary users.
435    final File mUserAppDataDir;
436
437    /** The location for ASEC container files on internal storage. */
438    final String mAsecInternalPath;
439
440    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
441    // LOCK HELD.  Can be called with mInstallLock held.
442    @GuardedBy("mInstallLock")
443    final Installer mInstaller;
444
445    /** Directory where installed third-party apps stored */
446    final File mAppInstallDir;
447
448    /**
449     * Directory to which applications installed internally have their
450     * 32 bit native libraries copied.
451     */
452    private File mAppLib32InstallDir;
453
454    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
455    // apps.
456    final File mDrmAppPrivateInstallDir;
457
458    // ----------------------------------------------------------------
459
460    // Lock for state used when installing and doing other long running
461    // operations.  Methods that must be called with this lock held have
462    // the suffix "LI".
463    final Object mInstallLock = new Object();
464
465    // ----------------------------------------------------------------
466
467    // Keys are String (package name), values are Package.  This also serves
468    // as the lock for the global state.  Methods that must be called with
469    // this lock held have the prefix "LP".
470    @GuardedBy("mPackages")
471    final ArrayMap<String, PackageParser.Package> mPackages =
472            new ArrayMap<String, PackageParser.Package>();
473
474    // Tracks available target package names -> overlay package paths.
475    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
476        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
477
478    /**
479     * Tracks new system packages [receiving in an OTA] that we expect to
480     * find updated user-installed versions. Keys are package name, values
481     * are package location.
482     */
483    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
484
485    final Settings mSettings;
486    boolean mRestoredSettings;
487
488    // System configuration read by SystemConfig.
489    final int[] mGlobalGids;
490    final SparseArray<ArraySet<String>> mSystemPermissions;
491    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
492
493    // If mac_permissions.xml was found for seinfo labeling.
494    boolean mFoundPolicyFile;
495
496    // If a recursive restorecon of /data/data/<pkg> is needed.
497    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
498
499    public static final class SharedLibraryEntry {
500        public final String path;
501        public final String apk;
502
503        SharedLibraryEntry(String _path, String _apk) {
504            path = _path;
505            apk = _apk;
506        }
507    }
508
509    // Currently known shared libraries.
510    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
511            new ArrayMap<String, SharedLibraryEntry>();
512
513    // All available activities, for your resolving pleasure.
514    final ActivityIntentResolver mActivities =
515            new ActivityIntentResolver();
516
517    // All available receivers, for your resolving pleasure.
518    final ActivityIntentResolver mReceivers =
519            new ActivityIntentResolver();
520
521    // All available services, for your resolving pleasure.
522    final ServiceIntentResolver mServices = new ServiceIntentResolver();
523
524    // All available providers, for your resolving pleasure.
525    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
526
527    // Mapping from provider base names (first directory in content URI codePath)
528    // to the provider information.
529    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
530            new ArrayMap<String, PackageParser.Provider>();
531
532    // Mapping from instrumentation class names to info about them.
533    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
534            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
535
536    // Mapping from permission names to info about them.
537    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
538            new ArrayMap<String, PackageParser.PermissionGroup>();
539
540    // Packages whose data we have transfered into another package, thus
541    // should no longer exist.
542    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
543
544    // Broadcast actions that are only available to the system.
545    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
546
547    /** List of packages waiting for verification. */
548    final SparseArray<PackageVerificationState> mPendingVerification
549            = new SparseArray<PackageVerificationState>();
550
551    /** Set of packages associated with each app op permission. */
552    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
553
554    final PackageInstallerService mInstallerService;
555
556    private final PackageDexOptimizer mPackageDexOptimizer;
557
558    private AtomicInteger mNextMoveId = new AtomicInteger();
559    private final MoveCallbacks mMoveCallbacks;
560
561    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
562
563    // Cache of users who need badging.
564    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
565
566    /** Token for keys in mPendingVerification. */
567    private int mPendingVerificationToken = 0;
568
569    volatile boolean mSystemReady;
570    volatile boolean mSafeMode;
571    volatile boolean mHasSystemUidErrors;
572
573    ApplicationInfo mAndroidApplication;
574    final ActivityInfo mResolveActivity = new ActivityInfo();
575    final ResolveInfo mResolveInfo = new ResolveInfo();
576    ComponentName mResolveComponentName;
577    PackageParser.Package mPlatformPackage;
578    ComponentName mCustomResolverComponentName;
579
580    boolean mResolverReplaced = false;
581
582    private final ComponentName mIntentFilterVerifierComponent;
583    private int mIntentFilterVerificationToken = 0;
584
585    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
586            = new SparseArray<IntentFilterVerificationState>();
587
588    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
589            new DefaultPermissionGrantPolicy(this);
590
591    private static class IFVerificationParams {
592        PackageParser.Package pkg;
593        boolean replacing;
594        int userId;
595        int verifierUid;
596
597        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
598                int _userId, int _verifierUid) {
599            pkg = _pkg;
600            replacing = _replacing;
601            userId = _userId;
602            replacing = _replacing;
603            verifierUid = _verifierUid;
604        }
605    }
606
607    private interface IntentFilterVerifier<T extends IntentFilter> {
608        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
609                                               T filter, String packageName);
610        void startVerifications(int userId);
611        void receiveVerificationResponse(int verificationId);
612    }
613
614    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
615        private Context mContext;
616        private ComponentName mIntentFilterVerifierComponent;
617        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
618
619        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
620            mContext = context;
621            mIntentFilterVerifierComponent = verifierComponent;
622        }
623
624        private String getDefaultScheme() {
625            return IntentFilter.SCHEME_HTTPS;
626        }
627
628        @Override
629        public void startVerifications(int userId) {
630            // Launch verifications requests
631            int count = mCurrentIntentFilterVerifications.size();
632            for (int n=0; n<count; n++) {
633                int verificationId = mCurrentIntentFilterVerifications.get(n);
634                final IntentFilterVerificationState ivs =
635                        mIntentFilterVerificationStates.get(verificationId);
636
637                String packageName = ivs.getPackageName();
638
639                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
640                final int filterCount = filters.size();
641                ArraySet<String> domainsSet = new ArraySet<>();
642                for (int m=0; m<filterCount; m++) {
643                    PackageParser.ActivityIntentInfo filter = filters.get(m);
644                    domainsSet.addAll(filter.getHostsList());
645                }
646                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
647                synchronized (mPackages) {
648                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
649                            packageName, domainsList) != null) {
650                        scheduleWriteSettingsLocked();
651                    }
652                }
653                sendVerificationRequest(userId, verificationId, ivs);
654            }
655            mCurrentIntentFilterVerifications.clear();
656        }
657
658        private void sendVerificationRequest(int userId, int verificationId,
659                IntentFilterVerificationState ivs) {
660
661            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
662            verificationIntent.putExtra(
663                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
664                    verificationId);
665            verificationIntent.putExtra(
666                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
667                    getDefaultScheme());
668            verificationIntent.putExtra(
669                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
670                    ivs.getHostsString());
671            verificationIntent.putExtra(
672                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
673                    ivs.getPackageName());
674            verificationIntent.setComponent(mIntentFilterVerifierComponent);
675            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
676
677            UserHandle user = new UserHandle(userId);
678            mContext.sendBroadcastAsUser(verificationIntent, user);
679            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
680                    "Sending IntentFilter verification broadcast");
681        }
682
683        public void receiveVerificationResponse(int verificationId) {
684            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
685
686            final boolean verified = ivs.isVerified();
687
688            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
689            final int count = filters.size();
690            if (DEBUG_DOMAIN_VERIFICATION) {
691                Slog.i(TAG, "Received verification response " + verificationId
692                        + " for " + count + " filters, verified=" + verified);
693            }
694            for (int n=0; n<count; n++) {
695                PackageParser.ActivityIntentInfo filter = filters.get(n);
696                filter.setVerified(verified);
697
698                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
699                        + " verified with result:" + verified + " and hosts:"
700                        + ivs.getHostsString());
701            }
702
703            mIntentFilterVerificationStates.remove(verificationId);
704
705            final String packageName = ivs.getPackageName();
706            IntentFilterVerificationInfo ivi = null;
707
708            synchronized (mPackages) {
709                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
710            }
711            if (ivi == null) {
712                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
713                        + verificationId + " packageName:" + packageName);
714                return;
715            }
716            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
717                    "Updating IntentFilterVerificationInfo for package " + packageName
718                            +" verificationId:" + verificationId);
719
720            synchronized (mPackages) {
721                if (verified) {
722                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
723                } else {
724                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
725                }
726                scheduleWriteSettingsLocked();
727
728                final int userId = ivs.getUserId();
729                if (userId != UserHandle.USER_ALL) {
730                    final int userStatus =
731                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
732
733                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
734                    boolean needUpdate = false;
735
736                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
737                    // already been set by the User thru the Disambiguation dialog
738                    switch (userStatus) {
739                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
740                            if (verified) {
741                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
742                            } else {
743                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
744                            }
745                            needUpdate = true;
746                            break;
747
748                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
749                            if (verified) {
750                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
751                                needUpdate = true;
752                            }
753                            break;
754
755                        default:
756                            // Nothing to do
757                    }
758
759                    if (needUpdate) {
760                        mSettings.updateIntentFilterVerificationStatusLPw(
761                                packageName, updatedStatus, userId);
762                        scheduleWritePackageRestrictionsLocked(userId);
763                    }
764                }
765            }
766        }
767
768        @Override
769        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
770                    ActivityIntentInfo filter, String packageName) {
771            if (!hasValidDomains(filter)) {
772                return false;
773            }
774            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
775            if (ivs == null) {
776                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
777                        packageName);
778            }
779            if (DEBUG_DOMAIN_VERIFICATION) {
780                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
781            }
782            ivs.addFilter(filter);
783            return true;
784        }
785
786        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
787                int userId, int verificationId, String packageName) {
788            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
789                    verifierUid, userId, packageName);
790            ivs.setPendingState();
791            synchronized (mPackages) {
792                mIntentFilterVerificationStates.append(verificationId, ivs);
793                mCurrentIntentFilterVerifications.add(verificationId);
794            }
795            return ivs;
796        }
797    }
798
799    private static boolean hasValidDomains(ActivityIntentInfo filter) {
800        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
801                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
802        if (!hasHTTPorHTTPS) {
803            return false;
804        }
805        return true;
806    }
807
808    private IntentFilterVerifier mIntentFilterVerifier;
809
810    // Set of pending broadcasts for aggregating enable/disable of components.
811    static class PendingPackageBroadcasts {
812        // for each user id, a map of <package name -> components within that package>
813        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
814
815        public PendingPackageBroadcasts() {
816            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
817        }
818
819        public ArrayList<String> get(int userId, String packageName) {
820            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
821            return packages.get(packageName);
822        }
823
824        public void put(int userId, String packageName, ArrayList<String> components) {
825            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
826            packages.put(packageName, components);
827        }
828
829        public void remove(int userId, String packageName) {
830            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
831            if (packages != null) {
832                packages.remove(packageName);
833            }
834        }
835
836        public void remove(int userId) {
837            mUidMap.remove(userId);
838        }
839
840        public int userIdCount() {
841            return mUidMap.size();
842        }
843
844        public int userIdAt(int n) {
845            return mUidMap.keyAt(n);
846        }
847
848        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
849            return mUidMap.get(userId);
850        }
851
852        public int size() {
853            // total number of pending broadcast entries across all userIds
854            int num = 0;
855            for (int i = 0; i< mUidMap.size(); i++) {
856                num += mUidMap.valueAt(i).size();
857            }
858            return num;
859        }
860
861        public void clear() {
862            mUidMap.clear();
863        }
864
865        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
866            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
867            if (map == null) {
868                map = new ArrayMap<String, ArrayList<String>>();
869                mUidMap.put(userId, map);
870            }
871            return map;
872        }
873    }
874    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
875
876    // Service Connection to remote media container service to copy
877    // package uri's from external media onto secure containers
878    // or internal storage.
879    private IMediaContainerService mContainerService = null;
880
881    static final int SEND_PENDING_BROADCAST = 1;
882    static final int MCS_BOUND = 3;
883    static final int END_COPY = 4;
884    static final int INIT_COPY = 5;
885    static final int MCS_UNBIND = 6;
886    static final int START_CLEANING_PACKAGE = 7;
887    static final int FIND_INSTALL_LOC = 8;
888    static final int POST_INSTALL = 9;
889    static final int MCS_RECONNECT = 10;
890    static final int MCS_GIVE_UP = 11;
891    static final int UPDATED_MEDIA_STATUS = 12;
892    static final int WRITE_SETTINGS = 13;
893    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
894    static final int PACKAGE_VERIFIED = 15;
895    static final int CHECK_PENDING_VERIFICATION = 16;
896    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
897    static final int INTENT_FILTER_VERIFIED = 18;
898
899    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
900
901    // Delay time in millisecs
902    static final int BROADCAST_DELAY = 10 * 1000;
903
904    static UserManagerService sUserManager;
905
906    // Stores a list of users whose package restrictions file needs to be updated
907    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
908
909    final private DefaultContainerConnection mDefContainerConn =
910            new DefaultContainerConnection();
911    class DefaultContainerConnection implements ServiceConnection {
912        public void onServiceConnected(ComponentName name, IBinder service) {
913            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
914            IMediaContainerService imcs =
915                IMediaContainerService.Stub.asInterface(service);
916            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
917        }
918
919        public void onServiceDisconnected(ComponentName name) {
920            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
921        }
922    }
923
924    // Recordkeeping of restore-after-install operations that are currently in flight
925    // between the Package Manager and the Backup Manager
926    class PostInstallData {
927        public InstallArgs args;
928        public PackageInstalledInfo res;
929
930        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
931            args = _a;
932            res = _r;
933        }
934    }
935
936    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
937    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
938
939    // XML tags for backup/restore of various bits of state
940    private static final String TAG_PREFERRED_BACKUP = "pa";
941    private static final String TAG_DEFAULT_APPS = "da";
942    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
943
944    final String mRequiredVerifierPackage;
945    final String mRequiredInstallerPackage;
946
947    private final PackageUsage mPackageUsage = new PackageUsage();
948
949    private class PackageUsage {
950        private static final int WRITE_INTERVAL
951            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
952
953        private final Object mFileLock = new Object();
954        private final AtomicLong mLastWritten = new AtomicLong(0);
955        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
956
957        private boolean mIsHistoricalPackageUsageAvailable = true;
958
959        boolean isHistoricalPackageUsageAvailable() {
960            return mIsHistoricalPackageUsageAvailable;
961        }
962
963        void write(boolean force) {
964            if (force) {
965                writeInternal();
966                return;
967            }
968            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
969                && !DEBUG_DEXOPT) {
970                return;
971            }
972            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
973                new Thread("PackageUsage_DiskWriter") {
974                    @Override
975                    public void run() {
976                        try {
977                            writeInternal();
978                        } finally {
979                            mBackgroundWriteRunning.set(false);
980                        }
981                    }
982                }.start();
983            }
984        }
985
986        private void writeInternal() {
987            synchronized (mPackages) {
988                synchronized (mFileLock) {
989                    AtomicFile file = getFile();
990                    FileOutputStream f = null;
991                    try {
992                        f = file.startWrite();
993                        BufferedOutputStream out = new BufferedOutputStream(f);
994                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
995                        StringBuilder sb = new StringBuilder();
996                        for (PackageParser.Package pkg : mPackages.values()) {
997                            if (pkg.mLastPackageUsageTimeInMills == 0) {
998                                continue;
999                            }
1000                            sb.setLength(0);
1001                            sb.append(pkg.packageName);
1002                            sb.append(' ');
1003                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1004                            sb.append('\n');
1005                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1006                        }
1007                        out.flush();
1008                        file.finishWrite(f);
1009                    } catch (IOException e) {
1010                        if (f != null) {
1011                            file.failWrite(f);
1012                        }
1013                        Log.e(TAG, "Failed to write package usage times", e);
1014                    }
1015                }
1016            }
1017            mLastWritten.set(SystemClock.elapsedRealtime());
1018        }
1019
1020        void readLP() {
1021            synchronized (mFileLock) {
1022                AtomicFile file = getFile();
1023                BufferedInputStream in = null;
1024                try {
1025                    in = new BufferedInputStream(file.openRead());
1026                    StringBuffer sb = new StringBuffer();
1027                    while (true) {
1028                        String packageName = readToken(in, sb, ' ');
1029                        if (packageName == null) {
1030                            break;
1031                        }
1032                        String timeInMillisString = readToken(in, sb, '\n');
1033                        if (timeInMillisString == null) {
1034                            throw new IOException("Failed to find last usage time for package "
1035                                                  + packageName);
1036                        }
1037                        PackageParser.Package pkg = mPackages.get(packageName);
1038                        if (pkg == null) {
1039                            continue;
1040                        }
1041                        long timeInMillis;
1042                        try {
1043                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1044                        } catch (NumberFormatException e) {
1045                            throw new IOException("Failed to parse " + timeInMillisString
1046                                                  + " as a long.", e);
1047                        }
1048                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1049                    }
1050                } catch (FileNotFoundException expected) {
1051                    mIsHistoricalPackageUsageAvailable = false;
1052                } catch (IOException e) {
1053                    Log.w(TAG, "Failed to read package usage times", e);
1054                } finally {
1055                    IoUtils.closeQuietly(in);
1056                }
1057            }
1058            mLastWritten.set(SystemClock.elapsedRealtime());
1059        }
1060
1061        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1062                throws IOException {
1063            sb.setLength(0);
1064            while (true) {
1065                int ch = in.read();
1066                if (ch == -1) {
1067                    if (sb.length() == 0) {
1068                        return null;
1069                    }
1070                    throw new IOException("Unexpected EOF");
1071                }
1072                if (ch == endOfToken) {
1073                    return sb.toString();
1074                }
1075                sb.append((char)ch);
1076            }
1077        }
1078
1079        private AtomicFile getFile() {
1080            File dataDir = Environment.getDataDirectory();
1081            File systemDir = new File(dataDir, "system");
1082            File fname = new File(systemDir, "package-usage.list");
1083            return new AtomicFile(fname);
1084        }
1085    }
1086
1087    class PackageHandler extends Handler {
1088        private boolean mBound = false;
1089        final ArrayList<HandlerParams> mPendingInstalls =
1090            new ArrayList<HandlerParams>();
1091
1092        private boolean connectToService() {
1093            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1094                    " DefaultContainerService");
1095            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1096            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1097            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1098                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1099                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1100                mBound = true;
1101                return true;
1102            }
1103            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1104            return false;
1105        }
1106
1107        private void disconnectService() {
1108            mContainerService = null;
1109            mBound = false;
1110            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1111            mContext.unbindService(mDefContainerConn);
1112            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1113        }
1114
1115        PackageHandler(Looper looper) {
1116            super(looper);
1117        }
1118
1119        public void handleMessage(Message msg) {
1120            try {
1121                doHandleMessage(msg);
1122            } finally {
1123                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1124            }
1125        }
1126
1127        void doHandleMessage(Message msg) {
1128            switch (msg.what) {
1129                case INIT_COPY: {
1130                    HandlerParams params = (HandlerParams) msg.obj;
1131                    int idx = mPendingInstalls.size();
1132                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1133                    // If a bind was already initiated we dont really
1134                    // need to do anything. The pending install
1135                    // will be processed later on.
1136                    if (!mBound) {
1137                        // If this is the only one pending we might
1138                        // have to bind to the service again.
1139                        if (!connectToService()) {
1140                            Slog.e(TAG, "Failed to bind to media container service");
1141                            params.serviceError();
1142                            return;
1143                        } else {
1144                            // Once we bind to the service, the first
1145                            // pending request will be processed.
1146                            mPendingInstalls.add(idx, params);
1147                        }
1148                    } else {
1149                        mPendingInstalls.add(idx, params);
1150                        // Already bound to the service. Just make
1151                        // sure we trigger off processing the first request.
1152                        if (idx == 0) {
1153                            mHandler.sendEmptyMessage(MCS_BOUND);
1154                        }
1155                    }
1156                    break;
1157                }
1158                case MCS_BOUND: {
1159                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1160                    if (msg.obj != null) {
1161                        mContainerService = (IMediaContainerService) msg.obj;
1162                    }
1163                    if (mContainerService == null) {
1164                        if (!mBound) {
1165                            // Something seriously wrong since we are not bound and we are not
1166                            // waiting for connection. Bail out.
1167                            Slog.e(TAG, "Cannot bind to media container service");
1168                            for (HandlerParams params : mPendingInstalls) {
1169                                // Indicate service bind error
1170                                params.serviceError();
1171                            }
1172                            mPendingInstalls.clear();
1173                        } else {
1174                            Slog.w(TAG, "Waiting to connect to media container service");
1175                        }
1176                    } else if (mPendingInstalls.size() > 0) {
1177                        HandlerParams params = mPendingInstalls.get(0);
1178                        if (params != null) {
1179                            if (params.startCopy()) {
1180                                // We are done...  look for more work or to
1181                                // go idle.
1182                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1183                                        "Checking for more work or unbind...");
1184                                // Delete pending install
1185                                if (mPendingInstalls.size() > 0) {
1186                                    mPendingInstalls.remove(0);
1187                                }
1188                                if (mPendingInstalls.size() == 0) {
1189                                    if (mBound) {
1190                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1191                                                "Posting delayed MCS_UNBIND");
1192                                        removeMessages(MCS_UNBIND);
1193                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1194                                        // Unbind after a little delay, to avoid
1195                                        // continual thrashing.
1196                                        sendMessageDelayed(ubmsg, 10000);
1197                                    }
1198                                } else {
1199                                    // There are more pending requests in queue.
1200                                    // Just post MCS_BOUND message to trigger processing
1201                                    // of next pending install.
1202                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1203                                            "Posting MCS_BOUND for next work");
1204                                    mHandler.sendEmptyMessage(MCS_BOUND);
1205                                }
1206                            }
1207                        }
1208                    } else {
1209                        // Should never happen ideally.
1210                        Slog.w(TAG, "Empty queue");
1211                    }
1212                    break;
1213                }
1214                case MCS_RECONNECT: {
1215                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1216                    if (mPendingInstalls.size() > 0) {
1217                        if (mBound) {
1218                            disconnectService();
1219                        }
1220                        if (!connectToService()) {
1221                            Slog.e(TAG, "Failed to bind to media container service");
1222                            for (HandlerParams params : mPendingInstalls) {
1223                                // Indicate service bind error
1224                                params.serviceError();
1225                            }
1226                            mPendingInstalls.clear();
1227                        }
1228                    }
1229                    break;
1230                }
1231                case MCS_UNBIND: {
1232                    // If there is no actual work left, then time to unbind.
1233                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1234
1235                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1236                        if (mBound) {
1237                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1238
1239                            disconnectService();
1240                        }
1241                    } else if (mPendingInstalls.size() > 0) {
1242                        // There are more pending requests in queue.
1243                        // Just post MCS_BOUND message to trigger processing
1244                        // of next pending install.
1245                        mHandler.sendEmptyMessage(MCS_BOUND);
1246                    }
1247
1248                    break;
1249                }
1250                case MCS_GIVE_UP: {
1251                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1252                    mPendingInstalls.remove(0);
1253                    break;
1254                }
1255                case SEND_PENDING_BROADCAST: {
1256                    String packages[];
1257                    ArrayList<String> components[];
1258                    int size = 0;
1259                    int uids[];
1260                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1261                    synchronized (mPackages) {
1262                        if (mPendingBroadcasts == null) {
1263                            return;
1264                        }
1265                        size = mPendingBroadcasts.size();
1266                        if (size <= 0) {
1267                            // Nothing to be done. Just return
1268                            return;
1269                        }
1270                        packages = new String[size];
1271                        components = new ArrayList[size];
1272                        uids = new int[size];
1273                        int i = 0;  // filling out the above arrays
1274
1275                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1276                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1277                            Iterator<Map.Entry<String, ArrayList<String>>> it
1278                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1279                                            .entrySet().iterator();
1280                            while (it.hasNext() && i < size) {
1281                                Map.Entry<String, ArrayList<String>> ent = it.next();
1282                                packages[i] = ent.getKey();
1283                                components[i] = ent.getValue();
1284                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1285                                uids[i] = (ps != null)
1286                                        ? UserHandle.getUid(packageUserId, ps.appId)
1287                                        : -1;
1288                                i++;
1289                            }
1290                        }
1291                        size = i;
1292                        mPendingBroadcasts.clear();
1293                    }
1294                    // Send broadcasts
1295                    for (int i = 0; i < size; i++) {
1296                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1297                    }
1298                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1299                    break;
1300                }
1301                case START_CLEANING_PACKAGE: {
1302                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1303                    final String packageName = (String)msg.obj;
1304                    final int userId = msg.arg1;
1305                    final boolean andCode = msg.arg2 != 0;
1306                    synchronized (mPackages) {
1307                        if (userId == UserHandle.USER_ALL) {
1308                            int[] users = sUserManager.getUserIds();
1309                            for (int user : users) {
1310                                mSettings.addPackageToCleanLPw(
1311                                        new PackageCleanItem(user, packageName, andCode));
1312                            }
1313                        } else {
1314                            mSettings.addPackageToCleanLPw(
1315                                    new PackageCleanItem(userId, packageName, andCode));
1316                        }
1317                    }
1318                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1319                    startCleaningPackages();
1320                } break;
1321                case POST_INSTALL: {
1322                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1323                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1324                    mRunningInstalls.delete(msg.arg1);
1325                    boolean deleteOld = false;
1326
1327                    if (data != null) {
1328                        InstallArgs args = data.args;
1329                        PackageInstalledInfo res = data.res;
1330
1331                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1332                            final String packageName = res.pkg.applicationInfo.packageName;
1333                            res.removedInfo.sendBroadcast(false, true, false);
1334                            Bundle extras = new Bundle(1);
1335                            extras.putInt(Intent.EXTRA_UID, res.uid);
1336
1337                            // Now that we successfully installed the package, grant runtime
1338                            // permissions if requested before broadcasting the install.
1339                            if ((args.installFlags
1340                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1341                                grantRequestedRuntimePermissions(res.pkg,
1342                                        args.user.getIdentifier());
1343                            }
1344
1345                            // Determine the set of users who are adding this
1346                            // package for the first time vs. those who are seeing
1347                            // an update.
1348                            int[] firstUsers;
1349                            int[] updateUsers = new int[0];
1350                            if (res.origUsers == null || res.origUsers.length == 0) {
1351                                firstUsers = res.newUsers;
1352                            } else {
1353                                firstUsers = new int[0];
1354                                for (int i=0; i<res.newUsers.length; i++) {
1355                                    int user = res.newUsers[i];
1356                                    boolean isNew = true;
1357                                    for (int j=0; j<res.origUsers.length; j++) {
1358                                        if (res.origUsers[j] == user) {
1359                                            isNew = false;
1360                                            break;
1361                                        }
1362                                    }
1363                                    if (isNew) {
1364                                        int[] newFirst = new int[firstUsers.length+1];
1365                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1366                                                firstUsers.length);
1367                                        newFirst[firstUsers.length] = user;
1368                                        firstUsers = newFirst;
1369                                    } else {
1370                                        int[] newUpdate = new int[updateUsers.length+1];
1371                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1372                                                updateUsers.length);
1373                                        newUpdate[updateUsers.length] = user;
1374                                        updateUsers = newUpdate;
1375                                    }
1376                                }
1377                            }
1378                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1379                                    packageName, extras, null, null, firstUsers);
1380                            final boolean update = res.removedInfo.removedPackage != null;
1381                            if (update) {
1382                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1383                            }
1384                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1385                                    packageName, extras, null, null, updateUsers);
1386                            if (update) {
1387                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1388                                        packageName, extras, null, null, updateUsers);
1389                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1390                                        null, null, packageName, null, updateUsers);
1391
1392                                // treat asec-hosted packages like removable media on upgrade
1393                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1394                                    if (DEBUG_INSTALL) {
1395                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1396                                                + " is ASEC-hosted -> AVAILABLE");
1397                                    }
1398                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1399                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1400                                    pkgList.add(packageName);
1401                                    sendResourcesChangedBroadcast(true, true,
1402                                            pkgList,uidArray, null);
1403                                }
1404                            }
1405                            if (res.removedInfo.args != null) {
1406                                // Remove the replaced package's older resources safely now
1407                                deleteOld = true;
1408                            }
1409
1410                            // If this app is a browser and it's newly-installed for some
1411                            // users, clear any default-browser state in those users
1412                            if (firstUsers.length > 0) {
1413                                // the app's nature doesn't depend on the user, so we can just
1414                                // check its browser nature in any user and generalize.
1415                                if (packageIsBrowser(packageName, firstUsers[0])) {
1416                                    synchronized (mPackages) {
1417                                        for (int userId : firstUsers) {
1418                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1419                                        }
1420                                    }
1421                                }
1422                            }
1423                            // Log current value of "unknown sources" setting
1424                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1425                                getUnknownSourcesSettings());
1426                        }
1427                        // Force a gc to clear up things
1428                        Runtime.getRuntime().gc();
1429                        // We delete after a gc for applications  on sdcard.
1430                        if (deleteOld) {
1431                            synchronized (mInstallLock) {
1432                                res.removedInfo.args.doPostDeleteLI(true);
1433                            }
1434                        }
1435                        if (args.observer != null) {
1436                            try {
1437                                Bundle extras = extrasForInstallResult(res);
1438                                args.observer.onPackageInstalled(res.name, res.returnCode,
1439                                        res.returnMsg, extras);
1440                            } catch (RemoteException e) {
1441                                Slog.i(TAG, "Observer no longer exists.");
1442                            }
1443                        }
1444                    } else {
1445                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1446                    }
1447                } break;
1448                case UPDATED_MEDIA_STATUS: {
1449                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1450                    boolean reportStatus = msg.arg1 == 1;
1451                    boolean doGc = msg.arg2 == 1;
1452                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1453                    if (doGc) {
1454                        // Force a gc to clear up stale containers.
1455                        Runtime.getRuntime().gc();
1456                    }
1457                    if (msg.obj != null) {
1458                        @SuppressWarnings("unchecked")
1459                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1460                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1461                        // Unload containers
1462                        unloadAllContainers(args);
1463                    }
1464                    if (reportStatus) {
1465                        try {
1466                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1467                            PackageHelper.getMountService().finishMediaUpdate();
1468                        } catch (RemoteException e) {
1469                            Log.e(TAG, "MountService not running?");
1470                        }
1471                    }
1472                } break;
1473                case WRITE_SETTINGS: {
1474                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1475                    synchronized (mPackages) {
1476                        removeMessages(WRITE_SETTINGS);
1477                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1478                        mSettings.writeLPr();
1479                        mDirtyUsers.clear();
1480                    }
1481                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1482                } break;
1483                case WRITE_PACKAGE_RESTRICTIONS: {
1484                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1485                    synchronized (mPackages) {
1486                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1487                        for (int userId : mDirtyUsers) {
1488                            mSettings.writePackageRestrictionsLPr(userId);
1489                        }
1490                        mDirtyUsers.clear();
1491                    }
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1493                } break;
1494                case CHECK_PENDING_VERIFICATION: {
1495                    final int verificationId = msg.arg1;
1496                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1497
1498                    if ((state != null) && !state.timeoutExtended()) {
1499                        final InstallArgs args = state.getInstallArgs();
1500                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1501
1502                        Slog.i(TAG, "Verification timed out for " + originUri);
1503                        mPendingVerification.remove(verificationId);
1504
1505                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1506
1507                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1508                            Slog.i(TAG, "Continuing with installation of " + originUri);
1509                            state.setVerifierResponse(Binder.getCallingUid(),
1510                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1511                            broadcastPackageVerified(verificationId, originUri,
1512                                    PackageManager.VERIFICATION_ALLOW,
1513                                    state.getInstallArgs().getUser());
1514                            try {
1515                                ret = args.copyApk(mContainerService, true);
1516                            } catch (RemoteException e) {
1517                                Slog.e(TAG, "Could not contact the ContainerService");
1518                            }
1519                        } else {
1520                            broadcastPackageVerified(verificationId, originUri,
1521                                    PackageManager.VERIFICATION_REJECT,
1522                                    state.getInstallArgs().getUser());
1523                        }
1524
1525                        processPendingInstall(args, ret);
1526                        mHandler.sendEmptyMessage(MCS_UNBIND);
1527                    }
1528                    break;
1529                }
1530                case PACKAGE_VERIFIED: {
1531                    final int verificationId = msg.arg1;
1532
1533                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1534                    if (state == null) {
1535                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1536                        break;
1537                    }
1538
1539                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1540
1541                    state.setVerifierResponse(response.callerUid, response.code);
1542
1543                    if (state.isVerificationComplete()) {
1544                        mPendingVerification.remove(verificationId);
1545
1546                        final InstallArgs args = state.getInstallArgs();
1547                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1548
1549                        int ret;
1550                        if (state.isInstallAllowed()) {
1551                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1552                            broadcastPackageVerified(verificationId, originUri,
1553                                    response.code, state.getInstallArgs().getUser());
1554                            try {
1555                                ret = args.copyApk(mContainerService, true);
1556                            } catch (RemoteException e) {
1557                                Slog.e(TAG, "Could not contact the ContainerService");
1558                            }
1559                        } else {
1560                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1561                        }
1562
1563                        processPendingInstall(args, ret);
1564
1565                        mHandler.sendEmptyMessage(MCS_UNBIND);
1566                    }
1567
1568                    break;
1569                }
1570                case START_INTENT_FILTER_VERIFICATIONS: {
1571                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1572                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1573                            params.replacing, params.pkg);
1574                    break;
1575                }
1576                case INTENT_FILTER_VERIFIED: {
1577                    final int verificationId = msg.arg1;
1578
1579                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1580                            verificationId);
1581                    if (state == null) {
1582                        Slog.w(TAG, "Invalid IntentFilter verification token "
1583                                + verificationId + " received");
1584                        break;
1585                    }
1586
1587                    final int userId = state.getUserId();
1588
1589                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1590                            "Processing IntentFilter verification with token:"
1591                            + verificationId + " and userId:" + userId);
1592
1593                    final IntentFilterVerificationResponse response =
1594                            (IntentFilterVerificationResponse) msg.obj;
1595
1596                    state.setVerifierResponse(response.callerUid, response.code);
1597
1598                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1599                            "IntentFilter verification with token:" + verificationId
1600                            + " and userId:" + userId
1601                            + " is settings verifier response with response code:"
1602                            + response.code);
1603
1604                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1605                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1606                                + response.getFailedDomainsString());
1607                    }
1608
1609                    if (state.isVerificationComplete()) {
1610                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1611                    } else {
1612                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1613                                "IntentFilter verification with token:" + verificationId
1614                                + " was not said to be complete");
1615                    }
1616
1617                    break;
1618                }
1619            }
1620        }
1621    }
1622
1623    private StorageEventListener mStorageListener = new StorageEventListener() {
1624        @Override
1625        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1626            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1627                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1628                    final String volumeUuid = vol.getFsUuid();
1629
1630                    // Clean up any users or apps that were removed or recreated
1631                    // while this volume was missing
1632                    reconcileUsers(volumeUuid);
1633                    reconcileApps(volumeUuid);
1634
1635                    // Clean up any install sessions that expired or were
1636                    // cancelled while this volume was missing
1637                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1638
1639                    loadPrivatePackages(vol);
1640
1641                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1642                    unloadPrivatePackages(vol);
1643                }
1644            }
1645
1646            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1647                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1648                    updateExternalMediaStatus(true, false);
1649                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1650                    updateExternalMediaStatus(false, false);
1651                }
1652            }
1653        }
1654
1655        @Override
1656        public void onVolumeForgotten(String fsUuid) {
1657            // Remove any apps installed on the forgotten volume
1658            synchronized (mPackages) {
1659                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1660                for (PackageSetting ps : packages) {
1661                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1662                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1663                            UserHandle.USER_OWNER, PackageManager.DELETE_ALL_USERS);
1664                }
1665
1666                mSettings.writeLPr();
1667            }
1668        }
1669    };
1670
1671    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1672        if (userId >= UserHandle.USER_OWNER) {
1673            grantRequestedRuntimePermissionsForUser(pkg, userId);
1674        } else if (userId == UserHandle.USER_ALL) {
1675            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1676                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1677            }
1678        }
1679
1680        // We could have touched GID membership, so flush out packages.list
1681        synchronized (mPackages) {
1682            mSettings.writePackageListLPr();
1683        }
1684    }
1685
1686    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1687        SettingBase sb = (SettingBase) pkg.mExtras;
1688        if (sb == null) {
1689            return;
1690        }
1691
1692        PermissionsState permissionsState = sb.getPermissionsState();
1693
1694        for (String permission : pkg.requestedPermissions) {
1695            BasePermission bp = mSettings.mPermissions.get(permission);
1696            if (bp != null && bp.isRuntime()) {
1697                permissionsState.grantRuntimePermission(bp, userId);
1698            }
1699        }
1700    }
1701
1702    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1703        Bundle extras = null;
1704        switch (res.returnCode) {
1705            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1706                extras = new Bundle();
1707                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1708                        res.origPermission);
1709                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1710                        res.origPackage);
1711                break;
1712            }
1713            case PackageManager.INSTALL_SUCCEEDED: {
1714                extras = new Bundle();
1715                extras.putBoolean(Intent.EXTRA_REPLACING,
1716                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1717                break;
1718            }
1719        }
1720        return extras;
1721    }
1722
1723    void scheduleWriteSettingsLocked() {
1724        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1725            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1726        }
1727    }
1728
1729    void scheduleWritePackageRestrictionsLocked(int userId) {
1730        if (!sUserManager.exists(userId)) return;
1731        mDirtyUsers.add(userId);
1732        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1733            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1734        }
1735    }
1736
1737    public static PackageManagerService main(Context context, Installer installer,
1738            boolean factoryTest, boolean onlyCore) {
1739        PackageManagerService m = new PackageManagerService(context, installer,
1740                factoryTest, onlyCore);
1741        ServiceManager.addService("package", m);
1742        return m;
1743    }
1744
1745    static String[] splitString(String str, char sep) {
1746        int count = 1;
1747        int i = 0;
1748        while ((i=str.indexOf(sep, i)) >= 0) {
1749            count++;
1750            i++;
1751        }
1752
1753        String[] res = new String[count];
1754        i=0;
1755        count = 0;
1756        int lastI=0;
1757        while ((i=str.indexOf(sep, i)) >= 0) {
1758            res[count] = str.substring(lastI, i);
1759            count++;
1760            i++;
1761            lastI = i;
1762        }
1763        res[count] = str.substring(lastI, str.length());
1764        return res;
1765    }
1766
1767    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1768        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1769                Context.DISPLAY_SERVICE);
1770        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1771    }
1772
1773    public PackageManagerService(Context context, Installer installer,
1774            boolean factoryTest, boolean onlyCore) {
1775        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1776                SystemClock.uptimeMillis());
1777
1778        if (mSdkVersion <= 0) {
1779            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1780        }
1781
1782        mContext = context;
1783        mFactoryTest = factoryTest;
1784        mOnlyCore = onlyCore;
1785        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1786        mMetrics = new DisplayMetrics();
1787        mSettings = new Settings(mPackages);
1788        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1789                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1790        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1791                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1792        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1793                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1794        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1795                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1796        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1797                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1798        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1799                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1800
1801        // TODO: add a property to control this?
1802        long dexOptLRUThresholdInMinutes;
1803        if (mLazyDexOpt) {
1804            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1805        } else {
1806            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1807        }
1808        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1809
1810        String separateProcesses = SystemProperties.get("debug.separate_processes");
1811        if (separateProcesses != null && separateProcesses.length() > 0) {
1812            if ("*".equals(separateProcesses)) {
1813                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1814                mSeparateProcesses = null;
1815                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1816            } else {
1817                mDefParseFlags = 0;
1818                mSeparateProcesses = separateProcesses.split(",");
1819                Slog.w(TAG, "Running with debug.separate_processes: "
1820                        + separateProcesses);
1821            }
1822        } else {
1823            mDefParseFlags = 0;
1824            mSeparateProcesses = null;
1825        }
1826
1827        mInstaller = installer;
1828        mPackageDexOptimizer = new PackageDexOptimizer(this);
1829        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1830
1831        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1832                FgThread.get().getLooper());
1833
1834        getDefaultDisplayMetrics(context, mMetrics);
1835
1836        SystemConfig systemConfig = SystemConfig.getInstance();
1837        mGlobalGids = systemConfig.getGlobalGids();
1838        mSystemPermissions = systemConfig.getSystemPermissions();
1839        mAvailableFeatures = systemConfig.getAvailableFeatures();
1840
1841        synchronized (mInstallLock) {
1842        // writer
1843        synchronized (mPackages) {
1844            mHandlerThread = new ServiceThread(TAG,
1845                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1846            mHandlerThread.start();
1847            mHandler = new PackageHandler(mHandlerThread.getLooper());
1848            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1849
1850            File dataDir = Environment.getDataDirectory();
1851            mAppDataDir = new File(dataDir, "data");
1852            mAppInstallDir = new File(dataDir, "app");
1853            mAppLib32InstallDir = new File(dataDir, "app-lib");
1854            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1855            mUserAppDataDir = new File(dataDir, "user");
1856            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1857
1858            sUserManager = new UserManagerService(context, this,
1859                    mInstallLock, mPackages);
1860
1861            // Propagate permission configuration in to package manager.
1862            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1863                    = systemConfig.getPermissions();
1864            for (int i=0; i<permConfig.size(); i++) {
1865                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1866                BasePermission bp = mSettings.mPermissions.get(perm.name);
1867                if (bp == null) {
1868                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1869                    mSettings.mPermissions.put(perm.name, bp);
1870                }
1871                if (perm.gids != null) {
1872                    bp.setGids(perm.gids, perm.perUser);
1873                }
1874            }
1875
1876            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1877            for (int i=0; i<libConfig.size(); i++) {
1878                mSharedLibraries.put(libConfig.keyAt(i),
1879                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1880            }
1881
1882            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1883
1884            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1885                    mSdkVersion, mOnlyCore);
1886
1887            String customResolverActivity = Resources.getSystem().getString(
1888                    R.string.config_customResolverActivity);
1889            if (TextUtils.isEmpty(customResolverActivity)) {
1890                customResolverActivity = null;
1891            } else {
1892                mCustomResolverComponentName = ComponentName.unflattenFromString(
1893                        customResolverActivity);
1894            }
1895
1896            long startTime = SystemClock.uptimeMillis();
1897
1898            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1899                    startTime);
1900
1901            // Set flag to monitor and not change apk file paths when
1902            // scanning install directories.
1903            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1904
1905            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1906
1907            /**
1908             * Add everything in the in the boot class path to the
1909             * list of process files because dexopt will have been run
1910             * if necessary during zygote startup.
1911             */
1912            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1913            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1914
1915            if (bootClassPath != null) {
1916                String[] bootClassPathElements = splitString(bootClassPath, ':');
1917                for (String element : bootClassPathElements) {
1918                    alreadyDexOpted.add(element);
1919                }
1920            } else {
1921                Slog.w(TAG, "No BOOTCLASSPATH found!");
1922            }
1923
1924            if (systemServerClassPath != null) {
1925                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1926                for (String element : systemServerClassPathElements) {
1927                    alreadyDexOpted.add(element);
1928                }
1929            } else {
1930                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1931            }
1932
1933            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1934            final String[] dexCodeInstructionSets =
1935                    getDexCodeInstructionSets(
1936                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1937
1938            /**
1939             * Ensure all external libraries have had dexopt run on them.
1940             */
1941            if (mSharedLibraries.size() > 0) {
1942                // NOTE: For now, we're compiling these system "shared libraries"
1943                // (and framework jars) into all available architectures. It's possible
1944                // to compile them only when we come across an app that uses them (there's
1945                // already logic for that in scanPackageLI) but that adds some complexity.
1946                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1947                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1948                        final String lib = libEntry.path;
1949                        if (lib == null) {
1950                            continue;
1951                        }
1952
1953                        try {
1954                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1955                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1956                                alreadyDexOpted.add(lib);
1957                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1958                            }
1959                        } catch (FileNotFoundException e) {
1960                            Slog.w(TAG, "Library not found: " + lib);
1961                        } catch (IOException e) {
1962                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1963                                    + e.getMessage());
1964                        }
1965                    }
1966                }
1967            }
1968
1969            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1970
1971            // Gross hack for now: we know this file doesn't contain any
1972            // code, so don't dexopt it to avoid the resulting log spew.
1973            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1974
1975            // Gross hack for now: we know this file is only part of
1976            // the boot class path for art, so don't dexopt it to
1977            // avoid the resulting log spew.
1978            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1979
1980            /**
1981             * There are a number of commands implemented in Java, which
1982             * we currently need to do the dexopt on so that they can be
1983             * run from a non-root shell.
1984             */
1985            String[] frameworkFiles = frameworkDir.list();
1986            if (frameworkFiles != null) {
1987                // TODO: We could compile these only for the most preferred ABI. We should
1988                // first double check that the dex files for these commands are not referenced
1989                // by other system apps.
1990                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1991                    for (int i=0; i<frameworkFiles.length; i++) {
1992                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1993                        String path = libPath.getPath();
1994                        // Skip the file if we already did it.
1995                        if (alreadyDexOpted.contains(path)) {
1996                            continue;
1997                        }
1998                        // Skip the file if it is not a type we want to dexopt.
1999                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2000                            continue;
2001                        }
2002                        try {
2003                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2004                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2005                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
2006                            }
2007                        } catch (FileNotFoundException e) {
2008                            Slog.w(TAG, "Jar not found: " + path);
2009                        } catch (IOException e) {
2010                            Slog.w(TAG, "Exception reading jar: " + path, e);
2011                        }
2012                    }
2013                }
2014            }
2015
2016            // Collect vendor overlay packages.
2017            // (Do this before scanning any apps.)
2018            // For security and version matching reason, only consider
2019            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2020            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2021            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2022                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2023
2024            // Find base frameworks (resource packages without code).
2025            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2026                    | PackageParser.PARSE_IS_SYSTEM_DIR
2027                    | PackageParser.PARSE_IS_PRIVILEGED,
2028                    scanFlags | SCAN_NO_DEX, 0);
2029
2030            // Collected privileged system packages.
2031            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2032            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2033                    | PackageParser.PARSE_IS_SYSTEM_DIR
2034                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2035
2036            // Collect ordinary system packages.
2037            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2038            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2039                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2040
2041            // Collect all vendor packages.
2042            File vendorAppDir = new File("/vendor/app");
2043            try {
2044                vendorAppDir = vendorAppDir.getCanonicalFile();
2045            } catch (IOException e) {
2046                // failed to look up canonical path, continue with original one
2047            }
2048            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2049                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2050
2051            // Collect all OEM packages.
2052            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2053            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2054                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2055
2056            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2057            mInstaller.moveFiles();
2058
2059            // Prune any system packages that no longer exist.
2060            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2061            if (!mOnlyCore) {
2062                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2063                while (psit.hasNext()) {
2064                    PackageSetting ps = psit.next();
2065
2066                    /*
2067                     * If this is not a system app, it can't be a
2068                     * disable system app.
2069                     */
2070                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2071                        continue;
2072                    }
2073
2074                    /*
2075                     * If the package is scanned, it's not erased.
2076                     */
2077                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2078                    if (scannedPkg != null) {
2079                        /*
2080                         * If the system app is both scanned and in the
2081                         * disabled packages list, then it must have been
2082                         * added via OTA. Remove it from the currently
2083                         * scanned package so the previously user-installed
2084                         * application can be scanned.
2085                         */
2086                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2087                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2088                                    + ps.name + "; removing system app.  Last known codePath="
2089                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2090                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2091                                    + scannedPkg.mVersionCode);
2092                            removePackageLI(ps, true);
2093                            mExpectingBetter.put(ps.name, ps.codePath);
2094                        }
2095
2096                        continue;
2097                    }
2098
2099                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2100                        psit.remove();
2101                        logCriticalInfo(Log.WARN, "System package " + ps.name
2102                                + " no longer exists; wiping its data");
2103                        removeDataDirsLI(null, ps.name);
2104                    } else {
2105                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2106                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2107                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2108                        }
2109                    }
2110                }
2111            }
2112
2113            //look for any incomplete package installations
2114            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2115            //clean up list
2116            for(int i = 0; i < deletePkgsList.size(); i++) {
2117                //clean up here
2118                cleanupInstallFailedPackage(deletePkgsList.get(i));
2119            }
2120            //delete tmp files
2121            deleteTempPackageFiles();
2122
2123            // Remove any shared userIDs that have no associated packages
2124            mSettings.pruneSharedUsersLPw();
2125
2126            if (!mOnlyCore) {
2127                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2128                        SystemClock.uptimeMillis());
2129                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2130
2131                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2132                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2133
2134                /**
2135                 * Remove disable package settings for any updated system
2136                 * apps that were removed via an OTA. If they're not a
2137                 * previously-updated app, remove them completely.
2138                 * Otherwise, just revoke their system-level permissions.
2139                 */
2140                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2141                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2142                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2143
2144                    String msg;
2145                    if (deletedPkg == null) {
2146                        msg = "Updated system package " + deletedAppName
2147                                + " no longer exists; wiping its data";
2148                        removeDataDirsLI(null, deletedAppName);
2149                    } else {
2150                        msg = "Updated system app + " + deletedAppName
2151                                + " no longer present; removing system privileges for "
2152                                + deletedAppName;
2153
2154                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2155
2156                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2157                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2158                    }
2159                    logCriticalInfo(Log.WARN, msg);
2160                }
2161
2162                /**
2163                 * Make sure all system apps that we expected to appear on
2164                 * the userdata partition actually showed up. If they never
2165                 * appeared, crawl back and revive the system version.
2166                 */
2167                for (int i = 0; i < mExpectingBetter.size(); i++) {
2168                    final String packageName = mExpectingBetter.keyAt(i);
2169                    if (!mPackages.containsKey(packageName)) {
2170                        final File scanFile = mExpectingBetter.valueAt(i);
2171
2172                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2173                                + " but never showed up; reverting to system");
2174
2175                        final int reparseFlags;
2176                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2177                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2178                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2179                                    | PackageParser.PARSE_IS_PRIVILEGED;
2180                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2181                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2182                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2183                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2184                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2185                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2186                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2187                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2188                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2189                        } else {
2190                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2191                            continue;
2192                        }
2193
2194                        mSettings.enableSystemPackageLPw(packageName);
2195
2196                        try {
2197                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2198                        } catch (PackageManagerException e) {
2199                            Slog.e(TAG, "Failed to parse original system package: "
2200                                    + e.getMessage());
2201                        }
2202                    }
2203                }
2204            }
2205            mExpectingBetter.clear();
2206
2207            // Now that we know all of the shared libraries, update all clients to have
2208            // the correct library paths.
2209            updateAllSharedLibrariesLPw();
2210
2211            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2212                // NOTE: We ignore potential failures here during a system scan (like
2213                // the rest of the commands above) because there's precious little we
2214                // can do about it. A settings error is reported, though.
2215                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2216                        false /* force dexopt */, false /* defer dexopt */);
2217            }
2218
2219            // Now that we know all the packages we are keeping,
2220            // read and update their last usage times.
2221            mPackageUsage.readLP();
2222
2223            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2224                    SystemClock.uptimeMillis());
2225            Slog.i(TAG, "Time to scan packages: "
2226                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2227                    + " seconds");
2228
2229            // If the platform SDK has changed since the last time we booted,
2230            // we need to re-grant app permission to catch any new ones that
2231            // appear.  This is really a hack, and means that apps can in some
2232            // cases get permissions that the user didn't initially explicitly
2233            // allow...  it would be nice to have some better way to handle
2234            // this situation.
2235            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2236                    != mSdkVersion;
2237            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2238                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2239                    + "; regranting permissions for internal storage");
2240            mSettings.mInternalSdkPlatform = mSdkVersion;
2241
2242            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2243                    | (regrantPermissions
2244                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2245                            : 0));
2246
2247            // If this is the first boot, and it is a normal boot, then
2248            // we need to initialize the default preferred apps.
2249            if (!mRestoredSettings && !onlyCore) {
2250                mSettings.applyDefaultPreferredAppsLPw(this, UserHandle.USER_OWNER);
2251                applyFactoryDefaultBrowserLPw(UserHandle.USER_OWNER);
2252                primeDomainVerificationsLPw(UserHandle.USER_OWNER);
2253            }
2254
2255            // If this is first boot after an OTA, and a normal boot, then
2256            // we need to clear code cache directories.
2257            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2258            if (mIsUpgrade && !onlyCore) {
2259                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2260                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2261                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2262                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2263                }
2264                mSettings.mFingerprint = Build.FINGERPRINT;
2265            }
2266
2267            checkDefaultBrowser();
2268
2269            // All the changes are done during package scanning.
2270            mSettings.updateInternalDatabaseVersion();
2271
2272            // can downgrade to reader
2273            mSettings.writeLPr();
2274
2275            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2276                    SystemClock.uptimeMillis());
2277
2278            mRequiredVerifierPackage = getRequiredVerifierLPr();
2279            mRequiredInstallerPackage = getRequiredInstallerLPr();
2280
2281            mInstallerService = new PackageInstallerService(context, this);
2282
2283            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2284            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2285                    mIntentFilterVerifierComponent);
2286
2287        } // synchronized (mPackages)
2288        } // synchronized (mInstallLock)
2289
2290        // Now after opening every single application zip, make sure they
2291        // are all flushed.  Not really needed, but keeps things nice and
2292        // tidy.
2293        Runtime.getRuntime().gc();
2294
2295        // Expose private service for system components to use.
2296        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2297    }
2298
2299    @Override
2300    public boolean isFirstBoot() {
2301        return !mRestoredSettings;
2302    }
2303
2304    @Override
2305    public boolean isOnlyCoreApps() {
2306        return mOnlyCore;
2307    }
2308
2309    @Override
2310    public boolean isUpgrade() {
2311        return mIsUpgrade;
2312    }
2313
2314    private String getRequiredVerifierLPr() {
2315        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2316        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2317                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2318
2319        String requiredVerifier = null;
2320
2321        final int N = receivers.size();
2322        for (int i = 0; i < N; i++) {
2323            final ResolveInfo info = receivers.get(i);
2324
2325            if (info.activityInfo == null) {
2326                continue;
2327            }
2328
2329            final String packageName = info.activityInfo.packageName;
2330
2331            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2332                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2333                continue;
2334            }
2335
2336            if (requiredVerifier != null) {
2337                throw new RuntimeException("There can be only one required verifier");
2338            }
2339
2340            requiredVerifier = packageName;
2341        }
2342
2343        return requiredVerifier;
2344    }
2345
2346    private String getRequiredInstallerLPr() {
2347        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2348        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2349        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2350
2351        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2352                PACKAGE_MIME_TYPE, 0, 0);
2353
2354        String requiredInstaller = null;
2355
2356        final int N = installers.size();
2357        for (int i = 0; i < N; i++) {
2358            final ResolveInfo info = installers.get(i);
2359            final String packageName = info.activityInfo.packageName;
2360
2361            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2362                continue;
2363            }
2364
2365            if (requiredInstaller != null) {
2366                throw new RuntimeException("There must be one required installer");
2367            }
2368
2369            requiredInstaller = packageName;
2370        }
2371
2372        if (requiredInstaller == null) {
2373            throw new RuntimeException("There must be one required installer");
2374        }
2375
2376        return requiredInstaller;
2377    }
2378
2379    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2380        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2381        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2382                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2383
2384        ComponentName verifierComponentName = null;
2385
2386        int priority = -1000;
2387        final int N = receivers.size();
2388        for (int i = 0; i < N; i++) {
2389            final ResolveInfo info = receivers.get(i);
2390
2391            if (info.activityInfo == null) {
2392                continue;
2393            }
2394
2395            final String packageName = info.activityInfo.packageName;
2396
2397            final PackageSetting ps = mSettings.mPackages.get(packageName);
2398            if (ps == null) {
2399                continue;
2400            }
2401
2402            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2403                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2404                continue;
2405            }
2406
2407            // Select the IntentFilterVerifier with the highest priority
2408            if (priority < info.priority) {
2409                priority = info.priority;
2410                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2411                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2412                        + verifierComponentName + " with priority: " + info.priority);
2413            }
2414        }
2415
2416        return verifierComponentName;
2417    }
2418
2419    private void primeDomainVerificationsLPw(int userId) {
2420        if (DEBUG_DOMAIN_VERIFICATION) {
2421            Slog.d(TAG, "Priming domain verifications in user " + userId);
2422        }
2423
2424        SystemConfig systemConfig = SystemConfig.getInstance();
2425        ArraySet<String> packages = systemConfig.getLinkedApps();
2426        ArraySet<String> domains = new ArraySet<String>();
2427
2428        for (String packageName : packages) {
2429            PackageParser.Package pkg = mPackages.get(packageName);
2430            if (pkg != null) {
2431                if (!pkg.isSystemApp()) {
2432                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2433                    continue;
2434                }
2435
2436                domains.clear();
2437                for (PackageParser.Activity a : pkg.activities) {
2438                    for (ActivityIntentInfo filter : a.intents) {
2439                        if (hasValidDomains(filter)) {
2440                            domains.addAll(filter.getHostsList());
2441                        }
2442                    }
2443                }
2444
2445                if (domains.size() > 0) {
2446                    if (DEBUG_DOMAIN_VERIFICATION) {
2447                        Slog.v(TAG, "      + " + packageName);
2448                    }
2449                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2450                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2451                    // and then 'always' in the per-user state actually used for intent resolution.
2452                    final IntentFilterVerificationInfo ivi;
2453                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2454                            new ArrayList<String>(domains));
2455                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2456                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2457                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2458                } else {
2459                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2460                            + "' does not handle web links");
2461                }
2462            } else {
2463                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2464            }
2465        }
2466
2467        scheduleWritePackageRestrictionsLocked(userId);
2468        scheduleWriteSettingsLocked();
2469    }
2470
2471    private void applyFactoryDefaultBrowserLPw(int userId) {
2472        // The default browser app's package name is stored in a string resource,
2473        // with a product-specific overlay used for vendor customization.
2474        String browserPkg = mContext.getResources().getString(
2475                com.android.internal.R.string.default_browser);
2476        if (!TextUtils.isEmpty(browserPkg)) {
2477            // non-empty string => required to be a known package
2478            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2479            if (ps == null) {
2480                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2481                browserPkg = null;
2482            } else {
2483                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2484            }
2485        }
2486
2487        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2488        // default.  If there's more than one, just leave everything alone.
2489        if (browserPkg == null) {
2490            calculateDefaultBrowserLPw(userId);
2491        }
2492    }
2493
2494    private void calculateDefaultBrowserLPw(int userId) {
2495        List<String> allBrowsers = resolveAllBrowserApps(userId);
2496        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2497        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2498    }
2499
2500    private List<String> resolveAllBrowserApps(int userId) {
2501        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2502        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2503                PackageManager.MATCH_ALL, userId);
2504
2505        final int count = list.size();
2506        List<String> result = new ArrayList<String>(count);
2507        for (int i=0; i<count; i++) {
2508            ResolveInfo info = list.get(i);
2509            if (info.activityInfo == null
2510                    || !info.handleAllWebDataURI
2511                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2512                    || result.contains(info.activityInfo.packageName)) {
2513                continue;
2514            }
2515            result.add(info.activityInfo.packageName);
2516        }
2517
2518        return result;
2519    }
2520
2521    private boolean packageIsBrowser(String packageName, int userId) {
2522        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2523                PackageManager.MATCH_ALL, userId);
2524        final int N = list.size();
2525        for (int i = 0; i < N; i++) {
2526            ResolveInfo info = list.get(i);
2527            if (packageName.equals(info.activityInfo.packageName)) {
2528                return true;
2529            }
2530        }
2531        return false;
2532    }
2533
2534    private void checkDefaultBrowser() {
2535        final int myUserId = UserHandle.myUserId();
2536        final String packageName = getDefaultBrowserPackageName(myUserId);
2537        if (packageName != null) {
2538            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2539            if (info == null) {
2540                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2541                synchronized (mPackages) {
2542                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2543                }
2544            }
2545        }
2546    }
2547
2548    @Override
2549    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2550            throws RemoteException {
2551        try {
2552            return super.onTransact(code, data, reply, flags);
2553        } catch (RuntimeException e) {
2554            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2555                Slog.wtf(TAG, "Package Manager Crash", e);
2556            }
2557            throw e;
2558        }
2559    }
2560
2561    void cleanupInstallFailedPackage(PackageSetting ps) {
2562        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2563
2564        removeDataDirsLI(ps.volumeUuid, ps.name);
2565        if (ps.codePath != null) {
2566            if (ps.codePath.isDirectory()) {
2567                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2568            } else {
2569                ps.codePath.delete();
2570            }
2571        }
2572        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2573            if (ps.resourcePath.isDirectory()) {
2574                FileUtils.deleteContents(ps.resourcePath);
2575            }
2576            ps.resourcePath.delete();
2577        }
2578        mSettings.removePackageLPw(ps.name);
2579    }
2580
2581    static int[] appendInts(int[] cur, int[] add) {
2582        if (add == null) return cur;
2583        if (cur == null) return add;
2584        final int N = add.length;
2585        for (int i=0; i<N; i++) {
2586            cur = appendInt(cur, add[i]);
2587        }
2588        return cur;
2589    }
2590
2591    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2592        if (!sUserManager.exists(userId)) return null;
2593        final PackageSetting ps = (PackageSetting) p.mExtras;
2594        if (ps == null) {
2595            return null;
2596        }
2597
2598        final PermissionsState permissionsState = ps.getPermissionsState();
2599
2600        final int[] gids = permissionsState.computeGids(userId);
2601        final Set<String> permissions = permissionsState.getPermissions(userId);
2602        final PackageUserState state = ps.readUserState(userId);
2603
2604        return PackageParser.generatePackageInfo(p, gids, flags,
2605                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2606    }
2607
2608    @Override
2609    public boolean isPackageFrozen(String packageName) {
2610        synchronized (mPackages) {
2611            final PackageSetting ps = mSettings.mPackages.get(packageName);
2612            if (ps != null) {
2613                return ps.frozen;
2614            }
2615        }
2616        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2617        return true;
2618    }
2619
2620    @Override
2621    public boolean isPackageAvailable(String packageName, int userId) {
2622        if (!sUserManager.exists(userId)) return false;
2623        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2624        synchronized (mPackages) {
2625            PackageParser.Package p = mPackages.get(packageName);
2626            if (p != null) {
2627                final PackageSetting ps = (PackageSetting) p.mExtras;
2628                if (ps != null) {
2629                    final PackageUserState state = ps.readUserState(userId);
2630                    if (state != null) {
2631                        return PackageParser.isAvailable(state);
2632                    }
2633                }
2634            }
2635        }
2636        return false;
2637    }
2638
2639    @Override
2640    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2641        if (!sUserManager.exists(userId)) return null;
2642        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2643        // reader
2644        synchronized (mPackages) {
2645            PackageParser.Package p = mPackages.get(packageName);
2646            if (DEBUG_PACKAGE_INFO)
2647                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2648            if (p != null) {
2649                return generatePackageInfo(p, flags, userId);
2650            }
2651            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2652                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2653            }
2654        }
2655        return null;
2656    }
2657
2658    @Override
2659    public String[] currentToCanonicalPackageNames(String[] names) {
2660        String[] out = new String[names.length];
2661        // reader
2662        synchronized (mPackages) {
2663            for (int i=names.length-1; i>=0; i--) {
2664                PackageSetting ps = mSettings.mPackages.get(names[i]);
2665                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2666            }
2667        }
2668        return out;
2669    }
2670
2671    @Override
2672    public String[] canonicalToCurrentPackageNames(String[] names) {
2673        String[] out = new String[names.length];
2674        // reader
2675        synchronized (mPackages) {
2676            for (int i=names.length-1; i>=0; i--) {
2677                String cur = mSettings.mRenamedPackages.get(names[i]);
2678                out[i] = cur != null ? cur : names[i];
2679            }
2680        }
2681        return out;
2682    }
2683
2684    @Override
2685    public int getPackageUid(String packageName, int userId) {
2686        if (!sUserManager.exists(userId)) return -1;
2687        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2688
2689        // reader
2690        synchronized (mPackages) {
2691            PackageParser.Package p = mPackages.get(packageName);
2692            if(p != null) {
2693                return UserHandle.getUid(userId, p.applicationInfo.uid);
2694            }
2695            PackageSetting ps = mSettings.mPackages.get(packageName);
2696            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2697                return -1;
2698            }
2699            p = ps.pkg;
2700            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2701        }
2702    }
2703
2704    @Override
2705    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2706        if (!sUserManager.exists(userId)) {
2707            return null;
2708        }
2709
2710        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2711                "getPackageGids");
2712
2713        // reader
2714        synchronized (mPackages) {
2715            PackageParser.Package p = mPackages.get(packageName);
2716            if (DEBUG_PACKAGE_INFO) {
2717                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2718            }
2719            if (p != null) {
2720                PackageSetting ps = (PackageSetting) p.mExtras;
2721                return ps.getPermissionsState().computeGids(userId);
2722            }
2723        }
2724
2725        return null;
2726    }
2727
2728    @Override
2729    public int getMountExternalMode(int uid) {
2730        if (Process.isIsolated(uid)) {
2731            return Zygote.MOUNT_EXTERNAL_NONE;
2732        } else {
2733            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
2734                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2735            } else if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2736                return Zygote.MOUNT_EXTERNAL_WRITE;
2737            } else if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_GRANTED) {
2738                return Zygote.MOUNT_EXTERNAL_READ;
2739            } else {
2740                return Zygote.MOUNT_EXTERNAL_DEFAULT;
2741            }
2742        }
2743    }
2744
2745    static PermissionInfo generatePermissionInfo(
2746            BasePermission bp, int flags) {
2747        if (bp.perm != null) {
2748            return PackageParser.generatePermissionInfo(bp.perm, flags);
2749        }
2750        PermissionInfo pi = new PermissionInfo();
2751        pi.name = bp.name;
2752        pi.packageName = bp.sourcePackage;
2753        pi.nonLocalizedLabel = bp.name;
2754        pi.protectionLevel = bp.protectionLevel;
2755        return pi;
2756    }
2757
2758    @Override
2759    public PermissionInfo getPermissionInfo(String name, int flags) {
2760        // reader
2761        synchronized (mPackages) {
2762            final BasePermission p = mSettings.mPermissions.get(name);
2763            if (p != null) {
2764                return generatePermissionInfo(p, flags);
2765            }
2766            return null;
2767        }
2768    }
2769
2770    @Override
2771    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2772        // reader
2773        synchronized (mPackages) {
2774            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2775            for (BasePermission p : mSettings.mPermissions.values()) {
2776                if (group == null) {
2777                    if (p.perm == null || p.perm.info.group == null) {
2778                        out.add(generatePermissionInfo(p, flags));
2779                    }
2780                } else {
2781                    if (p.perm != null && group.equals(p.perm.info.group)) {
2782                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2783                    }
2784                }
2785            }
2786
2787            if (out.size() > 0) {
2788                return out;
2789            }
2790            return mPermissionGroups.containsKey(group) ? out : null;
2791        }
2792    }
2793
2794    @Override
2795    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2796        // reader
2797        synchronized (mPackages) {
2798            return PackageParser.generatePermissionGroupInfo(
2799                    mPermissionGroups.get(name), flags);
2800        }
2801    }
2802
2803    @Override
2804    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2805        // reader
2806        synchronized (mPackages) {
2807            final int N = mPermissionGroups.size();
2808            ArrayList<PermissionGroupInfo> out
2809                    = new ArrayList<PermissionGroupInfo>(N);
2810            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2811                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2812            }
2813            return out;
2814        }
2815    }
2816
2817    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2818            int userId) {
2819        if (!sUserManager.exists(userId)) return null;
2820        PackageSetting ps = mSettings.mPackages.get(packageName);
2821        if (ps != null) {
2822            if (ps.pkg == null) {
2823                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2824                        flags, userId);
2825                if (pInfo != null) {
2826                    return pInfo.applicationInfo;
2827                }
2828                return null;
2829            }
2830            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2831                    ps.readUserState(userId), userId);
2832        }
2833        return null;
2834    }
2835
2836    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2837            int userId) {
2838        if (!sUserManager.exists(userId)) return null;
2839        PackageSetting ps = mSettings.mPackages.get(packageName);
2840        if (ps != null) {
2841            PackageParser.Package pkg = ps.pkg;
2842            if (pkg == null) {
2843                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2844                    return null;
2845                }
2846                // Only data remains, so we aren't worried about code paths
2847                pkg = new PackageParser.Package(packageName);
2848                pkg.applicationInfo.packageName = packageName;
2849                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2850                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2851                pkg.applicationInfo.dataDir = Environment
2852                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2853                        .getAbsolutePath();
2854                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2855                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2856            }
2857            return generatePackageInfo(pkg, flags, userId);
2858        }
2859        return null;
2860    }
2861
2862    @Override
2863    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2864        if (!sUserManager.exists(userId)) return null;
2865        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2866        // writer
2867        synchronized (mPackages) {
2868            PackageParser.Package p = mPackages.get(packageName);
2869            if (DEBUG_PACKAGE_INFO) Log.v(
2870                    TAG, "getApplicationInfo " + packageName
2871                    + ": " + p);
2872            if (p != null) {
2873                PackageSetting ps = mSettings.mPackages.get(packageName);
2874                if (ps == null) return null;
2875                // Note: isEnabledLP() does not apply here - always return info
2876                return PackageParser.generateApplicationInfo(
2877                        p, flags, ps.readUserState(userId), userId);
2878            }
2879            if ("android".equals(packageName)||"system".equals(packageName)) {
2880                return mAndroidApplication;
2881            }
2882            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2883                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2884            }
2885        }
2886        return null;
2887    }
2888
2889    @Override
2890    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2891            final IPackageDataObserver observer) {
2892        mContext.enforceCallingOrSelfPermission(
2893                android.Manifest.permission.CLEAR_APP_CACHE, null);
2894        // Queue up an async operation since clearing cache may take a little while.
2895        mHandler.post(new Runnable() {
2896            public void run() {
2897                mHandler.removeCallbacks(this);
2898                int retCode = -1;
2899                synchronized (mInstallLock) {
2900                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2901                    if (retCode < 0) {
2902                        Slog.w(TAG, "Couldn't clear application caches");
2903                    }
2904                }
2905                if (observer != null) {
2906                    try {
2907                        observer.onRemoveCompleted(null, (retCode >= 0));
2908                    } catch (RemoteException e) {
2909                        Slog.w(TAG, "RemoveException when invoking call back");
2910                    }
2911                }
2912            }
2913        });
2914    }
2915
2916    @Override
2917    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2918            final IntentSender pi) {
2919        mContext.enforceCallingOrSelfPermission(
2920                android.Manifest.permission.CLEAR_APP_CACHE, null);
2921        // Queue up an async operation since clearing cache may take a little while.
2922        mHandler.post(new Runnable() {
2923            public void run() {
2924                mHandler.removeCallbacks(this);
2925                int retCode = -1;
2926                synchronized (mInstallLock) {
2927                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2928                    if (retCode < 0) {
2929                        Slog.w(TAG, "Couldn't clear application caches");
2930                    }
2931                }
2932                if(pi != null) {
2933                    try {
2934                        // Callback via pending intent
2935                        int code = (retCode >= 0) ? 1 : 0;
2936                        pi.sendIntent(null, code, null,
2937                                null, null);
2938                    } catch (SendIntentException e1) {
2939                        Slog.i(TAG, "Failed to send pending intent");
2940                    }
2941                }
2942            }
2943        });
2944    }
2945
2946    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2947        synchronized (mInstallLock) {
2948            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2949                throw new IOException("Failed to free enough space");
2950            }
2951        }
2952    }
2953
2954    @Override
2955    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2956        if (!sUserManager.exists(userId)) return null;
2957        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2958        synchronized (mPackages) {
2959            PackageParser.Activity a = mActivities.mActivities.get(component);
2960
2961            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2962            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2963                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2964                if (ps == null) return null;
2965                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2966                        userId);
2967            }
2968            if (mResolveComponentName.equals(component)) {
2969                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2970                        new PackageUserState(), userId);
2971            }
2972        }
2973        return null;
2974    }
2975
2976    @Override
2977    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2978            String resolvedType) {
2979        synchronized (mPackages) {
2980            PackageParser.Activity a = mActivities.mActivities.get(component);
2981            if (a == null) {
2982                return false;
2983            }
2984            for (int i=0; i<a.intents.size(); i++) {
2985                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2986                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2987                    return true;
2988                }
2989            }
2990            return false;
2991        }
2992    }
2993
2994    @Override
2995    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2996        if (!sUserManager.exists(userId)) return null;
2997        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2998        synchronized (mPackages) {
2999            PackageParser.Activity a = mReceivers.mActivities.get(component);
3000            if (DEBUG_PACKAGE_INFO) Log.v(
3001                TAG, "getReceiverInfo " + component + ": " + a);
3002            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3003                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3004                if (ps == null) return null;
3005                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3006                        userId);
3007            }
3008        }
3009        return null;
3010    }
3011
3012    @Override
3013    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3014        if (!sUserManager.exists(userId)) return null;
3015        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3016        synchronized (mPackages) {
3017            PackageParser.Service s = mServices.mServices.get(component);
3018            if (DEBUG_PACKAGE_INFO) Log.v(
3019                TAG, "getServiceInfo " + component + ": " + s);
3020            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3021                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3022                if (ps == null) return null;
3023                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3024                        userId);
3025            }
3026        }
3027        return null;
3028    }
3029
3030    @Override
3031    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3032        if (!sUserManager.exists(userId)) return null;
3033        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3034        synchronized (mPackages) {
3035            PackageParser.Provider p = mProviders.mProviders.get(component);
3036            if (DEBUG_PACKAGE_INFO) Log.v(
3037                TAG, "getProviderInfo " + component + ": " + p);
3038            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3039                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3040                if (ps == null) return null;
3041                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3042                        userId);
3043            }
3044        }
3045        return null;
3046    }
3047
3048    @Override
3049    public String[] getSystemSharedLibraryNames() {
3050        Set<String> libSet;
3051        synchronized (mPackages) {
3052            libSet = mSharedLibraries.keySet();
3053            int size = libSet.size();
3054            if (size > 0) {
3055                String[] libs = new String[size];
3056                libSet.toArray(libs);
3057                return libs;
3058            }
3059        }
3060        return null;
3061    }
3062
3063    /**
3064     * @hide
3065     */
3066    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3067        synchronized (mPackages) {
3068            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3069            if (lib != null && lib.apk != null) {
3070                return mPackages.get(lib.apk);
3071            }
3072        }
3073        return null;
3074    }
3075
3076    @Override
3077    public FeatureInfo[] getSystemAvailableFeatures() {
3078        Collection<FeatureInfo> featSet;
3079        synchronized (mPackages) {
3080            featSet = mAvailableFeatures.values();
3081            int size = featSet.size();
3082            if (size > 0) {
3083                FeatureInfo[] features = new FeatureInfo[size+1];
3084                featSet.toArray(features);
3085                FeatureInfo fi = new FeatureInfo();
3086                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3087                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3088                features[size] = fi;
3089                return features;
3090            }
3091        }
3092        return null;
3093    }
3094
3095    @Override
3096    public boolean hasSystemFeature(String name) {
3097        synchronized (mPackages) {
3098            return mAvailableFeatures.containsKey(name);
3099        }
3100    }
3101
3102    private void checkValidCaller(int uid, int userId) {
3103        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3104            return;
3105
3106        throw new SecurityException("Caller uid=" + uid
3107                + " is not privileged to communicate with user=" + userId);
3108    }
3109
3110    @Override
3111    public int checkPermission(String permName, String pkgName, int userId) {
3112        if (!sUserManager.exists(userId)) {
3113            return PackageManager.PERMISSION_DENIED;
3114        }
3115
3116        synchronized (mPackages) {
3117            final PackageParser.Package p = mPackages.get(pkgName);
3118            if (p != null && p.mExtras != null) {
3119                final PackageSetting ps = (PackageSetting) p.mExtras;
3120                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3121                    return PackageManager.PERMISSION_GRANTED;
3122                }
3123            }
3124        }
3125
3126        return PackageManager.PERMISSION_DENIED;
3127    }
3128
3129    @Override
3130    public int checkUidPermission(String permName, int uid) {
3131        final int userId = UserHandle.getUserId(uid);
3132
3133        if (!sUserManager.exists(userId)) {
3134            return PackageManager.PERMISSION_DENIED;
3135        }
3136
3137        synchronized (mPackages) {
3138            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3139            if (obj != null) {
3140                final SettingBase ps = (SettingBase) obj;
3141                if (ps.getPermissionsState().hasPermission(permName, userId)) {
3142                    return PackageManager.PERMISSION_GRANTED;
3143                }
3144            } else {
3145                ArraySet<String> perms = mSystemPermissions.get(uid);
3146                if (perms != null && perms.contains(permName)) {
3147                    return PackageManager.PERMISSION_GRANTED;
3148                }
3149            }
3150        }
3151
3152        return PackageManager.PERMISSION_DENIED;
3153    }
3154
3155    @Override
3156    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3157        if (UserHandle.getCallingUserId() != userId) {
3158            mContext.enforceCallingPermission(
3159                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3160                    "isPermissionRevokedByPolicy for user " + userId);
3161        }
3162
3163        if (checkPermission(permission, packageName, userId)
3164                == PackageManager.PERMISSION_GRANTED) {
3165            return false;
3166        }
3167
3168        final long identity = Binder.clearCallingIdentity();
3169        try {
3170            final int flags = getPermissionFlags(permission, packageName, userId);
3171            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3172        } finally {
3173            Binder.restoreCallingIdentity(identity);
3174        }
3175    }
3176
3177    /**
3178     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3179     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3180     * @param checkShell TODO(yamasani):
3181     * @param message the message to log on security exception
3182     */
3183    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3184            boolean checkShell, String message) {
3185        if (userId < 0) {
3186            throw new IllegalArgumentException("Invalid userId " + userId);
3187        }
3188        if (checkShell) {
3189            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3190        }
3191        if (userId == UserHandle.getUserId(callingUid)) return;
3192        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3193            if (requireFullPermission) {
3194                mContext.enforceCallingOrSelfPermission(
3195                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3196            } else {
3197                try {
3198                    mContext.enforceCallingOrSelfPermission(
3199                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3200                } catch (SecurityException se) {
3201                    mContext.enforceCallingOrSelfPermission(
3202                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3203                }
3204            }
3205        }
3206    }
3207
3208    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3209        if (callingUid == Process.SHELL_UID) {
3210            if (userHandle >= 0
3211                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3212                throw new SecurityException("Shell does not have permission to access user "
3213                        + userHandle);
3214            } else if (userHandle < 0) {
3215                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3216                        + Debug.getCallers(3));
3217            }
3218        }
3219    }
3220
3221    private BasePermission findPermissionTreeLP(String permName) {
3222        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3223            if (permName.startsWith(bp.name) &&
3224                    permName.length() > bp.name.length() &&
3225                    permName.charAt(bp.name.length()) == '.') {
3226                return bp;
3227            }
3228        }
3229        return null;
3230    }
3231
3232    private BasePermission checkPermissionTreeLP(String permName) {
3233        if (permName != null) {
3234            BasePermission bp = findPermissionTreeLP(permName);
3235            if (bp != null) {
3236                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3237                    return bp;
3238                }
3239                throw new SecurityException("Calling uid "
3240                        + Binder.getCallingUid()
3241                        + " is not allowed to add to permission tree "
3242                        + bp.name + " owned by uid " + bp.uid);
3243            }
3244        }
3245        throw new SecurityException("No permission tree found for " + permName);
3246    }
3247
3248    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3249        if (s1 == null) {
3250            return s2 == null;
3251        }
3252        if (s2 == null) {
3253            return false;
3254        }
3255        if (s1.getClass() != s2.getClass()) {
3256            return false;
3257        }
3258        return s1.equals(s2);
3259    }
3260
3261    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3262        if (pi1.icon != pi2.icon) return false;
3263        if (pi1.logo != pi2.logo) return false;
3264        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3265        if (!compareStrings(pi1.name, pi2.name)) return false;
3266        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3267        // We'll take care of setting this one.
3268        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3269        // These are not currently stored in settings.
3270        //if (!compareStrings(pi1.group, pi2.group)) return false;
3271        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3272        //if (pi1.labelRes != pi2.labelRes) return false;
3273        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3274        return true;
3275    }
3276
3277    int permissionInfoFootprint(PermissionInfo info) {
3278        int size = info.name.length();
3279        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3280        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3281        return size;
3282    }
3283
3284    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3285        int size = 0;
3286        for (BasePermission perm : mSettings.mPermissions.values()) {
3287            if (perm.uid == tree.uid) {
3288                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3289            }
3290        }
3291        return size;
3292    }
3293
3294    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3295        // We calculate the max size of permissions defined by this uid and throw
3296        // if that plus the size of 'info' would exceed our stated maximum.
3297        if (tree.uid != Process.SYSTEM_UID) {
3298            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3299            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3300                throw new SecurityException("Permission tree size cap exceeded");
3301            }
3302        }
3303    }
3304
3305    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3306        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3307            throw new SecurityException("Label must be specified in permission");
3308        }
3309        BasePermission tree = checkPermissionTreeLP(info.name);
3310        BasePermission bp = mSettings.mPermissions.get(info.name);
3311        boolean added = bp == null;
3312        boolean changed = true;
3313        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3314        if (added) {
3315            enforcePermissionCapLocked(info, tree);
3316            bp = new BasePermission(info.name, tree.sourcePackage,
3317                    BasePermission.TYPE_DYNAMIC);
3318        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3319            throw new SecurityException(
3320                    "Not allowed to modify non-dynamic permission "
3321                    + info.name);
3322        } else {
3323            if (bp.protectionLevel == fixedLevel
3324                    && bp.perm.owner.equals(tree.perm.owner)
3325                    && bp.uid == tree.uid
3326                    && comparePermissionInfos(bp.perm.info, info)) {
3327                changed = false;
3328            }
3329        }
3330        bp.protectionLevel = fixedLevel;
3331        info = new PermissionInfo(info);
3332        info.protectionLevel = fixedLevel;
3333        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3334        bp.perm.info.packageName = tree.perm.info.packageName;
3335        bp.uid = tree.uid;
3336        if (added) {
3337            mSettings.mPermissions.put(info.name, bp);
3338        }
3339        if (changed) {
3340            if (!async) {
3341                mSettings.writeLPr();
3342            } else {
3343                scheduleWriteSettingsLocked();
3344            }
3345        }
3346        return added;
3347    }
3348
3349    @Override
3350    public boolean addPermission(PermissionInfo info) {
3351        synchronized (mPackages) {
3352            return addPermissionLocked(info, false);
3353        }
3354    }
3355
3356    @Override
3357    public boolean addPermissionAsync(PermissionInfo info) {
3358        synchronized (mPackages) {
3359            return addPermissionLocked(info, true);
3360        }
3361    }
3362
3363    @Override
3364    public void removePermission(String name) {
3365        synchronized (mPackages) {
3366            checkPermissionTreeLP(name);
3367            BasePermission bp = mSettings.mPermissions.get(name);
3368            if (bp != null) {
3369                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3370                    throw new SecurityException(
3371                            "Not allowed to modify non-dynamic permission "
3372                            + name);
3373                }
3374                mSettings.mPermissions.remove(name);
3375                mSettings.writeLPr();
3376            }
3377        }
3378    }
3379
3380    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3381            BasePermission bp) {
3382        int index = pkg.requestedPermissions.indexOf(bp.name);
3383        if (index == -1) {
3384            throw new SecurityException("Package " + pkg.packageName
3385                    + " has not requested permission " + bp.name);
3386        }
3387        if (!bp.isRuntime()) {
3388            throw new SecurityException("Permission " + bp.name
3389                    + " is not a changeable permission type");
3390        }
3391    }
3392
3393    @Override
3394    public void grantRuntimePermission(String packageName, String name, final int userId) {
3395        if (!sUserManager.exists(userId)) {
3396            Log.e(TAG, "No such user:" + userId);
3397            return;
3398        }
3399
3400        mContext.enforceCallingOrSelfPermission(
3401                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3402                "grantRuntimePermission");
3403
3404        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3405                "grantRuntimePermission");
3406
3407        final int uid;
3408        final SettingBase sb;
3409
3410        synchronized (mPackages) {
3411            final PackageParser.Package pkg = mPackages.get(packageName);
3412            if (pkg == null) {
3413                throw new IllegalArgumentException("Unknown package: " + packageName);
3414            }
3415
3416            final BasePermission bp = mSettings.mPermissions.get(name);
3417            if (bp == null) {
3418                throw new IllegalArgumentException("Unknown permission: " + name);
3419            }
3420
3421            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3422
3423            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3424            sb = (SettingBase) pkg.mExtras;
3425            if (sb == null) {
3426                throw new IllegalArgumentException("Unknown package: " + packageName);
3427            }
3428
3429            final PermissionsState permissionsState = sb.getPermissionsState();
3430
3431            final int flags = permissionsState.getPermissionFlags(name, userId);
3432            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3433                throw new SecurityException("Cannot grant system fixed permission: "
3434                        + name + " for package: " + packageName);
3435            }
3436
3437            final int result = permissionsState.grantRuntimePermission(bp, userId);
3438            switch (result) {
3439                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3440                    return;
3441                }
3442
3443                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3444                    mHandler.post(new Runnable() {
3445                        @Override
3446                        public void run() {
3447                            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3448                        }
3449                    });
3450                } break;
3451            }
3452
3453            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3454
3455            // Not critical if that is lost - app has to request again.
3456            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3457        }
3458
3459        // Only need to do this if user is initialized. Otherwise it's a new user
3460        // and there are no processes running as the user yet and there's no need
3461        // to make an expensive call to remount processes for the changed permissions.
3462        if ((READ_EXTERNAL_STORAGE.equals(name)
3463                || WRITE_EXTERNAL_STORAGE.equals(name))
3464                && sUserManager.isInitialized(userId)) {
3465            final long token = Binder.clearCallingIdentity();
3466            try {
3467                final StorageManager storage = mContext.getSystemService(StorageManager.class);
3468                storage.remountUid(uid);
3469            } finally {
3470                Binder.restoreCallingIdentity(token);
3471            }
3472        }
3473    }
3474
3475    @Override
3476    public void revokeRuntimePermission(String packageName, String name, int userId) {
3477        if (!sUserManager.exists(userId)) {
3478            Log.e(TAG, "No such user:" + userId);
3479            return;
3480        }
3481
3482        mContext.enforceCallingOrSelfPermission(
3483                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3484                "revokeRuntimePermission");
3485
3486        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3487                "revokeRuntimePermission");
3488
3489        final SettingBase sb;
3490
3491        synchronized (mPackages) {
3492            final PackageParser.Package pkg = mPackages.get(packageName);
3493            if (pkg == null) {
3494                throw new IllegalArgumentException("Unknown package: " + packageName);
3495            }
3496
3497            final BasePermission bp = mSettings.mPermissions.get(name);
3498            if (bp == null) {
3499                throw new IllegalArgumentException("Unknown permission: " + name);
3500            }
3501
3502            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3503
3504            sb = (SettingBase) pkg.mExtras;
3505            if (sb == null) {
3506                throw new IllegalArgumentException("Unknown package: " + packageName);
3507            }
3508
3509            final PermissionsState permissionsState = sb.getPermissionsState();
3510
3511            final int flags = permissionsState.getPermissionFlags(name, userId);
3512            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3513                throw new SecurityException("Cannot revoke system fixed permission: "
3514                        + name + " for package: " + packageName);
3515            }
3516
3517            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3518                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3519                return;
3520            }
3521
3522            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3523
3524            // Critical, after this call app should never have the permission.
3525            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3526        }
3527
3528        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3529    }
3530
3531    @Override
3532    public void resetRuntimePermissions() {
3533        mContext.enforceCallingOrSelfPermission(
3534                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3535                "revokeRuntimePermission");
3536
3537        int callingUid = Binder.getCallingUid();
3538        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3539            mContext.enforceCallingOrSelfPermission(
3540                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3541                    "resetRuntimePermissions");
3542        }
3543
3544        final int[] userIds;
3545
3546        synchronized (mPackages) {
3547            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3548            final int userCount = UserManagerService.getInstance().getUserIds().length;
3549            userIds = Arrays.copyOf(UserManagerService.getInstance().getUserIds(), userCount);
3550        }
3551
3552        for (int userId : userIds) {
3553            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
3554        }
3555    }
3556
3557    @Override
3558    public int getPermissionFlags(String name, String packageName, int userId) {
3559        if (!sUserManager.exists(userId)) {
3560            return 0;
3561        }
3562
3563        mContext.enforceCallingOrSelfPermission(
3564                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3565                "getPermissionFlags");
3566
3567        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3568                "getPermissionFlags");
3569
3570        synchronized (mPackages) {
3571            final PackageParser.Package pkg = mPackages.get(packageName);
3572            if (pkg == null) {
3573                throw new IllegalArgumentException("Unknown package: " + packageName);
3574            }
3575
3576            final BasePermission bp = mSettings.mPermissions.get(name);
3577            if (bp == null) {
3578                throw new IllegalArgumentException("Unknown permission: " + name);
3579            }
3580
3581            SettingBase sb = (SettingBase) pkg.mExtras;
3582            if (sb == null) {
3583                throw new IllegalArgumentException("Unknown package: " + packageName);
3584            }
3585
3586            PermissionsState permissionsState = sb.getPermissionsState();
3587            return permissionsState.getPermissionFlags(name, userId);
3588        }
3589    }
3590
3591    @Override
3592    public void updatePermissionFlags(String name, String packageName, int flagMask,
3593            int flagValues, int userId) {
3594        if (!sUserManager.exists(userId)) {
3595            return;
3596        }
3597
3598        mContext.enforceCallingOrSelfPermission(
3599                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3600                "updatePermissionFlags");
3601
3602        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3603                "updatePermissionFlags");
3604
3605        // Only the system can change system fixed flags.
3606        if (getCallingUid() != Process.SYSTEM_UID) {
3607            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3608            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3609        }
3610
3611        synchronized (mPackages) {
3612            final PackageParser.Package pkg = mPackages.get(packageName);
3613            if (pkg == null) {
3614                throw new IllegalArgumentException("Unknown package: " + packageName);
3615            }
3616
3617            final BasePermission bp = mSettings.mPermissions.get(name);
3618            if (bp == null) {
3619                throw new IllegalArgumentException("Unknown permission: " + name);
3620            }
3621
3622            SettingBase sb = (SettingBase) pkg.mExtras;
3623            if (sb == null) {
3624                throw new IllegalArgumentException("Unknown package: " + packageName);
3625            }
3626
3627            PermissionsState permissionsState = sb.getPermissionsState();
3628
3629            // Only the package manager can change flags for system component permissions.
3630            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3631            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3632                return;
3633            }
3634
3635            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3636
3637            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3638                // Install and runtime permissions are stored in different places,
3639                // so figure out what permission changed and persist the change.
3640                if (permissionsState.getInstallPermissionState(name) != null) {
3641                    scheduleWriteSettingsLocked();
3642                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3643                        || hadState) {
3644                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3645                }
3646            }
3647        }
3648    }
3649
3650    /**
3651     * Update the permission flags for all packages and runtime permissions of a user in order
3652     * to allow device or profile owner to remove POLICY_FIXED.
3653     */
3654    @Override
3655    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3656        if (!sUserManager.exists(userId)) {
3657            return;
3658        }
3659
3660        mContext.enforceCallingOrSelfPermission(
3661                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3662                "updatePermissionFlagsForAllApps");
3663
3664        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3665                "updatePermissionFlagsForAllApps");
3666
3667        // Only the system can change system fixed flags.
3668        if (getCallingUid() != Process.SYSTEM_UID) {
3669            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3670            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3671        }
3672
3673        synchronized (mPackages) {
3674            boolean changed = false;
3675            final int packageCount = mPackages.size();
3676            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3677                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3678                SettingBase sb = (SettingBase) pkg.mExtras;
3679                if (sb == null) {
3680                    continue;
3681                }
3682                PermissionsState permissionsState = sb.getPermissionsState();
3683                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3684                        userId, flagMask, flagValues);
3685            }
3686            if (changed) {
3687                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3688            }
3689        }
3690    }
3691
3692    @Override
3693    public boolean shouldShowRequestPermissionRationale(String permissionName,
3694            String packageName, int userId) {
3695        if (UserHandle.getCallingUserId() != userId) {
3696            mContext.enforceCallingPermission(
3697                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3698                    "canShowRequestPermissionRationale for user " + userId);
3699        }
3700
3701        final int uid = getPackageUid(packageName, userId);
3702        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3703            return false;
3704        }
3705
3706        if (checkPermission(permissionName, packageName, userId)
3707                == PackageManager.PERMISSION_GRANTED) {
3708            return false;
3709        }
3710
3711        final int flags;
3712
3713        final long identity = Binder.clearCallingIdentity();
3714        try {
3715            flags = getPermissionFlags(permissionName,
3716                    packageName, userId);
3717        } finally {
3718            Binder.restoreCallingIdentity(identity);
3719        }
3720
3721        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3722                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3723                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3724
3725        if ((flags & fixedFlags) != 0) {
3726            return false;
3727        }
3728
3729        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3730    }
3731
3732    void grantInstallPermissionLPw(String permission, PackageParser.Package pkg) {
3733        BasePermission bp = mSettings.mPermissions.get(permission);
3734        if (bp == null) {
3735            throw new SecurityException("Missing " + permission + " permission");
3736        }
3737
3738        SettingBase sb = (SettingBase) pkg.mExtras;
3739        PermissionsState permissionsState = sb.getPermissionsState();
3740
3741        if (permissionsState.grantInstallPermission(bp) !=
3742                PermissionsState.PERMISSION_OPERATION_FAILURE) {
3743            scheduleWriteSettingsLocked();
3744        }
3745    }
3746
3747    @Override
3748    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3749        mContext.enforceCallingOrSelfPermission(
3750                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3751                "addOnPermissionsChangeListener");
3752
3753        synchronized (mPackages) {
3754            mOnPermissionChangeListeners.addListenerLocked(listener);
3755        }
3756    }
3757
3758    @Override
3759    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3760        synchronized (mPackages) {
3761            mOnPermissionChangeListeners.removeListenerLocked(listener);
3762        }
3763    }
3764
3765    @Override
3766    public boolean isProtectedBroadcast(String actionName) {
3767        synchronized (mPackages) {
3768            return mProtectedBroadcasts.contains(actionName);
3769        }
3770    }
3771
3772    @Override
3773    public int checkSignatures(String pkg1, String pkg2) {
3774        synchronized (mPackages) {
3775            final PackageParser.Package p1 = mPackages.get(pkg1);
3776            final PackageParser.Package p2 = mPackages.get(pkg2);
3777            if (p1 == null || p1.mExtras == null
3778                    || p2 == null || p2.mExtras == null) {
3779                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3780            }
3781            return compareSignatures(p1.mSignatures, p2.mSignatures);
3782        }
3783    }
3784
3785    @Override
3786    public int checkUidSignatures(int uid1, int uid2) {
3787        // Map to base uids.
3788        uid1 = UserHandle.getAppId(uid1);
3789        uid2 = UserHandle.getAppId(uid2);
3790        // reader
3791        synchronized (mPackages) {
3792            Signature[] s1;
3793            Signature[] s2;
3794            Object obj = mSettings.getUserIdLPr(uid1);
3795            if (obj != null) {
3796                if (obj instanceof SharedUserSetting) {
3797                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3798                } else if (obj instanceof PackageSetting) {
3799                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3800                } else {
3801                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3802                }
3803            } else {
3804                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3805            }
3806            obj = mSettings.getUserIdLPr(uid2);
3807            if (obj != null) {
3808                if (obj instanceof SharedUserSetting) {
3809                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3810                } else if (obj instanceof PackageSetting) {
3811                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3812                } else {
3813                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3814                }
3815            } else {
3816                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3817            }
3818            return compareSignatures(s1, s2);
3819        }
3820    }
3821
3822    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3823        final long identity = Binder.clearCallingIdentity();
3824        try {
3825            if (sb instanceof SharedUserSetting) {
3826                SharedUserSetting sus = (SharedUserSetting) sb;
3827                final int packageCount = sus.packages.size();
3828                for (int i = 0; i < packageCount; i++) {
3829                    PackageSetting susPs = sus.packages.valueAt(i);
3830                    if (userId == UserHandle.USER_ALL) {
3831                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3832                    } else {
3833                        final int uid = UserHandle.getUid(userId, susPs.appId);
3834                        killUid(uid, reason);
3835                    }
3836                }
3837            } else if (sb instanceof PackageSetting) {
3838                PackageSetting ps = (PackageSetting) sb;
3839                if (userId == UserHandle.USER_ALL) {
3840                    killApplication(ps.pkg.packageName, ps.appId, reason);
3841                } else {
3842                    final int uid = UserHandle.getUid(userId, ps.appId);
3843                    killUid(uid, reason);
3844                }
3845            }
3846        } finally {
3847            Binder.restoreCallingIdentity(identity);
3848        }
3849    }
3850
3851    private static void killUid(int uid, String reason) {
3852        IActivityManager am = ActivityManagerNative.getDefault();
3853        if (am != null) {
3854            try {
3855                am.killUid(uid, reason);
3856            } catch (RemoteException e) {
3857                /* ignore - same process */
3858            }
3859        }
3860    }
3861
3862    /**
3863     * Compares two sets of signatures. Returns:
3864     * <br />
3865     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3866     * <br />
3867     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3868     * <br />
3869     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3870     * <br />
3871     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3872     * <br />
3873     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3874     */
3875    static int compareSignatures(Signature[] s1, Signature[] s2) {
3876        if (s1 == null) {
3877            return s2 == null
3878                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3879                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3880        }
3881
3882        if (s2 == null) {
3883            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3884        }
3885
3886        if (s1.length != s2.length) {
3887            return PackageManager.SIGNATURE_NO_MATCH;
3888        }
3889
3890        // Since both signature sets are of size 1, we can compare without HashSets.
3891        if (s1.length == 1) {
3892            return s1[0].equals(s2[0]) ?
3893                    PackageManager.SIGNATURE_MATCH :
3894                    PackageManager.SIGNATURE_NO_MATCH;
3895        }
3896
3897        ArraySet<Signature> set1 = new ArraySet<Signature>();
3898        for (Signature sig : s1) {
3899            set1.add(sig);
3900        }
3901        ArraySet<Signature> set2 = new ArraySet<Signature>();
3902        for (Signature sig : s2) {
3903            set2.add(sig);
3904        }
3905        // Make sure s2 contains all signatures in s1.
3906        if (set1.equals(set2)) {
3907            return PackageManager.SIGNATURE_MATCH;
3908        }
3909        return PackageManager.SIGNATURE_NO_MATCH;
3910    }
3911
3912    /**
3913     * If the database version for this type of package (internal storage or
3914     * external storage) is less than the version where package signatures
3915     * were updated, return true.
3916     */
3917    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3918        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3919                DatabaseVersion.SIGNATURE_END_ENTITY))
3920                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3921                        DatabaseVersion.SIGNATURE_END_ENTITY));
3922    }
3923
3924    /**
3925     * Used for backward compatibility to make sure any packages with
3926     * certificate chains get upgraded to the new style. {@code existingSigs}
3927     * will be in the old format (since they were stored on disk from before the
3928     * system upgrade) and {@code scannedSigs} will be in the newer format.
3929     */
3930    private int compareSignaturesCompat(PackageSignatures existingSigs,
3931            PackageParser.Package scannedPkg) {
3932        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3933            return PackageManager.SIGNATURE_NO_MATCH;
3934        }
3935
3936        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3937        for (Signature sig : existingSigs.mSignatures) {
3938            existingSet.add(sig);
3939        }
3940        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3941        for (Signature sig : scannedPkg.mSignatures) {
3942            try {
3943                Signature[] chainSignatures = sig.getChainSignatures();
3944                for (Signature chainSig : chainSignatures) {
3945                    scannedCompatSet.add(chainSig);
3946                }
3947            } catch (CertificateEncodingException e) {
3948                scannedCompatSet.add(sig);
3949            }
3950        }
3951        /*
3952         * Make sure the expanded scanned set contains all signatures in the
3953         * existing one.
3954         */
3955        if (scannedCompatSet.equals(existingSet)) {
3956            // Migrate the old signatures to the new scheme.
3957            existingSigs.assignSignatures(scannedPkg.mSignatures);
3958            // The new KeySets will be re-added later in the scanning process.
3959            synchronized (mPackages) {
3960                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3961            }
3962            return PackageManager.SIGNATURE_MATCH;
3963        }
3964        return PackageManager.SIGNATURE_NO_MATCH;
3965    }
3966
3967    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3968        if (isExternal(scannedPkg)) {
3969            return mSettings.isExternalDatabaseVersionOlderThan(
3970                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3971        } else {
3972            return mSettings.isInternalDatabaseVersionOlderThan(
3973                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3974        }
3975    }
3976
3977    private int compareSignaturesRecover(PackageSignatures existingSigs,
3978            PackageParser.Package scannedPkg) {
3979        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3980            return PackageManager.SIGNATURE_NO_MATCH;
3981        }
3982
3983        String msg = null;
3984        try {
3985            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3986                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3987                        + scannedPkg.packageName);
3988                return PackageManager.SIGNATURE_MATCH;
3989            }
3990        } catch (CertificateException e) {
3991            msg = e.getMessage();
3992        }
3993
3994        logCriticalInfo(Log.INFO,
3995                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3996        return PackageManager.SIGNATURE_NO_MATCH;
3997    }
3998
3999    @Override
4000    public String[] getPackagesForUid(int uid) {
4001        uid = UserHandle.getAppId(uid);
4002        // reader
4003        synchronized (mPackages) {
4004            Object obj = mSettings.getUserIdLPr(uid);
4005            if (obj instanceof SharedUserSetting) {
4006                final SharedUserSetting sus = (SharedUserSetting) obj;
4007                final int N = sus.packages.size();
4008                final String[] res = new String[N];
4009                final Iterator<PackageSetting> it = sus.packages.iterator();
4010                int i = 0;
4011                while (it.hasNext()) {
4012                    res[i++] = it.next().name;
4013                }
4014                return res;
4015            } else if (obj instanceof PackageSetting) {
4016                final PackageSetting ps = (PackageSetting) obj;
4017                return new String[] { ps.name };
4018            }
4019        }
4020        return null;
4021    }
4022
4023    @Override
4024    public String getNameForUid(int uid) {
4025        // reader
4026        synchronized (mPackages) {
4027            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4028            if (obj instanceof SharedUserSetting) {
4029                final SharedUserSetting sus = (SharedUserSetting) obj;
4030                return sus.name + ":" + sus.userId;
4031            } else if (obj instanceof PackageSetting) {
4032                final PackageSetting ps = (PackageSetting) obj;
4033                return ps.name;
4034            }
4035        }
4036        return null;
4037    }
4038
4039    @Override
4040    public int getUidForSharedUser(String sharedUserName) {
4041        if(sharedUserName == null) {
4042            return -1;
4043        }
4044        // reader
4045        synchronized (mPackages) {
4046            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4047            if (suid == null) {
4048                return -1;
4049            }
4050            return suid.userId;
4051        }
4052    }
4053
4054    @Override
4055    public int getFlagsForUid(int uid) {
4056        synchronized (mPackages) {
4057            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4058            if (obj instanceof SharedUserSetting) {
4059                final SharedUserSetting sus = (SharedUserSetting) obj;
4060                return sus.pkgFlags;
4061            } else if (obj instanceof PackageSetting) {
4062                final PackageSetting ps = (PackageSetting) obj;
4063                return ps.pkgFlags;
4064            }
4065        }
4066        return 0;
4067    }
4068
4069    @Override
4070    public int getPrivateFlagsForUid(int uid) {
4071        synchronized (mPackages) {
4072            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4073            if (obj instanceof SharedUserSetting) {
4074                final SharedUserSetting sus = (SharedUserSetting) obj;
4075                return sus.pkgPrivateFlags;
4076            } else if (obj instanceof PackageSetting) {
4077                final PackageSetting ps = (PackageSetting) obj;
4078                return ps.pkgPrivateFlags;
4079            }
4080        }
4081        return 0;
4082    }
4083
4084    @Override
4085    public boolean isUidPrivileged(int uid) {
4086        uid = UserHandle.getAppId(uid);
4087        // reader
4088        synchronized (mPackages) {
4089            Object obj = mSettings.getUserIdLPr(uid);
4090            if (obj instanceof SharedUserSetting) {
4091                final SharedUserSetting sus = (SharedUserSetting) obj;
4092                final Iterator<PackageSetting> it = sus.packages.iterator();
4093                while (it.hasNext()) {
4094                    if (it.next().isPrivileged()) {
4095                        return true;
4096                    }
4097                }
4098            } else if (obj instanceof PackageSetting) {
4099                final PackageSetting ps = (PackageSetting) obj;
4100                return ps.isPrivileged();
4101            }
4102        }
4103        return false;
4104    }
4105
4106    @Override
4107    public String[] getAppOpPermissionPackages(String permissionName) {
4108        synchronized (mPackages) {
4109            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4110            if (pkgs == null) {
4111                return null;
4112            }
4113            return pkgs.toArray(new String[pkgs.size()]);
4114        }
4115    }
4116
4117    @Override
4118    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4119            int flags, int userId) {
4120        if (!sUserManager.exists(userId)) return null;
4121        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4122        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4123        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4124    }
4125
4126    @Override
4127    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4128            IntentFilter filter, int match, ComponentName activity) {
4129        final int userId = UserHandle.getCallingUserId();
4130        if (DEBUG_PREFERRED) {
4131            Log.v(TAG, "setLastChosenActivity intent=" + intent
4132                + " resolvedType=" + resolvedType
4133                + " flags=" + flags
4134                + " filter=" + filter
4135                + " match=" + match
4136                + " activity=" + activity);
4137            filter.dump(new PrintStreamPrinter(System.out), "    ");
4138        }
4139        intent.setComponent(null);
4140        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4141        // Find any earlier preferred or last chosen entries and nuke them
4142        findPreferredActivity(intent, resolvedType,
4143                flags, query, 0, false, true, false, userId);
4144        // Add the new activity as the last chosen for this filter
4145        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4146                "Setting last chosen");
4147    }
4148
4149    @Override
4150    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4151        final int userId = UserHandle.getCallingUserId();
4152        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4153        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4154        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4155                false, false, false, userId);
4156    }
4157
4158    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4159            int flags, List<ResolveInfo> query, int userId) {
4160        if (query != null) {
4161            final int N = query.size();
4162            if (N == 1) {
4163                return query.get(0);
4164            } else if (N > 1) {
4165                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4166                // If there is more than one activity with the same priority,
4167                // then let the user decide between them.
4168                ResolveInfo r0 = query.get(0);
4169                ResolveInfo r1 = query.get(1);
4170                if (DEBUG_INTENT_MATCHING || debug) {
4171                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4172                            + r1.activityInfo.name + "=" + r1.priority);
4173                }
4174                // If the first activity has a higher priority, or a different
4175                // default, then it is always desireable to pick it.
4176                if (r0.priority != r1.priority
4177                        || r0.preferredOrder != r1.preferredOrder
4178                        || r0.isDefault != r1.isDefault) {
4179                    return query.get(0);
4180                }
4181                // If we have saved a preference for a preferred activity for
4182                // this Intent, use that.
4183                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4184                        flags, query, r0.priority, true, false, debug, userId);
4185                if (ri != null) {
4186                    return ri;
4187                }
4188                if (userId != 0) {
4189                    ri = new ResolveInfo(mResolveInfo);
4190                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
4191                    ri.activityInfo.applicationInfo = new ApplicationInfo(
4192                            ri.activityInfo.applicationInfo);
4193                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4194                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4195                    return ri;
4196                }
4197                return mResolveInfo;
4198            }
4199        }
4200        return null;
4201    }
4202
4203    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4204            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4205        final int N = query.size();
4206        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4207                .get(userId);
4208        // Get the list of persistent preferred activities that handle the intent
4209        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4210        List<PersistentPreferredActivity> pprefs = ppir != null
4211                ? ppir.queryIntent(intent, resolvedType,
4212                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4213                : null;
4214        if (pprefs != null && pprefs.size() > 0) {
4215            final int M = pprefs.size();
4216            for (int i=0; i<M; i++) {
4217                final PersistentPreferredActivity ppa = pprefs.get(i);
4218                if (DEBUG_PREFERRED || debug) {
4219                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4220                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4221                            + "\n  component=" + ppa.mComponent);
4222                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4223                }
4224                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4225                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4226                if (DEBUG_PREFERRED || debug) {
4227                    Slog.v(TAG, "Found persistent preferred activity:");
4228                    if (ai != null) {
4229                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4230                    } else {
4231                        Slog.v(TAG, "  null");
4232                    }
4233                }
4234                if (ai == null) {
4235                    // This previously registered persistent preferred activity
4236                    // component is no longer known. Ignore it and do NOT remove it.
4237                    continue;
4238                }
4239                for (int j=0; j<N; j++) {
4240                    final ResolveInfo ri = query.get(j);
4241                    if (!ri.activityInfo.applicationInfo.packageName
4242                            .equals(ai.applicationInfo.packageName)) {
4243                        continue;
4244                    }
4245                    if (!ri.activityInfo.name.equals(ai.name)) {
4246                        continue;
4247                    }
4248                    //  Found a persistent preference that can handle the intent.
4249                    if (DEBUG_PREFERRED || debug) {
4250                        Slog.v(TAG, "Returning persistent preferred activity: " +
4251                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4252                    }
4253                    return ri;
4254                }
4255            }
4256        }
4257        return null;
4258    }
4259
4260    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4261            List<ResolveInfo> query, int priority, boolean always,
4262            boolean removeMatches, boolean debug, int userId) {
4263        if (!sUserManager.exists(userId)) return null;
4264        // writer
4265        synchronized (mPackages) {
4266            if (intent.getSelector() != null) {
4267                intent = intent.getSelector();
4268            }
4269            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4270
4271            // Try to find a matching persistent preferred activity.
4272            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4273                    debug, userId);
4274
4275            // If a persistent preferred activity matched, use it.
4276            if (pri != null) {
4277                return pri;
4278            }
4279
4280            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4281            // Get the list of preferred activities that handle the intent
4282            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4283            List<PreferredActivity> prefs = pir != null
4284                    ? pir.queryIntent(intent, resolvedType,
4285                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4286                    : null;
4287            if (prefs != null && prefs.size() > 0) {
4288                boolean changed = false;
4289                try {
4290                    // First figure out how good the original match set is.
4291                    // We will only allow preferred activities that came
4292                    // from the same match quality.
4293                    int match = 0;
4294
4295                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4296
4297                    final int N = query.size();
4298                    for (int j=0; j<N; j++) {
4299                        final ResolveInfo ri = query.get(j);
4300                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4301                                + ": 0x" + Integer.toHexString(match));
4302                        if (ri.match > match) {
4303                            match = ri.match;
4304                        }
4305                    }
4306
4307                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4308                            + Integer.toHexString(match));
4309
4310                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4311                    final int M = prefs.size();
4312                    for (int i=0; i<M; i++) {
4313                        final PreferredActivity pa = prefs.get(i);
4314                        if (DEBUG_PREFERRED || debug) {
4315                            Slog.v(TAG, "Checking PreferredActivity ds="
4316                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4317                                    + "\n  component=" + pa.mPref.mComponent);
4318                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4319                        }
4320                        if (pa.mPref.mMatch != match) {
4321                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4322                                    + Integer.toHexString(pa.mPref.mMatch));
4323                            continue;
4324                        }
4325                        // If it's not an "always" type preferred activity and that's what we're
4326                        // looking for, skip it.
4327                        if (always && !pa.mPref.mAlways) {
4328                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4329                            continue;
4330                        }
4331                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4332                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4333                        if (DEBUG_PREFERRED || debug) {
4334                            Slog.v(TAG, "Found preferred activity:");
4335                            if (ai != null) {
4336                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4337                            } else {
4338                                Slog.v(TAG, "  null");
4339                            }
4340                        }
4341                        if (ai == null) {
4342                            // This previously registered preferred activity
4343                            // component is no longer known.  Most likely an update
4344                            // to the app was installed and in the new version this
4345                            // component no longer exists.  Clean it up by removing
4346                            // it from the preferred activities list, and skip it.
4347                            Slog.w(TAG, "Removing dangling preferred activity: "
4348                                    + pa.mPref.mComponent);
4349                            pir.removeFilter(pa);
4350                            changed = true;
4351                            continue;
4352                        }
4353                        for (int j=0; j<N; j++) {
4354                            final ResolveInfo ri = query.get(j);
4355                            if (!ri.activityInfo.applicationInfo.packageName
4356                                    .equals(ai.applicationInfo.packageName)) {
4357                                continue;
4358                            }
4359                            if (!ri.activityInfo.name.equals(ai.name)) {
4360                                continue;
4361                            }
4362
4363                            if (removeMatches) {
4364                                pir.removeFilter(pa);
4365                                changed = true;
4366                                if (DEBUG_PREFERRED) {
4367                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4368                                }
4369                                break;
4370                            }
4371
4372                            // Okay we found a previously set preferred or last chosen app.
4373                            // If the result set is different from when this
4374                            // was created, we need to clear it and re-ask the
4375                            // user their preference, if we're looking for an "always" type entry.
4376                            if (always && !pa.mPref.sameSet(query)) {
4377                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4378                                        + intent + " type " + resolvedType);
4379                                if (DEBUG_PREFERRED) {
4380                                    Slog.v(TAG, "Removing preferred activity since set changed "
4381                                            + pa.mPref.mComponent);
4382                                }
4383                                pir.removeFilter(pa);
4384                                // Re-add the filter as a "last chosen" entry (!always)
4385                                PreferredActivity lastChosen = new PreferredActivity(
4386                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4387                                pir.addFilter(lastChosen);
4388                                changed = true;
4389                                return null;
4390                            }
4391
4392                            // Yay! Either the set matched or we're looking for the last chosen
4393                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4394                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4395                            return ri;
4396                        }
4397                    }
4398                } finally {
4399                    if (changed) {
4400                        if (DEBUG_PREFERRED) {
4401                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4402                        }
4403                        scheduleWritePackageRestrictionsLocked(userId);
4404                    }
4405                }
4406            }
4407        }
4408        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4409        return null;
4410    }
4411
4412    /*
4413     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4414     */
4415    @Override
4416    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4417            int targetUserId) {
4418        mContext.enforceCallingOrSelfPermission(
4419                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4420        List<CrossProfileIntentFilter> matches =
4421                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4422        if (matches != null) {
4423            int size = matches.size();
4424            for (int i = 0; i < size; i++) {
4425                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4426            }
4427        }
4428        if (hasWebURI(intent)) {
4429            // cross-profile app linking works only towards the parent.
4430            final UserInfo parent = getProfileParent(sourceUserId);
4431            synchronized(mPackages) {
4432                return getCrossProfileDomainPreferredLpr(intent, resolvedType, 0, sourceUserId,
4433                        parent.id) != null;
4434            }
4435        }
4436        return false;
4437    }
4438
4439    private UserInfo getProfileParent(int userId) {
4440        final long identity = Binder.clearCallingIdentity();
4441        try {
4442            return sUserManager.getProfileParent(userId);
4443        } finally {
4444            Binder.restoreCallingIdentity(identity);
4445        }
4446    }
4447
4448    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4449            String resolvedType, int userId) {
4450        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4451        if (resolver != null) {
4452            return resolver.queryIntent(intent, resolvedType, false, userId);
4453        }
4454        return null;
4455    }
4456
4457    @Override
4458    public List<ResolveInfo> queryIntentActivities(Intent intent,
4459            String resolvedType, int flags, int userId) {
4460        if (!sUserManager.exists(userId)) return Collections.emptyList();
4461        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4462        ComponentName comp = intent.getComponent();
4463        if (comp == null) {
4464            if (intent.getSelector() != null) {
4465                intent = intent.getSelector();
4466                comp = intent.getComponent();
4467            }
4468        }
4469
4470        if (comp != null) {
4471            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4472            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4473            if (ai != null) {
4474                final ResolveInfo ri = new ResolveInfo();
4475                ri.activityInfo = ai;
4476                list.add(ri);
4477            }
4478            return list;
4479        }
4480
4481        // reader
4482        synchronized (mPackages) {
4483            final String pkgName = intent.getPackage();
4484            if (pkgName == null) {
4485                List<CrossProfileIntentFilter> matchingFilters =
4486                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4487                // Check for results that need to skip the current profile.
4488                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4489                        resolvedType, flags, userId);
4490                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4491                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4492                    result.add(xpResolveInfo);
4493                    return filterIfNotPrimaryUser(result, userId);
4494                }
4495
4496                // Check for results in the current profile.
4497                List<ResolveInfo> result = mActivities.queryIntent(
4498                        intent, resolvedType, flags, userId);
4499
4500                // Check for cross profile results.
4501                xpResolveInfo = queryCrossProfileIntents(
4502                        matchingFilters, intent, resolvedType, flags, userId);
4503                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4504                    result.add(xpResolveInfo);
4505                    Collections.sort(result, mResolvePrioritySorter);
4506                }
4507                result = filterIfNotPrimaryUser(result, userId);
4508                if (hasWebURI(intent)) {
4509                    CrossProfileDomainInfo xpDomainInfo = null;
4510                    final UserInfo parent = getProfileParent(userId);
4511                    if (parent != null) {
4512                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4513                                flags, userId, parent.id);
4514                    }
4515                    if (xpDomainInfo != null) {
4516                        if (xpResolveInfo != null) {
4517                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4518                            // in the result.
4519                            result.remove(xpResolveInfo);
4520                        }
4521                        if (result.size() == 0) {
4522                            result.add(xpDomainInfo.resolveInfo);
4523                            return result;
4524                        }
4525                    } else if (result.size() <= 1) {
4526                        return result;
4527                    }
4528                    result = filterCandidatesWithDomainPreferredActivitiesLPr(flags, result,
4529                            xpDomainInfo);
4530                    Collections.sort(result, mResolvePrioritySorter);
4531                }
4532                return result;
4533            }
4534            final PackageParser.Package pkg = mPackages.get(pkgName);
4535            if (pkg != null) {
4536                return filterIfNotPrimaryUser(
4537                        mActivities.queryIntentForPackage(
4538                                intent, resolvedType, flags, pkg.activities, userId),
4539                        userId);
4540            }
4541            return new ArrayList<ResolveInfo>();
4542        }
4543    }
4544
4545    private static class CrossProfileDomainInfo {
4546        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4547        ResolveInfo resolveInfo;
4548        /* Best domain verification status of the activities found in the other profile */
4549        int bestDomainVerificationStatus;
4550    }
4551
4552    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4553            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4554        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4555                sourceUserId)) {
4556            return null;
4557        }
4558        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4559                resolvedType, flags, parentUserId);
4560
4561        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4562            return null;
4563        }
4564        CrossProfileDomainInfo result = null;
4565        int size = resultTargetUser.size();
4566        for (int i = 0; i < size; i++) {
4567            ResolveInfo riTargetUser = resultTargetUser.get(i);
4568            // Intent filter verification is only for filters that specify a host. So don't return
4569            // those that handle all web uris.
4570            if (riTargetUser.handleAllWebDataURI) {
4571                continue;
4572            }
4573            String packageName = riTargetUser.activityInfo.packageName;
4574            PackageSetting ps = mSettings.mPackages.get(packageName);
4575            if (ps == null) {
4576                continue;
4577            }
4578            int status = getDomainVerificationStatusLPr(ps, parentUserId);
4579            if (result == null) {
4580                result = new CrossProfileDomainInfo();
4581                result.resolveInfo =
4582                        createForwardingResolveInfo(null, sourceUserId, parentUserId);
4583                result.bestDomainVerificationStatus = status;
4584            } else {
4585                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4586                        result.bestDomainVerificationStatus);
4587            }
4588        }
4589        return result;
4590    }
4591
4592    /**
4593     * Verification statuses are ordered from the worse to the best, except for
4594     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4595     */
4596    private int bestDomainVerificationStatus(int status1, int status2) {
4597        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4598            return status2;
4599        }
4600        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4601            return status1;
4602        }
4603        return (int) MathUtils.max(status1, status2);
4604    }
4605
4606    private boolean isUserEnabled(int userId) {
4607        long callingId = Binder.clearCallingIdentity();
4608        try {
4609            UserInfo userInfo = sUserManager.getUserInfo(userId);
4610            return userInfo != null && userInfo.isEnabled();
4611        } finally {
4612            Binder.restoreCallingIdentity(callingId);
4613        }
4614    }
4615
4616    /**
4617     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4618     *
4619     * @return filtered list
4620     */
4621    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4622        if (userId == UserHandle.USER_OWNER) {
4623            return resolveInfos;
4624        }
4625        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4626            ResolveInfo info = resolveInfos.get(i);
4627            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4628                resolveInfos.remove(i);
4629            }
4630        }
4631        return resolveInfos;
4632    }
4633
4634    private static boolean hasWebURI(Intent intent) {
4635        if (intent.getData() == null) {
4636            return false;
4637        }
4638        final String scheme = intent.getScheme();
4639        if (TextUtils.isEmpty(scheme)) {
4640            return false;
4641        }
4642        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4643    }
4644
4645    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(
4646            int flags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo) {
4647        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4648            Slog.v("TAG", "Filtering results with preferred activities. Candidates count: " +
4649                    candidates.size());
4650        }
4651
4652        final int userId = UserHandle.getCallingUserId();
4653        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4654        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4655        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4656        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4657        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4658
4659        synchronized (mPackages) {
4660            final int count = candidates.size();
4661            // First, try to use linked apps. Partition the candidates into four lists:
4662            // one for the final results, one for the "do not use ever", one for "undefined status"
4663            // and finally one for "browser app type".
4664            for (int n=0; n<count; n++) {
4665                ResolveInfo info = candidates.get(n);
4666                String packageName = info.activityInfo.packageName;
4667                PackageSetting ps = mSettings.mPackages.get(packageName);
4668                if (ps != null) {
4669                    // Add to the special match all list (Browser use case)
4670                    if (info.handleAllWebDataURI) {
4671                        matchAllList.add(info);
4672                        continue;
4673                    }
4674                    // Try to get the status from User settings first
4675                    int status = getDomainVerificationStatusLPr(ps, userId);
4676                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4677                        if (DEBUG_DOMAIN_VERIFICATION) {
4678                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName);
4679                        }
4680                        alwaysList.add(info);
4681                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4682                        if (DEBUG_DOMAIN_VERIFICATION) {
4683                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4684                        }
4685                        neverList.add(info);
4686                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4687                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4688                        if (DEBUG_DOMAIN_VERIFICATION) {
4689                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4690                        }
4691                        undefinedList.add(info);
4692                    }
4693                }
4694            }
4695            // First try to add the "always" resolution for the current user if there is any
4696            if (alwaysList.size() > 0) {
4697                result.addAll(alwaysList);
4698            // if there is an "always" for the parent user, add it.
4699            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4700                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4701                result.add(xpDomainInfo.resolveInfo);
4702            } else {
4703                // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4704                result.addAll(undefinedList);
4705                if (xpDomainInfo != null && (
4706                        xpDomainInfo.bestDomainVerificationStatus
4707                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4708                        || xpDomainInfo.bestDomainVerificationStatus
4709                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4710                    result.add(xpDomainInfo.resolveInfo);
4711                }
4712                // Also add Browsers (all of them or only the default one)
4713                if ((flags & MATCH_ALL) != 0) {
4714                    result.addAll(matchAllList);
4715                } else {
4716                    // Try to add the Default Browser if we can
4717                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4718                            UserHandle.myUserId());
4719                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4720                        boolean defaultBrowserFound = false;
4721                        final int browserCount = matchAllList.size();
4722                        for (int n=0; n<browserCount; n++) {
4723                            ResolveInfo browser = matchAllList.get(n);
4724                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4725                                result.add(browser);
4726                                defaultBrowserFound = true;
4727                                break;
4728                            }
4729                        }
4730                        if (!defaultBrowserFound) {
4731                            result.addAll(matchAllList);
4732                        }
4733                    } else {
4734                        result.addAll(matchAllList);
4735                    }
4736                }
4737
4738                // If there is nothing selected, add all candidates and remove the ones that the user
4739                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4740                if (result.size() == 0) {
4741                    result.addAll(candidates);
4742                    result.removeAll(neverList);
4743                }
4744            }
4745        }
4746        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4747            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4748                    result.size());
4749            for (ResolveInfo info : result) {
4750                Slog.v(TAG, "  + " + info.activityInfo);
4751            }
4752        }
4753        return result;
4754    }
4755
4756    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4757        int status = ps.getDomainVerificationStatusForUser(userId);
4758        // if none available, get the master status
4759        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4760            if (ps.getIntentFilterVerificationInfo() != null) {
4761                status = ps.getIntentFilterVerificationInfo().getStatus();
4762            }
4763        }
4764        return status;
4765    }
4766
4767    private ResolveInfo querySkipCurrentProfileIntents(
4768            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4769            int flags, int sourceUserId) {
4770        if (matchingFilters != null) {
4771            int size = matchingFilters.size();
4772            for (int i = 0; i < size; i ++) {
4773                CrossProfileIntentFilter filter = matchingFilters.get(i);
4774                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4775                    // Checking if there are activities in the target user that can handle the
4776                    // intent.
4777                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4778                            flags, sourceUserId);
4779                    if (resolveInfo != null) {
4780                        return resolveInfo;
4781                    }
4782                }
4783            }
4784        }
4785        return null;
4786    }
4787
4788    // Return matching ResolveInfo if any for skip current profile intent filters.
4789    private ResolveInfo queryCrossProfileIntents(
4790            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4791            int flags, int sourceUserId) {
4792        if (matchingFilters != null) {
4793            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4794            // match the same intent. For performance reasons, it is better not to
4795            // run queryIntent twice for the same userId
4796            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4797            int size = matchingFilters.size();
4798            for (int i = 0; i < size; i++) {
4799                CrossProfileIntentFilter filter = matchingFilters.get(i);
4800                int targetUserId = filter.getTargetUserId();
4801                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4802                        && !alreadyTriedUserIds.get(targetUserId)) {
4803                    // Checking if there are activities in the target user that can handle the
4804                    // intent.
4805                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4806                            flags, sourceUserId);
4807                    if (resolveInfo != null) return resolveInfo;
4808                    alreadyTriedUserIds.put(targetUserId, true);
4809                }
4810            }
4811        }
4812        return null;
4813    }
4814
4815    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4816            String resolvedType, int flags, int sourceUserId) {
4817        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4818                resolvedType, flags, filter.getTargetUserId());
4819        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4820            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4821        }
4822        return null;
4823    }
4824
4825    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4826            int sourceUserId, int targetUserId) {
4827        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4828        String className;
4829        if (targetUserId == UserHandle.USER_OWNER) {
4830            className = FORWARD_INTENT_TO_USER_OWNER;
4831        } else {
4832            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4833        }
4834        ComponentName forwardingActivityComponentName = new ComponentName(
4835                mAndroidApplication.packageName, className);
4836        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4837                sourceUserId);
4838        if (targetUserId == UserHandle.USER_OWNER) {
4839            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4840            forwardingResolveInfo.noResourceId = true;
4841        }
4842        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4843        forwardingResolveInfo.priority = 0;
4844        forwardingResolveInfo.preferredOrder = 0;
4845        forwardingResolveInfo.match = 0;
4846        forwardingResolveInfo.isDefault = true;
4847        forwardingResolveInfo.filter = filter;
4848        forwardingResolveInfo.targetUserId = targetUserId;
4849        return forwardingResolveInfo;
4850    }
4851
4852    @Override
4853    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4854            Intent[] specifics, String[] specificTypes, Intent intent,
4855            String resolvedType, int flags, int userId) {
4856        if (!sUserManager.exists(userId)) return Collections.emptyList();
4857        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4858                false, "query intent activity options");
4859        final String resultsAction = intent.getAction();
4860
4861        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4862                | PackageManager.GET_RESOLVED_FILTER, userId);
4863
4864        if (DEBUG_INTENT_MATCHING) {
4865            Log.v(TAG, "Query " + intent + ": " + results);
4866        }
4867
4868        int specificsPos = 0;
4869        int N;
4870
4871        // todo: note that the algorithm used here is O(N^2).  This
4872        // isn't a problem in our current environment, but if we start running
4873        // into situations where we have more than 5 or 10 matches then this
4874        // should probably be changed to something smarter...
4875
4876        // First we go through and resolve each of the specific items
4877        // that were supplied, taking care of removing any corresponding
4878        // duplicate items in the generic resolve list.
4879        if (specifics != null) {
4880            for (int i=0; i<specifics.length; i++) {
4881                final Intent sintent = specifics[i];
4882                if (sintent == null) {
4883                    continue;
4884                }
4885
4886                if (DEBUG_INTENT_MATCHING) {
4887                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4888                }
4889
4890                String action = sintent.getAction();
4891                if (resultsAction != null && resultsAction.equals(action)) {
4892                    // If this action was explicitly requested, then don't
4893                    // remove things that have it.
4894                    action = null;
4895                }
4896
4897                ResolveInfo ri = null;
4898                ActivityInfo ai = null;
4899
4900                ComponentName comp = sintent.getComponent();
4901                if (comp == null) {
4902                    ri = resolveIntent(
4903                        sintent,
4904                        specificTypes != null ? specificTypes[i] : null,
4905                            flags, userId);
4906                    if (ri == null) {
4907                        continue;
4908                    }
4909                    if (ri == mResolveInfo) {
4910                        // ACK!  Must do something better with this.
4911                    }
4912                    ai = ri.activityInfo;
4913                    comp = new ComponentName(ai.applicationInfo.packageName,
4914                            ai.name);
4915                } else {
4916                    ai = getActivityInfo(comp, flags, userId);
4917                    if (ai == null) {
4918                        continue;
4919                    }
4920                }
4921
4922                // Look for any generic query activities that are duplicates
4923                // of this specific one, and remove them from the results.
4924                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4925                N = results.size();
4926                int j;
4927                for (j=specificsPos; j<N; j++) {
4928                    ResolveInfo sri = results.get(j);
4929                    if ((sri.activityInfo.name.equals(comp.getClassName())
4930                            && sri.activityInfo.applicationInfo.packageName.equals(
4931                                    comp.getPackageName()))
4932                        || (action != null && sri.filter.matchAction(action))) {
4933                        results.remove(j);
4934                        if (DEBUG_INTENT_MATCHING) Log.v(
4935                            TAG, "Removing duplicate item from " + j
4936                            + " due to specific " + specificsPos);
4937                        if (ri == null) {
4938                            ri = sri;
4939                        }
4940                        j--;
4941                        N--;
4942                    }
4943                }
4944
4945                // Add this specific item to its proper place.
4946                if (ri == null) {
4947                    ri = new ResolveInfo();
4948                    ri.activityInfo = ai;
4949                }
4950                results.add(specificsPos, ri);
4951                ri.specificIndex = i;
4952                specificsPos++;
4953            }
4954        }
4955
4956        // Now we go through the remaining generic results and remove any
4957        // duplicate actions that are found here.
4958        N = results.size();
4959        for (int i=specificsPos; i<N-1; i++) {
4960            final ResolveInfo rii = results.get(i);
4961            if (rii.filter == null) {
4962                continue;
4963            }
4964
4965            // Iterate over all of the actions of this result's intent
4966            // filter...  typically this should be just one.
4967            final Iterator<String> it = rii.filter.actionsIterator();
4968            if (it == null) {
4969                continue;
4970            }
4971            while (it.hasNext()) {
4972                final String action = it.next();
4973                if (resultsAction != null && resultsAction.equals(action)) {
4974                    // If this action was explicitly requested, then don't
4975                    // remove things that have it.
4976                    continue;
4977                }
4978                for (int j=i+1; j<N; j++) {
4979                    final ResolveInfo rij = results.get(j);
4980                    if (rij.filter != null && rij.filter.hasAction(action)) {
4981                        results.remove(j);
4982                        if (DEBUG_INTENT_MATCHING) Log.v(
4983                            TAG, "Removing duplicate item from " + j
4984                            + " due to action " + action + " at " + i);
4985                        j--;
4986                        N--;
4987                    }
4988                }
4989            }
4990
4991            // If the caller didn't request filter information, drop it now
4992            // so we don't have to marshall/unmarshall it.
4993            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4994                rii.filter = null;
4995            }
4996        }
4997
4998        // Filter out the caller activity if so requested.
4999        if (caller != null) {
5000            N = results.size();
5001            for (int i=0; i<N; i++) {
5002                ActivityInfo ainfo = results.get(i).activityInfo;
5003                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5004                        && caller.getClassName().equals(ainfo.name)) {
5005                    results.remove(i);
5006                    break;
5007                }
5008            }
5009        }
5010
5011        // If the caller didn't request filter information,
5012        // drop them now so we don't have to
5013        // marshall/unmarshall it.
5014        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5015            N = results.size();
5016            for (int i=0; i<N; i++) {
5017                results.get(i).filter = null;
5018            }
5019        }
5020
5021        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5022        return results;
5023    }
5024
5025    @Override
5026    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5027            int userId) {
5028        if (!sUserManager.exists(userId)) return Collections.emptyList();
5029        ComponentName comp = intent.getComponent();
5030        if (comp == null) {
5031            if (intent.getSelector() != null) {
5032                intent = intent.getSelector();
5033                comp = intent.getComponent();
5034            }
5035        }
5036        if (comp != null) {
5037            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5038            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5039            if (ai != null) {
5040                ResolveInfo ri = new ResolveInfo();
5041                ri.activityInfo = ai;
5042                list.add(ri);
5043            }
5044            return list;
5045        }
5046
5047        // reader
5048        synchronized (mPackages) {
5049            String pkgName = intent.getPackage();
5050            if (pkgName == null) {
5051                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5052            }
5053            final PackageParser.Package pkg = mPackages.get(pkgName);
5054            if (pkg != null) {
5055                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5056                        userId);
5057            }
5058            return null;
5059        }
5060    }
5061
5062    @Override
5063    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5064        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5065        if (!sUserManager.exists(userId)) return null;
5066        if (query != null) {
5067            if (query.size() >= 1) {
5068                // If there is more than one service with the same priority,
5069                // just arbitrarily pick the first one.
5070                return query.get(0);
5071            }
5072        }
5073        return null;
5074    }
5075
5076    @Override
5077    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5078            int userId) {
5079        if (!sUserManager.exists(userId)) return Collections.emptyList();
5080        ComponentName comp = intent.getComponent();
5081        if (comp == null) {
5082            if (intent.getSelector() != null) {
5083                intent = intent.getSelector();
5084                comp = intent.getComponent();
5085            }
5086        }
5087        if (comp != null) {
5088            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5089            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5090            if (si != null) {
5091                final ResolveInfo ri = new ResolveInfo();
5092                ri.serviceInfo = si;
5093                list.add(ri);
5094            }
5095            return list;
5096        }
5097
5098        // reader
5099        synchronized (mPackages) {
5100            String pkgName = intent.getPackage();
5101            if (pkgName == null) {
5102                return mServices.queryIntent(intent, resolvedType, flags, userId);
5103            }
5104            final PackageParser.Package pkg = mPackages.get(pkgName);
5105            if (pkg != null) {
5106                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5107                        userId);
5108            }
5109            return null;
5110        }
5111    }
5112
5113    @Override
5114    public List<ResolveInfo> queryIntentContentProviders(
5115            Intent intent, String resolvedType, int flags, int userId) {
5116        if (!sUserManager.exists(userId)) return Collections.emptyList();
5117        ComponentName comp = intent.getComponent();
5118        if (comp == null) {
5119            if (intent.getSelector() != null) {
5120                intent = intent.getSelector();
5121                comp = intent.getComponent();
5122            }
5123        }
5124        if (comp != null) {
5125            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5126            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5127            if (pi != null) {
5128                final ResolveInfo ri = new ResolveInfo();
5129                ri.providerInfo = pi;
5130                list.add(ri);
5131            }
5132            return list;
5133        }
5134
5135        // reader
5136        synchronized (mPackages) {
5137            String pkgName = intent.getPackage();
5138            if (pkgName == null) {
5139                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5140            }
5141            final PackageParser.Package pkg = mPackages.get(pkgName);
5142            if (pkg != null) {
5143                return mProviders.queryIntentForPackage(
5144                        intent, resolvedType, flags, pkg.providers, userId);
5145            }
5146            return null;
5147        }
5148    }
5149
5150    @Override
5151    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5152        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5153
5154        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5155
5156        // writer
5157        synchronized (mPackages) {
5158            ArrayList<PackageInfo> list;
5159            if (listUninstalled) {
5160                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5161                for (PackageSetting ps : mSettings.mPackages.values()) {
5162                    PackageInfo pi;
5163                    if (ps.pkg != null) {
5164                        pi = generatePackageInfo(ps.pkg, flags, userId);
5165                    } else {
5166                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5167                    }
5168                    if (pi != null) {
5169                        list.add(pi);
5170                    }
5171                }
5172            } else {
5173                list = new ArrayList<PackageInfo>(mPackages.size());
5174                for (PackageParser.Package p : mPackages.values()) {
5175                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5176                    if (pi != null) {
5177                        list.add(pi);
5178                    }
5179                }
5180            }
5181
5182            return new ParceledListSlice<PackageInfo>(list);
5183        }
5184    }
5185
5186    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5187            String[] permissions, boolean[] tmp, int flags, int userId) {
5188        int numMatch = 0;
5189        final PermissionsState permissionsState = ps.getPermissionsState();
5190        for (int i=0; i<permissions.length; i++) {
5191            final String permission = permissions[i];
5192            if (permissionsState.hasPermission(permission, userId)) {
5193                tmp[i] = true;
5194                numMatch++;
5195            } else {
5196                tmp[i] = false;
5197            }
5198        }
5199        if (numMatch == 0) {
5200            return;
5201        }
5202        PackageInfo pi;
5203        if (ps.pkg != null) {
5204            pi = generatePackageInfo(ps.pkg, flags, userId);
5205        } else {
5206            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5207        }
5208        // The above might return null in cases of uninstalled apps or install-state
5209        // skew across users/profiles.
5210        if (pi != null) {
5211            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5212                if (numMatch == permissions.length) {
5213                    pi.requestedPermissions = permissions;
5214                } else {
5215                    pi.requestedPermissions = new String[numMatch];
5216                    numMatch = 0;
5217                    for (int i=0; i<permissions.length; i++) {
5218                        if (tmp[i]) {
5219                            pi.requestedPermissions[numMatch] = permissions[i];
5220                            numMatch++;
5221                        }
5222                    }
5223                }
5224            }
5225            list.add(pi);
5226        }
5227    }
5228
5229    @Override
5230    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5231            String[] permissions, int flags, int userId) {
5232        if (!sUserManager.exists(userId)) return null;
5233        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5234
5235        // writer
5236        synchronized (mPackages) {
5237            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5238            boolean[] tmpBools = new boolean[permissions.length];
5239            if (listUninstalled) {
5240                for (PackageSetting ps : mSettings.mPackages.values()) {
5241                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5242                }
5243            } else {
5244                for (PackageParser.Package pkg : mPackages.values()) {
5245                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5246                    if (ps != null) {
5247                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5248                                userId);
5249                    }
5250                }
5251            }
5252
5253            return new ParceledListSlice<PackageInfo>(list);
5254        }
5255    }
5256
5257    @Override
5258    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5259        if (!sUserManager.exists(userId)) return null;
5260        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5261
5262        // writer
5263        synchronized (mPackages) {
5264            ArrayList<ApplicationInfo> list;
5265            if (listUninstalled) {
5266                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5267                for (PackageSetting ps : mSettings.mPackages.values()) {
5268                    ApplicationInfo ai;
5269                    if (ps.pkg != null) {
5270                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5271                                ps.readUserState(userId), userId);
5272                    } else {
5273                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5274                    }
5275                    if (ai != null) {
5276                        list.add(ai);
5277                    }
5278                }
5279            } else {
5280                list = new ArrayList<ApplicationInfo>(mPackages.size());
5281                for (PackageParser.Package p : mPackages.values()) {
5282                    if (p.mExtras != null) {
5283                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5284                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5285                        if (ai != null) {
5286                            list.add(ai);
5287                        }
5288                    }
5289                }
5290            }
5291
5292            return new ParceledListSlice<ApplicationInfo>(list);
5293        }
5294    }
5295
5296    public List<ApplicationInfo> getPersistentApplications(int flags) {
5297        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5298
5299        // reader
5300        synchronized (mPackages) {
5301            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5302            final int userId = UserHandle.getCallingUserId();
5303            while (i.hasNext()) {
5304                final PackageParser.Package p = i.next();
5305                if (p.applicationInfo != null
5306                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5307                        && (!mSafeMode || isSystemApp(p))) {
5308                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5309                    if (ps != null) {
5310                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5311                                ps.readUserState(userId), userId);
5312                        if (ai != null) {
5313                            finalList.add(ai);
5314                        }
5315                    }
5316                }
5317            }
5318        }
5319
5320        return finalList;
5321    }
5322
5323    @Override
5324    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5325        if (!sUserManager.exists(userId)) return null;
5326        // reader
5327        synchronized (mPackages) {
5328            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5329            PackageSetting ps = provider != null
5330                    ? mSettings.mPackages.get(provider.owner.packageName)
5331                    : null;
5332            return ps != null
5333                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5334                    && (!mSafeMode || (provider.info.applicationInfo.flags
5335                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5336                    ? PackageParser.generateProviderInfo(provider, flags,
5337                            ps.readUserState(userId), userId)
5338                    : null;
5339        }
5340    }
5341
5342    /**
5343     * @deprecated
5344     */
5345    @Deprecated
5346    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5347        // reader
5348        synchronized (mPackages) {
5349            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5350                    .entrySet().iterator();
5351            final int userId = UserHandle.getCallingUserId();
5352            while (i.hasNext()) {
5353                Map.Entry<String, PackageParser.Provider> entry = i.next();
5354                PackageParser.Provider p = entry.getValue();
5355                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5356
5357                if (ps != null && p.syncable
5358                        && (!mSafeMode || (p.info.applicationInfo.flags
5359                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5360                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5361                            ps.readUserState(userId), userId);
5362                    if (info != null) {
5363                        outNames.add(entry.getKey());
5364                        outInfo.add(info);
5365                    }
5366                }
5367            }
5368        }
5369    }
5370
5371    @Override
5372    public List<ProviderInfo> queryContentProviders(String processName,
5373            int uid, int flags) {
5374        ArrayList<ProviderInfo> finalList = null;
5375        // reader
5376        synchronized (mPackages) {
5377            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5378            final int userId = processName != null ?
5379                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5380            while (i.hasNext()) {
5381                final PackageParser.Provider p = i.next();
5382                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5383                if (ps != null && p.info.authority != null
5384                        && (processName == null
5385                                || (p.info.processName.equals(processName)
5386                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5387                        && mSettings.isEnabledLPr(p.info, flags, userId)
5388                        && (!mSafeMode
5389                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5390                    if (finalList == null) {
5391                        finalList = new ArrayList<ProviderInfo>(3);
5392                    }
5393                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5394                            ps.readUserState(userId), userId);
5395                    if (info != null) {
5396                        finalList.add(info);
5397                    }
5398                }
5399            }
5400        }
5401
5402        if (finalList != null) {
5403            Collections.sort(finalList, mProviderInitOrderSorter);
5404        }
5405
5406        return finalList;
5407    }
5408
5409    @Override
5410    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5411            int flags) {
5412        // reader
5413        synchronized (mPackages) {
5414            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5415            return PackageParser.generateInstrumentationInfo(i, flags);
5416        }
5417    }
5418
5419    @Override
5420    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5421            int flags) {
5422        ArrayList<InstrumentationInfo> finalList =
5423            new ArrayList<InstrumentationInfo>();
5424
5425        // reader
5426        synchronized (mPackages) {
5427            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5428            while (i.hasNext()) {
5429                final PackageParser.Instrumentation p = i.next();
5430                if (targetPackage == null
5431                        || targetPackage.equals(p.info.targetPackage)) {
5432                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5433                            flags);
5434                    if (ii != null) {
5435                        finalList.add(ii);
5436                    }
5437                }
5438            }
5439        }
5440
5441        return finalList;
5442    }
5443
5444    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5445        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5446        if (overlays == null) {
5447            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5448            return;
5449        }
5450        for (PackageParser.Package opkg : overlays.values()) {
5451            // Not much to do if idmap fails: we already logged the error
5452            // and we certainly don't want to abort installation of pkg simply
5453            // because an overlay didn't fit properly. For these reasons,
5454            // ignore the return value of createIdmapForPackagePairLI.
5455            createIdmapForPackagePairLI(pkg, opkg);
5456        }
5457    }
5458
5459    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5460            PackageParser.Package opkg) {
5461        if (!opkg.mTrustedOverlay) {
5462            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5463                    opkg.baseCodePath + ": overlay not trusted");
5464            return false;
5465        }
5466        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5467        if (overlaySet == null) {
5468            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5469                    opkg.baseCodePath + " but target package has no known overlays");
5470            return false;
5471        }
5472        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5473        // TODO: generate idmap for split APKs
5474        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5475            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5476                    + opkg.baseCodePath);
5477            return false;
5478        }
5479        PackageParser.Package[] overlayArray =
5480            overlaySet.values().toArray(new PackageParser.Package[0]);
5481        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5482            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5483                return p1.mOverlayPriority - p2.mOverlayPriority;
5484            }
5485        };
5486        Arrays.sort(overlayArray, cmp);
5487
5488        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5489        int i = 0;
5490        for (PackageParser.Package p : overlayArray) {
5491            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5492        }
5493        return true;
5494    }
5495
5496    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5497        final File[] files = dir.listFiles();
5498        if (ArrayUtils.isEmpty(files)) {
5499            Log.d(TAG, "No files in app dir " + dir);
5500            return;
5501        }
5502
5503        if (DEBUG_PACKAGE_SCANNING) {
5504            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5505                    + " flags=0x" + Integer.toHexString(parseFlags));
5506        }
5507
5508        for (File file : files) {
5509            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5510                    && !PackageInstallerService.isStageName(file.getName());
5511            if (!isPackage) {
5512                // Ignore entries which are not packages
5513                continue;
5514            }
5515            try {
5516                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5517                        scanFlags, currentTime, null);
5518            } catch (PackageManagerException e) {
5519                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5520
5521                // Delete invalid userdata apps
5522                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5523                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5524                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5525                    if (file.isDirectory()) {
5526                        mInstaller.rmPackageDir(file.getAbsolutePath());
5527                    } else {
5528                        file.delete();
5529                    }
5530                }
5531            }
5532        }
5533    }
5534
5535    private static File getSettingsProblemFile() {
5536        File dataDir = Environment.getDataDirectory();
5537        File systemDir = new File(dataDir, "system");
5538        File fname = new File(systemDir, "uiderrors.txt");
5539        return fname;
5540    }
5541
5542    static void reportSettingsProblem(int priority, String msg) {
5543        logCriticalInfo(priority, msg);
5544    }
5545
5546    static void logCriticalInfo(int priority, String msg) {
5547        Slog.println(priority, TAG, msg);
5548        EventLogTags.writePmCriticalInfo(msg);
5549        try {
5550            File fname = getSettingsProblemFile();
5551            FileOutputStream out = new FileOutputStream(fname, true);
5552            PrintWriter pw = new FastPrintWriter(out);
5553            SimpleDateFormat formatter = new SimpleDateFormat();
5554            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5555            pw.println(dateString + ": " + msg);
5556            pw.close();
5557            FileUtils.setPermissions(
5558                    fname.toString(),
5559                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5560                    -1, -1);
5561        } catch (java.io.IOException e) {
5562        }
5563    }
5564
5565    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5566            PackageParser.Package pkg, File srcFile, int parseFlags)
5567            throws PackageManagerException {
5568        if (ps != null
5569                && ps.codePath.equals(srcFile)
5570                && ps.timeStamp == srcFile.lastModified()
5571                && !isCompatSignatureUpdateNeeded(pkg)
5572                && !isRecoverSignatureUpdateNeeded(pkg)) {
5573            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5574            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5575            ArraySet<PublicKey> signingKs;
5576            synchronized (mPackages) {
5577                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5578            }
5579            if (ps.signatures.mSignatures != null
5580                    && ps.signatures.mSignatures.length != 0
5581                    && signingKs != null) {
5582                // Optimization: reuse the existing cached certificates
5583                // if the package appears to be unchanged.
5584                pkg.mSignatures = ps.signatures.mSignatures;
5585                pkg.mSigningKeys = signingKs;
5586                return;
5587            }
5588
5589            Slog.w(TAG, "PackageSetting for " + ps.name
5590                    + " is missing signatures.  Collecting certs again to recover them.");
5591        } else {
5592            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5593        }
5594
5595        try {
5596            pp.collectCertificates(pkg, parseFlags);
5597            pp.collectManifestDigest(pkg);
5598        } catch (PackageParserException e) {
5599            throw PackageManagerException.from(e);
5600        }
5601    }
5602
5603    /*
5604     *  Scan a package and return the newly parsed package.
5605     *  Returns null in case of errors and the error code is stored in mLastScanError
5606     */
5607    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5608            long currentTime, UserHandle user) throws PackageManagerException {
5609        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5610        parseFlags |= mDefParseFlags;
5611        PackageParser pp = new PackageParser();
5612        pp.setSeparateProcesses(mSeparateProcesses);
5613        pp.setOnlyCoreApps(mOnlyCore);
5614        pp.setDisplayMetrics(mMetrics);
5615
5616        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5617            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5618        }
5619
5620        final PackageParser.Package pkg;
5621        try {
5622            pkg = pp.parsePackage(scanFile, parseFlags);
5623        } catch (PackageParserException e) {
5624            throw PackageManagerException.from(e);
5625        }
5626
5627        PackageSetting ps = null;
5628        PackageSetting updatedPkg;
5629        // reader
5630        synchronized (mPackages) {
5631            // Look to see if we already know about this package.
5632            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5633            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5634                // This package has been renamed to its original name.  Let's
5635                // use that.
5636                ps = mSettings.peekPackageLPr(oldName);
5637            }
5638            // If there was no original package, see one for the real package name.
5639            if (ps == null) {
5640                ps = mSettings.peekPackageLPr(pkg.packageName);
5641            }
5642            // Check to see if this package could be hiding/updating a system
5643            // package.  Must look for it either under the original or real
5644            // package name depending on our state.
5645            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5646            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5647        }
5648        boolean updatedPkgBetter = false;
5649        // First check if this is a system package that may involve an update
5650        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5651            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5652            // it needs to drop FLAG_PRIVILEGED.
5653            if (locationIsPrivileged(scanFile)) {
5654                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5655            } else {
5656                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5657            }
5658
5659            if (ps != null && !ps.codePath.equals(scanFile)) {
5660                // The path has changed from what was last scanned...  check the
5661                // version of the new path against what we have stored to determine
5662                // what to do.
5663                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5664                if (pkg.mVersionCode <= ps.versionCode) {
5665                    // The system package has been updated and the code path does not match
5666                    // Ignore entry. Skip it.
5667                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5668                            + " ignored: updated version " + ps.versionCode
5669                            + " better than this " + pkg.mVersionCode);
5670                    if (!updatedPkg.codePath.equals(scanFile)) {
5671                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5672                                + ps.name + " changing from " + updatedPkg.codePathString
5673                                + " to " + scanFile);
5674                        updatedPkg.codePath = scanFile;
5675                        updatedPkg.codePathString = scanFile.toString();
5676                        updatedPkg.resourcePath = scanFile;
5677                        updatedPkg.resourcePathString = scanFile.toString();
5678                    }
5679                    updatedPkg.pkg = pkg;
5680                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5681                            "Package " + ps.name + " at " + scanFile
5682                                    + " ignored: updated version " + ps.versionCode
5683                                    + " better than this " + pkg.mVersionCode);
5684                } else {
5685                    // The current app on the system partition is better than
5686                    // what we have updated to on the data partition; switch
5687                    // back to the system partition version.
5688                    // At this point, its safely assumed that package installation for
5689                    // apps in system partition will go through. If not there won't be a working
5690                    // version of the app
5691                    // writer
5692                    synchronized (mPackages) {
5693                        // Just remove the loaded entries from package lists.
5694                        mPackages.remove(ps.name);
5695                    }
5696
5697                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5698                            + " reverting from " + ps.codePathString
5699                            + ": new version " + pkg.mVersionCode
5700                            + " better than installed " + ps.versionCode);
5701
5702                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5703                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5704                    synchronized (mInstallLock) {
5705                        args.cleanUpResourcesLI();
5706                    }
5707                    synchronized (mPackages) {
5708                        mSettings.enableSystemPackageLPw(ps.name);
5709                    }
5710                    updatedPkgBetter = true;
5711                }
5712            }
5713        }
5714
5715        if (updatedPkg != null) {
5716            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5717            // initially
5718            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5719
5720            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5721            // flag set initially
5722            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5723                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5724            }
5725        }
5726
5727        // Verify certificates against what was last scanned
5728        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5729
5730        /*
5731         * A new system app appeared, but we already had a non-system one of the
5732         * same name installed earlier.
5733         */
5734        boolean shouldHideSystemApp = false;
5735        if (updatedPkg == null && ps != null
5736                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5737            /*
5738             * Check to make sure the signatures match first. If they don't,
5739             * wipe the installed application and its data.
5740             */
5741            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5742                    != PackageManager.SIGNATURE_MATCH) {
5743                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5744                        + " signatures don't match existing userdata copy; removing");
5745                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5746                ps = null;
5747            } else {
5748                /*
5749                 * If the newly-added system app is an older version than the
5750                 * already installed version, hide it. It will be scanned later
5751                 * and re-added like an update.
5752                 */
5753                if (pkg.mVersionCode <= ps.versionCode) {
5754                    shouldHideSystemApp = true;
5755                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5756                            + " but new version " + pkg.mVersionCode + " better than installed "
5757                            + ps.versionCode + "; hiding system");
5758                } else {
5759                    /*
5760                     * The newly found system app is a newer version that the
5761                     * one previously installed. Simply remove the
5762                     * already-installed application and replace it with our own
5763                     * while keeping the application data.
5764                     */
5765                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5766                            + " reverting from " + ps.codePathString + ": new version "
5767                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5768                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5769                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5770                    synchronized (mInstallLock) {
5771                        args.cleanUpResourcesLI();
5772                    }
5773                }
5774            }
5775        }
5776
5777        // The apk is forward locked (not public) if its code and resources
5778        // are kept in different files. (except for app in either system or
5779        // vendor path).
5780        // TODO grab this value from PackageSettings
5781        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5782            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5783                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5784            }
5785        }
5786
5787        // TODO: extend to support forward-locked splits
5788        String resourcePath = null;
5789        String baseResourcePath = null;
5790        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5791            if (ps != null && ps.resourcePathString != null) {
5792                resourcePath = ps.resourcePathString;
5793                baseResourcePath = ps.resourcePathString;
5794            } else {
5795                // Should not happen at all. Just log an error.
5796                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5797            }
5798        } else {
5799            resourcePath = pkg.codePath;
5800            baseResourcePath = pkg.baseCodePath;
5801        }
5802
5803        // Set application objects path explicitly.
5804        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5805        pkg.applicationInfo.setCodePath(pkg.codePath);
5806        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5807        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5808        pkg.applicationInfo.setResourcePath(resourcePath);
5809        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5810        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5811
5812        // Note that we invoke the following method only if we are about to unpack an application
5813        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5814                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5815
5816        /*
5817         * If the system app should be overridden by a previously installed
5818         * data, hide the system app now and let the /data/app scan pick it up
5819         * again.
5820         */
5821        if (shouldHideSystemApp) {
5822            synchronized (mPackages) {
5823                /*
5824                 * We have to grant systems permissions before we hide, because
5825                 * grantPermissions will assume the package update is trying to
5826                 * expand its permissions.
5827                 */
5828                grantPermissionsLPw(pkg, true, pkg.packageName);
5829                mSettings.disableSystemPackageLPw(pkg.packageName);
5830            }
5831        }
5832
5833        return scannedPkg;
5834    }
5835
5836    private static String fixProcessName(String defProcessName,
5837            String processName, int uid) {
5838        if (processName == null) {
5839            return defProcessName;
5840        }
5841        return processName;
5842    }
5843
5844    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5845            throws PackageManagerException {
5846        if (pkgSetting.signatures.mSignatures != null) {
5847            // Already existing package. Make sure signatures match
5848            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5849                    == PackageManager.SIGNATURE_MATCH;
5850            if (!match) {
5851                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5852                        == PackageManager.SIGNATURE_MATCH;
5853            }
5854            if (!match) {
5855                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5856                        == PackageManager.SIGNATURE_MATCH;
5857            }
5858            if (!match) {
5859                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5860                        + pkg.packageName + " signatures do not match the "
5861                        + "previously installed version; ignoring!");
5862            }
5863        }
5864
5865        // Check for shared user signatures
5866        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5867            // Already existing package. Make sure signatures match
5868            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5869                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5870            if (!match) {
5871                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5872                        == PackageManager.SIGNATURE_MATCH;
5873            }
5874            if (!match) {
5875                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5876                        == PackageManager.SIGNATURE_MATCH;
5877            }
5878            if (!match) {
5879                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5880                        "Package " + pkg.packageName
5881                        + " has no signatures that match those in shared user "
5882                        + pkgSetting.sharedUser.name + "; ignoring!");
5883            }
5884        }
5885    }
5886
5887    /**
5888     * Enforces that only the system UID or root's UID can call a method exposed
5889     * via Binder.
5890     *
5891     * @param message used as message if SecurityException is thrown
5892     * @throws SecurityException if the caller is not system or root
5893     */
5894    private static final void enforceSystemOrRoot(String message) {
5895        final int uid = Binder.getCallingUid();
5896        if (uid != Process.SYSTEM_UID && uid != 0) {
5897            throw new SecurityException(message);
5898        }
5899    }
5900
5901    @Override
5902    public void performBootDexOpt() {
5903        enforceSystemOrRoot("Only the system can request dexopt be performed");
5904
5905        // Before everything else, see whether we need to fstrim.
5906        try {
5907            IMountService ms = PackageHelper.getMountService();
5908            if (ms != null) {
5909                final boolean isUpgrade = isUpgrade();
5910                boolean doTrim = isUpgrade;
5911                if (doTrim) {
5912                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5913                } else {
5914                    final long interval = android.provider.Settings.Global.getLong(
5915                            mContext.getContentResolver(),
5916                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5917                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5918                    if (interval > 0) {
5919                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5920                        if (timeSinceLast > interval) {
5921                            doTrim = true;
5922                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5923                                    + "; running immediately");
5924                        }
5925                    }
5926                }
5927                if (doTrim) {
5928                    if (!isFirstBoot()) {
5929                        try {
5930                            ActivityManagerNative.getDefault().showBootMessage(
5931                                    mContext.getResources().getString(
5932                                            R.string.android_upgrading_fstrim), true);
5933                        } catch (RemoteException e) {
5934                        }
5935                    }
5936                    ms.runMaintenance();
5937                }
5938            } else {
5939                Slog.e(TAG, "Mount service unavailable!");
5940            }
5941        } catch (RemoteException e) {
5942            // Can't happen; MountService is local
5943        }
5944
5945        final ArraySet<PackageParser.Package> pkgs;
5946        synchronized (mPackages) {
5947            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5948        }
5949
5950        if (pkgs != null) {
5951            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5952            // in case the device runs out of space.
5953            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5954            // Give priority to core apps.
5955            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5956                PackageParser.Package pkg = it.next();
5957                if (pkg.coreApp) {
5958                    if (DEBUG_DEXOPT) {
5959                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5960                    }
5961                    sortedPkgs.add(pkg);
5962                    it.remove();
5963                }
5964            }
5965            // Give priority to system apps that listen for pre boot complete.
5966            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5967            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5968            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5969                PackageParser.Package pkg = it.next();
5970                if (pkgNames.contains(pkg.packageName)) {
5971                    if (DEBUG_DEXOPT) {
5972                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5973                    }
5974                    sortedPkgs.add(pkg);
5975                    it.remove();
5976                }
5977            }
5978            // Give priority to system apps.
5979            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5980                PackageParser.Package pkg = it.next();
5981                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5982                    if (DEBUG_DEXOPT) {
5983                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5984                    }
5985                    sortedPkgs.add(pkg);
5986                    it.remove();
5987                }
5988            }
5989            // Give priority to updated system apps.
5990            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5991                PackageParser.Package pkg = it.next();
5992                if (pkg.isUpdatedSystemApp()) {
5993                    if (DEBUG_DEXOPT) {
5994                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5995                    }
5996                    sortedPkgs.add(pkg);
5997                    it.remove();
5998                }
5999            }
6000            // Give priority to apps that listen for boot complete.
6001            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
6002            pkgNames = getPackageNamesForIntent(intent);
6003            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6004                PackageParser.Package pkg = it.next();
6005                if (pkgNames.contains(pkg.packageName)) {
6006                    if (DEBUG_DEXOPT) {
6007                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
6008                    }
6009                    sortedPkgs.add(pkg);
6010                    it.remove();
6011                }
6012            }
6013            // Filter out packages that aren't recently used.
6014            filterRecentlyUsedApps(pkgs);
6015            // Add all remaining apps.
6016            for (PackageParser.Package pkg : pkgs) {
6017                if (DEBUG_DEXOPT) {
6018                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6019                }
6020                sortedPkgs.add(pkg);
6021            }
6022
6023            // If we want to be lazy, filter everything that wasn't recently used.
6024            if (mLazyDexOpt) {
6025                filterRecentlyUsedApps(sortedPkgs);
6026            }
6027
6028            int i = 0;
6029            int total = sortedPkgs.size();
6030            File dataDir = Environment.getDataDirectory();
6031            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6032            if (lowThreshold == 0) {
6033                throw new IllegalStateException("Invalid low memory threshold");
6034            }
6035            for (PackageParser.Package pkg : sortedPkgs) {
6036                long usableSpace = dataDir.getUsableSpace();
6037                if (usableSpace < lowThreshold) {
6038                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6039                    break;
6040                }
6041                performBootDexOpt(pkg, ++i, total);
6042            }
6043        }
6044    }
6045
6046    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6047        // Filter out packages that aren't recently used.
6048        //
6049        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6050        // should do a full dexopt.
6051        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6052            int total = pkgs.size();
6053            int skipped = 0;
6054            long now = System.currentTimeMillis();
6055            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6056                PackageParser.Package pkg = i.next();
6057                long then = pkg.mLastPackageUsageTimeInMills;
6058                if (then + mDexOptLRUThresholdInMills < now) {
6059                    if (DEBUG_DEXOPT) {
6060                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6061                              ((then == 0) ? "never" : new Date(then)));
6062                    }
6063                    i.remove();
6064                    skipped++;
6065                }
6066            }
6067            if (DEBUG_DEXOPT) {
6068                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6069            }
6070        }
6071    }
6072
6073    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6074        List<ResolveInfo> ris = null;
6075        try {
6076            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6077                    intent, null, 0, UserHandle.USER_OWNER);
6078        } catch (RemoteException e) {
6079        }
6080        ArraySet<String> pkgNames = new ArraySet<String>();
6081        if (ris != null) {
6082            for (ResolveInfo ri : ris) {
6083                pkgNames.add(ri.activityInfo.packageName);
6084            }
6085        }
6086        return pkgNames;
6087    }
6088
6089    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6090        if (DEBUG_DEXOPT) {
6091            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6092        }
6093        if (!isFirstBoot()) {
6094            try {
6095                ActivityManagerNative.getDefault().showBootMessage(
6096                        mContext.getResources().getString(R.string.android_upgrading_apk,
6097                                curr, total), true);
6098            } catch (RemoteException e) {
6099            }
6100        }
6101        PackageParser.Package p = pkg;
6102        synchronized (mInstallLock) {
6103            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6104                    false /* force dex */, false /* defer */, true /* include dependencies */);
6105        }
6106    }
6107
6108    @Override
6109    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6110        return performDexOpt(packageName, instructionSet, false);
6111    }
6112
6113    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6114        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6115        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6116        if (!dexopt && !updateUsage) {
6117            // We aren't going to dexopt or update usage, so bail early.
6118            return false;
6119        }
6120        PackageParser.Package p;
6121        final String targetInstructionSet;
6122        synchronized (mPackages) {
6123            p = mPackages.get(packageName);
6124            if (p == null) {
6125                return false;
6126            }
6127            if (updateUsage) {
6128                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6129            }
6130            mPackageUsage.write(false);
6131            if (!dexopt) {
6132                // We aren't going to dexopt, so bail early.
6133                return false;
6134            }
6135
6136            targetInstructionSet = instructionSet != null ? instructionSet :
6137                    getPrimaryInstructionSet(p.applicationInfo);
6138            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6139                return false;
6140            }
6141        }
6142
6143        synchronized (mInstallLock) {
6144            final String[] instructionSets = new String[] { targetInstructionSet };
6145            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6146                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
6147            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6148        }
6149    }
6150
6151    public ArraySet<String> getPackagesThatNeedDexOpt() {
6152        ArraySet<String> pkgs = null;
6153        synchronized (mPackages) {
6154            for (PackageParser.Package p : mPackages.values()) {
6155                if (DEBUG_DEXOPT) {
6156                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6157                }
6158                if (!p.mDexOptPerformed.isEmpty()) {
6159                    continue;
6160                }
6161                if (pkgs == null) {
6162                    pkgs = new ArraySet<String>();
6163                }
6164                pkgs.add(p.packageName);
6165            }
6166        }
6167        return pkgs;
6168    }
6169
6170    public void shutdown() {
6171        mPackageUsage.write(true);
6172    }
6173
6174    @Override
6175    public void forceDexOpt(String packageName) {
6176        enforceSystemOrRoot("forceDexOpt");
6177
6178        PackageParser.Package pkg;
6179        synchronized (mPackages) {
6180            pkg = mPackages.get(packageName);
6181            if (pkg == null) {
6182                throw new IllegalArgumentException("Missing package: " + packageName);
6183            }
6184        }
6185
6186        synchronized (mInstallLock) {
6187            final String[] instructionSets = new String[] {
6188                    getPrimaryInstructionSet(pkg.applicationInfo) };
6189            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6190                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
6191            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6192                throw new IllegalStateException("Failed to dexopt: " + res);
6193            }
6194        }
6195    }
6196
6197    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6198        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6199            Slog.w(TAG, "Unable to update from " + oldPkg.name
6200                    + " to " + newPkg.packageName
6201                    + ": old package not in system partition");
6202            return false;
6203        } else if (mPackages.get(oldPkg.name) != null) {
6204            Slog.w(TAG, "Unable to update from " + oldPkg.name
6205                    + " to " + newPkg.packageName
6206                    + ": old package still exists");
6207            return false;
6208        }
6209        return true;
6210    }
6211
6212    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6213        int[] users = sUserManager.getUserIds();
6214        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6215        if (res < 0) {
6216            return res;
6217        }
6218        for (int user : users) {
6219            if (user != 0) {
6220                res = mInstaller.createUserData(volumeUuid, packageName,
6221                        UserHandle.getUid(user, uid), user, seinfo);
6222                if (res < 0) {
6223                    return res;
6224                }
6225            }
6226        }
6227        return res;
6228    }
6229
6230    private int removeDataDirsLI(String volumeUuid, String packageName) {
6231        int[] users = sUserManager.getUserIds();
6232        int res = 0;
6233        for (int user : users) {
6234            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6235            if (resInner < 0) {
6236                res = resInner;
6237            }
6238        }
6239
6240        return res;
6241    }
6242
6243    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6244        int[] users = sUserManager.getUserIds();
6245        int res = 0;
6246        for (int user : users) {
6247            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6248            if (resInner < 0) {
6249                res = resInner;
6250            }
6251        }
6252        return res;
6253    }
6254
6255    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6256            PackageParser.Package changingLib) {
6257        if (file.path != null) {
6258            usesLibraryFiles.add(file.path);
6259            return;
6260        }
6261        PackageParser.Package p = mPackages.get(file.apk);
6262        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6263            // If we are doing this while in the middle of updating a library apk,
6264            // then we need to make sure to use that new apk for determining the
6265            // dependencies here.  (We haven't yet finished committing the new apk
6266            // to the package manager state.)
6267            if (p == null || p.packageName.equals(changingLib.packageName)) {
6268                p = changingLib;
6269            }
6270        }
6271        if (p != null) {
6272            usesLibraryFiles.addAll(p.getAllCodePaths());
6273        }
6274    }
6275
6276    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6277            PackageParser.Package changingLib) throws PackageManagerException {
6278        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6279            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6280            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6281            for (int i=0; i<N; i++) {
6282                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6283                if (file == null) {
6284                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6285                            "Package " + pkg.packageName + " requires unavailable shared library "
6286                            + pkg.usesLibraries.get(i) + "; failing!");
6287                }
6288                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6289            }
6290            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6291            for (int i=0; i<N; i++) {
6292                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6293                if (file == null) {
6294                    Slog.w(TAG, "Package " + pkg.packageName
6295                            + " desires unavailable shared library "
6296                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6297                } else {
6298                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6299                }
6300            }
6301            N = usesLibraryFiles.size();
6302            if (N > 0) {
6303                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6304            } else {
6305                pkg.usesLibraryFiles = null;
6306            }
6307        }
6308    }
6309
6310    private static boolean hasString(List<String> list, List<String> which) {
6311        if (list == null) {
6312            return false;
6313        }
6314        for (int i=list.size()-1; i>=0; i--) {
6315            for (int j=which.size()-1; j>=0; j--) {
6316                if (which.get(j).equals(list.get(i))) {
6317                    return true;
6318                }
6319            }
6320        }
6321        return false;
6322    }
6323
6324    private void updateAllSharedLibrariesLPw() {
6325        for (PackageParser.Package pkg : mPackages.values()) {
6326            try {
6327                updateSharedLibrariesLPw(pkg, null);
6328            } catch (PackageManagerException e) {
6329                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6330            }
6331        }
6332    }
6333
6334    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6335            PackageParser.Package changingPkg) {
6336        ArrayList<PackageParser.Package> res = null;
6337        for (PackageParser.Package pkg : mPackages.values()) {
6338            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6339                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6340                if (res == null) {
6341                    res = new ArrayList<PackageParser.Package>();
6342                }
6343                res.add(pkg);
6344                try {
6345                    updateSharedLibrariesLPw(pkg, changingPkg);
6346                } catch (PackageManagerException e) {
6347                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6348                }
6349            }
6350        }
6351        return res;
6352    }
6353
6354    /**
6355     * Derive the value of the {@code cpuAbiOverride} based on the provided
6356     * value and an optional stored value from the package settings.
6357     */
6358    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6359        String cpuAbiOverride = null;
6360
6361        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6362            cpuAbiOverride = null;
6363        } else if (abiOverride != null) {
6364            cpuAbiOverride = abiOverride;
6365        } else if (settings != null) {
6366            cpuAbiOverride = settings.cpuAbiOverrideString;
6367        }
6368
6369        return cpuAbiOverride;
6370    }
6371
6372    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6373            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6374        boolean success = false;
6375        try {
6376            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6377                    currentTime, user);
6378            success = true;
6379            return res;
6380        } finally {
6381            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6382                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6383            }
6384        }
6385    }
6386
6387    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6388            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6389        final File scanFile = new File(pkg.codePath);
6390        if (pkg.applicationInfo.getCodePath() == null ||
6391                pkg.applicationInfo.getResourcePath() == null) {
6392            // Bail out. The resource and code paths haven't been set.
6393            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6394                    "Code and resource paths haven't been set correctly");
6395        }
6396
6397        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6398            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6399        } else {
6400            // Only allow system apps to be flagged as core apps.
6401            pkg.coreApp = false;
6402        }
6403
6404        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6405            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6406        }
6407
6408        if (mCustomResolverComponentName != null &&
6409                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6410            setUpCustomResolverActivity(pkg);
6411        }
6412
6413        if (pkg.packageName.equals("android")) {
6414            synchronized (mPackages) {
6415                if (mAndroidApplication != null) {
6416                    Slog.w(TAG, "*************************************************");
6417                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6418                    Slog.w(TAG, " file=" + scanFile);
6419                    Slog.w(TAG, "*************************************************");
6420                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6421                            "Core android package being redefined.  Skipping.");
6422                }
6423
6424                // Set up information for our fall-back user intent resolution activity.
6425                mPlatformPackage = pkg;
6426                pkg.mVersionCode = mSdkVersion;
6427                mAndroidApplication = pkg.applicationInfo;
6428
6429                if (!mResolverReplaced) {
6430                    mResolveActivity.applicationInfo = mAndroidApplication;
6431                    mResolveActivity.name = ResolverActivity.class.getName();
6432                    mResolveActivity.packageName = mAndroidApplication.packageName;
6433                    mResolveActivity.processName = "system:ui";
6434                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6435                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6436                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6437                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6438                    mResolveActivity.exported = true;
6439                    mResolveActivity.enabled = true;
6440                    mResolveInfo.activityInfo = mResolveActivity;
6441                    mResolveInfo.priority = 0;
6442                    mResolveInfo.preferredOrder = 0;
6443                    mResolveInfo.match = 0;
6444                    mResolveComponentName = new ComponentName(
6445                            mAndroidApplication.packageName, mResolveActivity.name);
6446                }
6447            }
6448        }
6449
6450        if (DEBUG_PACKAGE_SCANNING) {
6451            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6452                Log.d(TAG, "Scanning package " + pkg.packageName);
6453        }
6454
6455        if (mPackages.containsKey(pkg.packageName)
6456                || mSharedLibraries.containsKey(pkg.packageName)) {
6457            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6458                    "Application package " + pkg.packageName
6459                    + " already installed.  Skipping duplicate.");
6460        }
6461
6462        // If we're only installing presumed-existing packages, require that the
6463        // scanned APK is both already known and at the path previously established
6464        // for it.  Previously unknown packages we pick up normally, but if we have an
6465        // a priori expectation about this package's install presence, enforce it.
6466        // With a singular exception for new system packages. When an OTA contains
6467        // a new system package, we allow the codepath to change from a system location
6468        // to the user-installed location. If we don't allow this change, any newer,
6469        // user-installed version of the application will be ignored.
6470        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6471            if (mExpectingBetter.containsKey(pkg.packageName)) {
6472                logCriticalInfo(Log.WARN,
6473                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6474            } else {
6475                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6476                if (known != null) {
6477                    if (DEBUG_PACKAGE_SCANNING) {
6478                        Log.d(TAG, "Examining " + pkg.codePath
6479                                + " and requiring known paths " + known.codePathString
6480                                + " & " + known.resourcePathString);
6481                    }
6482                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6483                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6484                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6485                                "Application package " + pkg.packageName
6486                                + " found at " + pkg.applicationInfo.getCodePath()
6487                                + " but expected at " + known.codePathString + "; ignoring.");
6488                    }
6489                }
6490            }
6491        }
6492
6493        // Initialize package source and resource directories
6494        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6495        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6496
6497        SharedUserSetting suid = null;
6498        PackageSetting pkgSetting = null;
6499
6500        if (!isSystemApp(pkg)) {
6501            // Only system apps can use these features.
6502            pkg.mOriginalPackages = null;
6503            pkg.mRealPackage = null;
6504            pkg.mAdoptPermissions = null;
6505        }
6506
6507        // writer
6508        synchronized (mPackages) {
6509            if (pkg.mSharedUserId != null) {
6510                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6511                if (suid == null) {
6512                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6513                            "Creating application package " + pkg.packageName
6514                            + " for shared user failed");
6515                }
6516                if (DEBUG_PACKAGE_SCANNING) {
6517                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6518                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6519                                + "): packages=" + suid.packages);
6520                }
6521            }
6522
6523            // Check if we are renaming from an original package name.
6524            PackageSetting origPackage = null;
6525            String realName = null;
6526            if (pkg.mOriginalPackages != null) {
6527                // This package may need to be renamed to a previously
6528                // installed name.  Let's check on that...
6529                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6530                if (pkg.mOriginalPackages.contains(renamed)) {
6531                    // This package had originally been installed as the
6532                    // original name, and we have already taken care of
6533                    // transitioning to the new one.  Just update the new
6534                    // one to continue using the old name.
6535                    realName = pkg.mRealPackage;
6536                    if (!pkg.packageName.equals(renamed)) {
6537                        // Callers into this function may have already taken
6538                        // care of renaming the package; only do it here if
6539                        // it is not already done.
6540                        pkg.setPackageName(renamed);
6541                    }
6542
6543                } else {
6544                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6545                        if ((origPackage = mSettings.peekPackageLPr(
6546                                pkg.mOriginalPackages.get(i))) != null) {
6547                            // We do have the package already installed under its
6548                            // original name...  should we use it?
6549                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6550                                // New package is not compatible with original.
6551                                origPackage = null;
6552                                continue;
6553                            } else if (origPackage.sharedUser != null) {
6554                                // Make sure uid is compatible between packages.
6555                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6556                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6557                                            + " to " + pkg.packageName + ": old uid "
6558                                            + origPackage.sharedUser.name
6559                                            + " differs from " + pkg.mSharedUserId);
6560                                    origPackage = null;
6561                                    continue;
6562                                }
6563                            } else {
6564                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6565                                        + pkg.packageName + " to old name " + origPackage.name);
6566                            }
6567                            break;
6568                        }
6569                    }
6570                }
6571            }
6572
6573            if (mTransferedPackages.contains(pkg.packageName)) {
6574                Slog.w(TAG, "Package " + pkg.packageName
6575                        + " was transferred to another, but its .apk remains");
6576            }
6577
6578            // Just create the setting, don't add it yet. For already existing packages
6579            // the PkgSetting exists already and doesn't have to be created.
6580            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6581                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6582                    pkg.applicationInfo.primaryCpuAbi,
6583                    pkg.applicationInfo.secondaryCpuAbi,
6584                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6585                    user, false);
6586            if (pkgSetting == null) {
6587                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6588                        "Creating application package " + pkg.packageName + " failed");
6589            }
6590
6591            if (pkgSetting.origPackage != null) {
6592                // If we are first transitioning from an original package,
6593                // fix up the new package's name now.  We need to do this after
6594                // looking up the package under its new name, so getPackageLP
6595                // can take care of fiddling things correctly.
6596                pkg.setPackageName(origPackage.name);
6597
6598                // File a report about this.
6599                String msg = "New package " + pkgSetting.realName
6600                        + " renamed to replace old package " + pkgSetting.name;
6601                reportSettingsProblem(Log.WARN, msg);
6602
6603                // Make a note of it.
6604                mTransferedPackages.add(origPackage.name);
6605
6606                // No longer need to retain this.
6607                pkgSetting.origPackage = null;
6608            }
6609
6610            if (realName != null) {
6611                // Make a note of it.
6612                mTransferedPackages.add(pkg.packageName);
6613            }
6614
6615            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6616                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6617            }
6618
6619            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6620                // Check all shared libraries and map to their actual file path.
6621                // We only do this here for apps not on a system dir, because those
6622                // are the only ones that can fail an install due to this.  We
6623                // will take care of the system apps by updating all of their
6624                // library paths after the scan is done.
6625                updateSharedLibrariesLPw(pkg, null);
6626            }
6627
6628            if (mFoundPolicyFile) {
6629                SELinuxMMAC.assignSeinfoValue(pkg);
6630            }
6631
6632            pkg.applicationInfo.uid = pkgSetting.appId;
6633            pkg.mExtras = pkgSetting;
6634            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6635                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6636                    // We just determined the app is signed correctly, so bring
6637                    // over the latest parsed certs.
6638                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6639                } else {
6640                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6641                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6642                                "Package " + pkg.packageName + " upgrade keys do not match the "
6643                                + "previously installed version");
6644                    } else {
6645                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6646                        String msg = "System package " + pkg.packageName
6647                            + " signature changed; retaining data.";
6648                        reportSettingsProblem(Log.WARN, msg);
6649                    }
6650                }
6651            } else {
6652                try {
6653                    verifySignaturesLP(pkgSetting, pkg);
6654                    // We just determined the app is signed correctly, so bring
6655                    // over the latest parsed certs.
6656                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6657                } catch (PackageManagerException e) {
6658                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6659                        throw e;
6660                    }
6661                    // The signature has changed, but this package is in the system
6662                    // image...  let's recover!
6663                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6664                    // However...  if this package is part of a shared user, but it
6665                    // doesn't match the signature of the shared user, let's fail.
6666                    // What this means is that you can't change the signatures
6667                    // associated with an overall shared user, which doesn't seem all
6668                    // that unreasonable.
6669                    if (pkgSetting.sharedUser != null) {
6670                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6671                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6672                            throw new PackageManagerException(
6673                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6674                                            "Signature mismatch for shared user : "
6675                                            + pkgSetting.sharedUser);
6676                        }
6677                    }
6678                    // File a report about this.
6679                    String msg = "System package " + pkg.packageName
6680                        + " signature changed; retaining data.";
6681                    reportSettingsProblem(Log.WARN, msg);
6682                }
6683            }
6684            // Verify that this new package doesn't have any content providers
6685            // that conflict with existing packages.  Only do this if the
6686            // package isn't already installed, since we don't want to break
6687            // things that are installed.
6688            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6689                final int N = pkg.providers.size();
6690                int i;
6691                for (i=0; i<N; i++) {
6692                    PackageParser.Provider p = pkg.providers.get(i);
6693                    if (p.info.authority != null) {
6694                        String names[] = p.info.authority.split(";");
6695                        for (int j = 0; j < names.length; j++) {
6696                            if (mProvidersByAuthority.containsKey(names[j])) {
6697                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6698                                final String otherPackageName =
6699                                        ((other != null && other.getComponentName() != null) ?
6700                                                other.getComponentName().getPackageName() : "?");
6701                                throw new PackageManagerException(
6702                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6703                                                "Can't install because provider name " + names[j]
6704                                                + " (in package " + pkg.applicationInfo.packageName
6705                                                + ") is already used by " + otherPackageName);
6706                            }
6707                        }
6708                    }
6709                }
6710            }
6711
6712            if (pkg.mAdoptPermissions != null) {
6713                // This package wants to adopt ownership of permissions from
6714                // another package.
6715                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6716                    final String origName = pkg.mAdoptPermissions.get(i);
6717                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6718                    if (orig != null) {
6719                        if (verifyPackageUpdateLPr(orig, pkg)) {
6720                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6721                                    + pkg.packageName);
6722                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6723                        }
6724                    }
6725                }
6726            }
6727        }
6728
6729        final String pkgName = pkg.packageName;
6730
6731        final long scanFileTime = scanFile.lastModified();
6732        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6733        pkg.applicationInfo.processName = fixProcessName(
6734                pkg.applicationInfo.packageName,
6735                pkg.applicationInfo.processName,
6736                pkg.applicationInfo.uid);
6737
6738        File dataPath;
6739        if (mPlatformPackage == pkg) {
6740            // The system package is special.
6741            dataPath = new File(Environment.getDataDirectory(), "system");
6742
6743            pkg.applicationInfo.dataDir = dataPath.getPath();
6744
6745        } else {
6746            // This is a normal package, need to make its data directory.
6747            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6748                    UserHandle.USER_OWNER, pkg.packageName);
6749
6750            boolean uidError = false;
6751            if (dataPath.exists()) {
6752                int currentUid = 0;
6753                try {
6754                    StructStat stat = Os.stat(dataPath.getPath());
6755                    currentUid = stat.st_uid;
6756                } catch (ErrnoException e) {
6757                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6758                }
6759
6760                // If we have mismatched owners for the data path, we have a problem.
6761                if (currentUid != pkg.applicationInfo.uid) {
6762                    boolean recovered = false;
6763                    if (currentUid == 0) {
6764                        // The directory somehow became owned by root.  Wow.
6765                        // This is probably because the system was stopped while
6766                        // installd was in the middle of messing with its libs
6767                        // directory.  Ask installd to fix that.
6768                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6769                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6770                        if (ret >= 0) {
6771                            recovered = true;
6772                            String msg = "Package " + pkg.packageName
6773                                    + " unexpectedly changed to uid 0; recovered to " +
6774                                    + pkg.applicationInfo.uid;
6775                            reportSettingsProblem(Log.WARN, msg);
6776                        }
6777                    }
6778                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6779                            || (scanFlags&SCAN_BOOTING) != 0)) {
6780                        // If this is a system app, we can at least delete its
6781                        // current data so the application will still work.
6782                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6783                        if (ret >= 0) {
6784                            // TODO: Kill the processes first
6785                            // Old data gone!
6786                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6787                                    ? "System package " : "Third party package ";
6788                            String msg = prefix + pkg.packageName
6789                                    + " has changed from uid: "
6790                                    + currentUid + " to "
6791                                    + pkg.applicationInfo.uid + "; old data erased";
6792                            reportSettingsProblem(Log.WARN, msg);
6793                            recovered = true;
6794
6795                            // And now re-install the app.
6796                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6797                                    pkg.applicationInfo.seinfo);
6798                            if (ret == -1) {
6799                                // Ack should not happen!
6800                                msg = prefix + pkg.packageName
6801                                        + " could not have data directory re-created after delete.";
6802                                reportSettingsProblem(Log.WARN, msg);
6803                                throw new PackageManagerException(
6804                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6805                            }
6806                        }
6807                        if (!recovered) {
6808                            mHasSystemUidErrors = true;
6809                        }
6810                    } else if (!recovered) {
6811                        // If we allow this install to proceed, we will be broken.
6812                        // Abort, abort!
6813                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6814                                "scanPackageLI");
6815                    }
6816                    if (!recovered) {
6817                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6818                            + pkg.applicationInfo.uid + "/fs_"
6819                            + currentUid;
6820                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6821                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6822                        String msg = "Package " + pkg.packageName
6823                                + " has mismatched uid: "
6824                                + currentUid + " on disk, "
6825                                + pkg.applicationInfo.uid + " in settings";
6826                        // writer
6827                        synchronized (mPackages) {
6828                            mSettings.mReadMessages.append(msg);
6829                            mSettings.mReadMessages.append('\n');
6830                            uidError = true;
6831                            if (!pkgSetting.uidError) {
6832                                reportSettingsProblem(Log.ERROR, msg);
6833                            }
6834                        }
6835                    }
6836                }
6837                pkg.applicationInfo.dataDir = dataPath.getPath();
6838                if (mShouldRestoreconData) {
6839                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6840                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6841                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6842                }
6843            } else {
6844                if (DEBUG_PACKAGE_SCANNING) {
6845                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6846                        Log.v(TAG, "Want this data dir: " + dataPath);
6847                }
6848                //invoke installer to do the actual installation
6849                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6850                        pkg.applicationInfo.seinfo);
6851                if (ret < 0) {
6852                    // Error from installer
6853                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6854                            "Unable to create data dirs [errorCode=" + ret + "]");
6855                }
6856
6857                if (dataPath.exists()) {
6858                    pkg.applicationInfo.dataDir = dataPath.getPath();
6859                } else {
6860                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6861                    pkg.applicationInfo.dataDir = null;
6862                }
6863            }
6864
6865            pkgSetting.uidError = uidError;
6866        }
6867
6868        final String path = scanFile.getPath();
6869        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6870
6871        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6872            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6873
6874            // Some system apps still use directory structure for native libraries
6875            // in which case we might end up not detecting abi solely based on apk
6876            // structure. Try to detect abi based on directory structure.
6877            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6878                    pkg.applicationInfo.primaryCpuAbi == null) {
6879                setBundledAppAbisAndRoots(pkg, pkgSetting);
6880                setNativeLibraryPaths(pkg);
6881            }
6882
6883        } else {
6884            if ((scanFlags & SCAN_MOVE) != 0) {
6885                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6886                // but we already have this packages package info in the PackageSetting. We just
6887                // use that and derive the native library path based on the new codepath.
6888                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6889                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6890            }
6891
6892            // Set native library paths again. For moves, the path will be updated based on the
6893            // ABIs we've determined above. For non-moves, the path will be updated based on the
6894            // ABIs we determined during compilation, but the path will depend on the final
6895            // package path (after the rename away from the stage path).
6896            setNativeLibraryPaths(pkg);
6897        }
6898
6899        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6900        final int[] userIds = sUserManager.getUserIds();
6901        synchronized (mInstallLock) {
6902            // Make sure all user data directories are ready to roll; we're okay
6903            // if they already exist
6904            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6905                for (int userId : userIds) {
6906                    if (userId != 0) {
6907                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6908                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
6909                                pkg.applicationInfo.seinfo);
6910                    }
6911                }
6912            }
6913
6914            // Create a native library symlink only if we have native libraries
6915            // and if the native libraries are 32 bit libraries. We do not provide
6916            // this symlink for 64 bit libraries.
6917            if (pkg.applicationInfo.primaryCpuAbi != null &&
6918                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6919                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6920                for (int userId : userIds) {
6921                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6922                            nativeLibPath, userId) < 0) {
6923                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6924                                "Failed linking native library dir (user=" + userId + ")");
6925                    }
6926                }
6927            }
6928        }
6929
6930        // This is a special case for the "system" package, where the ABI is
6931        // dictated by the zygote configuration (and init.rc). We should keep track
6932        // of this ABI so that we can deal with "normal" applications that run under
6933        // the same UID correctly.
6934        if (mPlatformPackage == pkg) {
6935            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6936                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6937        }
6938
6939        // If there's a mismatch between the abi-override in the package setting
6940        // and the abiOverride specified for the install. Warn about this because we
6941        // would've already compiled the app without taking the package setting into
6942        // account.
6943        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
6944            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
6945                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
6946                        " for package: " + pkg.packageName);
6947            }
6948        }
6949
6950        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6951        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6952        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6953
6954        // Copy the derived override back to the parsed package, so that we can
6955        // update the package settings accordingly.
6956        pkg.cpuAbiOverride = cpuAbiOverride;
6957
6958        if (DEBUG_ABI_SELECTION) {
6959            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6960                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6961                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6962        }
6963
6964        // Push the derived path down into PackageSettings so we know what to
6965        // clean up at uninstall time.
6966        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6967
6968        if (DEBUG_ABI_SELECTION) {
6969            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6970                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6971                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6972        }
6973
6974        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6975            // We don't do this here during boot because we can do it all
6976            // at once after scanning all existing packages.
6977            //
6978            // We also do this *before* we perform dexopt on this package, so that
6979            // we can avoid redundant dexopts, and also to make sure we've got the
6980            // code and package path correct.
6981            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6982                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6983        }
6984
6985        if ((scanFlags & SCAN_NO_DEX) == 0) {
6986            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6987                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6988            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6989                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6990            }
6991        }
6992        if (mFactoryTest && pkg.requestedPermissions.contains(
6993                android.Manifest.permission.FACTORY_TEST)) {
6994            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6995        }
6996
6997        ArrayList<PackageParser.Package> clientLibPkgs = null;
6998
6999        // writer
7000        synchronized (mPackages) {
7001            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7002                // Only system apps can add new shared libraries.
7003                if (pkg.libraryNames != null) {
7004                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7005                        String name = pkg.libraryNames.get(i);
7006                        boolean allowed = false;
7007                        if (pkg.isUpdatedSystemApp()) {
7008                            // New library entries can only be added through the
7009                            // system image.  This is important to get rid of a lot
7010                            // of nasty edge cases: for example if we allowed a non-
7011                            // system update of the app to add a library, then uninstalling
7012                            // the update would make the library go away, and assumptions
7013                            // we made such as through app install filtering would now
7014                            // have allowed apps on the device which aren't compatible
7015                            // with it.  Better to just have the restriction here, be
7016                            // conservative, and create many fewer cases that can negatively
7017                            // impact the user experience.
7018                            final PackageSetting sysPs = mSettings
7019                                    .getDisabledSystemPkgLPr(pkg.packageName);
7020                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7021                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7022                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7023                                        allowed = true;
7024                                        allowed = true;
7025                                        break;
7026                                    }
7027                                }
7028                            }
7029                        } else {
7030                            allowed = true;
7031                        }
7032                        if (allowed) {
7033                            if (!mSharedLibraries.containsKey(name)) {
7034                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7035                            } else if (!name.equals(pkg.packageName)) {
7036                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7037                                        + name + " already exists; skipping");
7038                            }
7039                        } else {
7040                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7041                                    + name + " that is not declared on system image; skipping");
7042                        }
7043                    }
7044                    if ((scanFlags&SCAN_BOOTING) == 0) {
7045                        // If we are not booting, we need to update any applications
7046                        // that are clients of our shared library.  If we are booting,
7047                        // this will all be done once the scan is complete.
7048                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7049                    }
7050                }
7051            }
7052        }
7053
7054        // We also need to dexopt any apps that are dependent on this library.  Note that
7055        // if these fail, we should abort the install since installing the library will
7056        // result in some apps being broken.
7057        if (clientLibPkgs != null) {
7058            if ((scanFlags & SCAN_NO_DEX) == 0) {
7059                for (int i = 0; i < clientLibPkgs.size(); i++) {
7060                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7061                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7062                            null /* instruction sets */, forceDex,
7063                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
7064                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7065                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7066                                "scanPackageLI failed to dexopt clientLibPkgs");
7067                    }
7068                }
7069            }
7070        }
7071
7072        // Also need to kill any apps that are dependent on the library.
7073        if (clientLibPkgs != null) {
7074            for (int i=0; i<clientLibPkgs.size(); i++) {
7075                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7076                killApplication(clientPkg.applicationInfo.packageName,
7077                        clientPkg.applicationInfo.uid, "update lib");
7078            }
7079        }
7080
7081        // Make sure we're not adding any bogus keyset info
7082        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7083        ksms.assertScannedPackageValid(pkg);
7084
7085        // writer
7086        synchronized (mPackages) {
7087            // We don't expect installation to fail beyond this point
7088
7089            // Add the new setting to mSettings
7090            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7091            // Add the new setting to mPackages
7092            mPackages.put(pkg.applicationInfo.packageName, pkg);
7093            // Make sure we don't accidentally delete its data.
7094            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7095            while (iter.hasNext()) {
7096                PackageCleanItem item = iter.next();
7097                if (pkgName.equals(item.packageName)) {
7098                    iter.remove();
7099                }
7100            }
7101
7102            // Take care of first install / last update times.
7103            if (currentTime != 0) {
7104                if (pkgSetting.firstInstallTime == 0) {
7105                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7106                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7107                    pkgSetting.lastUpdateTime = currentTime;
7108                }
7109            } else if (pkgSetting.firstInstallTime == 0) {
7110                // We need *something*.  Take time time stamp of the file.
7111                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7112            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7113                if (scanFileTime != pkgSetting.timeStamp) {
7114                    // A package on the system image has changed; consider this
7115                    // to be an update.
7116                    pkgSetting.lastUpdateTime = scanFileTime;
7117                }
7118            }
7119
7120            // Add the package's KeySets to the global KeySetManagerService
7121            ksms.addScannedPackageLPw(pkg);
7122
7123            int N = pkg.providers.size();
7124            StringBuilder r = null;
7125            int i;
7126            for (i=0; i<N; i++) {
7127                PackageParser.Provider p = pkg.providers.get(i);
7128                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7129                        p.info.processName, pkg.applicationInfo.uid);
7130                mProviders.addProvider(p);
7131                p.syncable = p.info.isSyncable;
7132                if (p.info.authority != null) {
7133                    String names[] = p.info.authority.split(";");
7134                    p.info.authority = null;
7135                    for (int j = 0; j < names.length; j++) {
7136                        if (j == 1 && p.syncable) {
7137                            // We only want the first authority for a provider to possibly be
7138                            // syncable, so if we already added this provider using a different
7139                            // authority clear the syncable flag. We copy the provider before
7140                            // changing it because the mProviders object contains a reference
7141                            // to a provider that we don't want to change.
7142                            // Only do this for the second authority since the resulting provider
7143                            // object can be the same for all future authorities for this provider.
7144                            p = new PackageParser.Provider(p);
7145                            p.syncable = false;
7146                        }
7147                        if (!mProvidersByAuthority.containsKey(names[j])) {
7148                            mProvidersByAuthority.put(names[j], p);
7149                            if (p.info.authority == null) {
7150                                p.info.authority = names[j];
7151                            } else {
7152                                p.info.authority = p.info.authority + ";" + names[j];
7153                            }
7154                            if (DEBUG_PACKAGE_SCANNING) {
7155                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7156                                    Log.d(TAG, "Registered content provider: " + names[j]
7157                                            + ", className = " + p.info.name + ", isSyncable = "
7158                                            + p.info.isSyncable);
7159                            }
7160                        } else {
7161                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7162                            Slog.w(TAG, "Skipping provider name " + names[j] +
7163                                    " (in package " + pkg.applicationInfo.packageName +
7164                                    "): name already used by "
7165                                    + ((other != null && other.getComponentName() != null)
7166                                            ? other.getComponentName().getPackageName() : "?"));
7167                        }
7168                    }
7169                }
7170                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7171                    if (r == null) {
7172                        r = new StringBuilder(256);
7173                    } else {
7174                        r.append(' ');
7175                    }
7176                    r.append(p.info.name);
7177                }
7178            }
7179            if (r != null) {
7180                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7181            }
7182
7183            N = pkg.services.size();
7184            r = null;
7185            for (i=0; i<N; i++) {
7186                PackageParser.Service s = pkg.services.get(i);
7187                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7188                        s.info.processName, pkg.applicationInfo.uid);
7189                mServices.addService(s);
7190                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7191                    if (r == null) {
7192                        r = new StringBuilder(256);
7193                    } else {
7194                        r.append(' ');
7195                    }
7196                    r.append(s.info.name);
7197                }
7198            }
7199            if (r != null) {
7200                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7201            }
7202
7203            N = pkg.receivers.size();
7204            r = null;
7205            for (i=0; i<N; i++) {
7206                PackageParser.Activity a = pkg.receivers.get(i);
7207                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7208                        a.info.processName, pkg.applicationInfo.uid);
7209                mReceivers.addActivity(a, "receiver");
7210                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7211                    if (r == null) {
7212                        r = new StringBuilder(256);
7213                    } else {
7214                        r.append(' ');
7215                    }
7216                    r.append(a.info.name);
7217                }
7218            }
7219            if (r != null) {
7220                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7221            }
7222
7223            N = pkg.activities.size();
7224            r = null;
7225            for (i=0; i<N; i++) {
7226                PackageParser.Activity a = pkg.activities.get(i);
7227                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7228                        a.info.processName, pkg.applicationInfo.uid);
7229                mActivities.addActivity(a, "activity");
7230                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7231                    if (r == null) {
7232                        r = new StringBuilder(256);
7233                    } else {
7234                        r.append(' ');
7235                    }
7236                    r.append(a.info.name);
7237                }
7238            }
7239            if (r != null) {
7240                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7241            }
7242
7243            N = pkg.permissionGroups.size();
7244            r = null;
7245            for (i=0; i<N; i++) {
7246                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7247                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7248                if (cur == null) {
7249                    mPermissionGroups.put(pg.info.name, pg);
7250                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7251                        if (r == null) {
7252                            r = new StringBuilder(256);
7253                        } else {
7254                            r.append(' ');
7255                        }
7256                        r.append(pg.info.name);
7257                    }
7258                } else {
7259                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7260                            + pg.info.packageName + " ignored: original from "
7261                            + cur.info.packageName);
7262                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7263                        if (r == null) {
7264                            r = new StringBuilder(256);
7265                        } else {
7266                            r.append(' ');
7267                        }
7268                        r.append("DUP:");
7269                        r.append(pg.info.name);
7270                    }
7271                }
7272            }
7273            if (r != null) {
7274                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7275            }
7276
7277            N = pkg.permissions.size();
7278            r = null;
7279            for (i=0; i<N; i++) {
7280                PackageParser.Permission p = pkg.permissions.get(i);
7281
7282                // Now that permission groups have a special meaning, we ignore permission
7283                // groups for legacy apps to prevent unexpected behavior. In particular,
7284                // permissions for one app being granted to someone just becuase they happen
7285                // to be in a group defined by another app (before this had no implications).
7286                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7287                    p.group = mPermissionGroups.get(p.info.group);
7288                    // Warn for a permission in an unknown group.
7289                    if (p.info.group != null && p.group == null) {
7290                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7291                                + p.info.packageName + " in an unknown group " + p.info.group);
7292                    }
7293                }
7294
7295                ArrayMap<String, BasePermission> permissionMap =
7296                        p.tree ? mSettings.mPermissionTrees
7297                                : mSettings.mPermissions;
7298                BasePermission bp = permissionMap.get(p.info.name);
7299
7300                // Allow system apps to redefine non-system permissions
7301                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7302                    final boolean currentOwnerIsSystem = (bp.perm != null
7303                            && isSystemApp(bp.perm.owner));
7304                    if (isSystemApp(p.owner)) {
7305                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7306                            // It's a built-in permission and no owner, take ownership now
7307                            bp.packageSetting = pkgSetting;
7308                            bp.perm = p;
7309                            bp.uid = pkg.applicationInfo.uid;
7310                            bp.sourcePackage = p.info.packageName;
7311                        } else if (!currentOwnerIsSystem) {
7312                            String msg = "New decl " + p.owner + " of permission  "
7313                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7314                            reportSettingsProblem(Log.WARN, msg);
7315                            bp = null;
7316                        }
7317                    }
7318                }
7319
7320                if (bp == null) {
7321                    bp = new BasePermission(p.info.name, p.info.packageName,
7322                            BasePermission.TYPE_NORMAL);
7323                    permissionMap.put(p.info.name, bp);
7324                }
7325
7326                if (bp.perm == null) {
7327                    if (bp.sourcePackage == null
7328                            || bp.sourcePackage.equals(p.info.packageName)) {
7329                        BasePermission tree = findPermissionTreeLP(p.info.name);
7330                        if (tree == null
7331                                || tree.sourcePackage.equals(p.info.packageName)) {
7332                            bp.packageSetting = pkgSetting;
7333                            bp.perm = p;
7334                            bp.uid = pkg.applicationInfo.uid;
7335                            bp.sourcePackage = p.info.packageName;
7336                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7337                                if (r == null) {
7338                                    r = new StringBuilder(256);
7339                                } else {
7340                                    r.append(' ');
7341                                }
7342                                r.append(p.info.name);
7343                            }
7344                        } else {
7345                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7346                                    + p.info.packageName + " ignored: base tree "
7347                                    + tree.name + " is from package "
7348                                    + tree.sourcePackage);
7349                        }
7350                    } else {
7351                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7352                                + p.info.packageName + " ignored: original from "
7353                                + bp.sourcePackage);
7354                    }
7355                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7356                    if (r == null) {
7357                        r = new StringBuilder(256);
7358                    } else {
7359                        r.append(' ');
7360                    }
7361                    r.append("DUP:");
7362                    r.append(p.info.name);
7363                }
7364                if (bp.perm == p) {
7365                    bp.protectionLevel = p.info.protectionLevel;
7366                }
7367            }
7368
7369            if (r != null) {
7370                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7371            }
7372
7373            N = pkg.instrumentation.size();
7374            r = null;
7375            for (i=0; i<N; i++) {
7376                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7377                a.info.packageName = pkg.applicationInfo.packageName;
7378                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7379                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7380                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7381                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7382                a.info.dataDir = pkg.applicationInfo.dataDir;
7383
7384                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7385                // need other information about the application, like the ABI and what not ?
7386                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7387                mInstrumentation.put(a.getComponentName(), a);
7388                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7389                    if (r == null) {
7390                        r = new StringBuilder(256);
7391                    } else {
7392                        r.append(' ');
7393                    }
7394                    r.append(a.info.name);
7395                }
7396            }
7397            if (r != null) {
7398                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7399            }
7400
7401            if (pkg.protectedBroadcasts != null) {
7402                N = pkg.protectedBroadcasts.size();
7403                for (i=0; i<N; i++) {
7404                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7405                }
7406            }
7407
7408            pkgSetting.setTimeStamp(scanFileTime);
7409
7410            // Create idmap files for pairs of (packages, overlay packages).
7411            // Note: "android", ie framework-res.apk, is handled by native layers.
7412            if (pkg.mOverlayTarget != null) {
7413                // This is an overlay package.
7414                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7415                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7416                        mOverlays.put(pkg.mOverlayTarget,
7417                                new ArrayMap<String, PackageParser.Package>());
7418                    }
7419                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7420                    map.put(pkg.packageName, pkg);
7421                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7422                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7423                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7424                                "scanPackageLI failed to createIdmap");
7425                    }
7426                }
7427            } else if (mOverlays.containsKey(pkg.packageName) &&
7428                    !pkg.packageName.equals("android")) {
7429                // This is a regular package, with one or more known overlay packages.
7430                createIdmapsForPackageLI(pkg);
7431            }
7432        }
7433
7434        return pkg;
7435    }
7436
7437    /**
7438     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7439     * is derived purely on the basis of the contents of {@code scanFile} and
7440     * {@code cpuAbiOverride}.
7441     *
7442     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7443     */
7444    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7445                                 String cpuAbiOverride, boolean extractLibs)
7446            throws PackageManagerException {
7447        // TODO: We can probably be smarter about this stuff. For installed apps,
7448        // we can calculate this information at install time once and for all. For
7449        // system apps, we can probably assume that this information doesn't change
7450        // after the first boot scan. As things stand, we do lots of unnecessary work.
7451
7452        // Give ourselves some initial paths; we'll come back for another
7453        // pass once we've determined ABI below.
7454        setNativeLibraryPaths(pkg);
7455
7456        // We would never need to extract libs for forward-locked and external packages,
7457        // since the container service will do it for us. We shouldn't attempt to
7458        // extract libs from system app when it was not updated.
7459        if (pkg.isForwardLocked() || isExternal(pkg) ||
7460            (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) ) {
7461            extractLibs = false;
7462        }
7463
7464        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7465        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7466
7467        NativeLibraryHelper.Handle handle = null;
7468        try {
7469            handle = NativeLibraryHelper.Handle.create(pkg);
7470            // TODO(multiArch): This can be null for apps that didn't go through the
7471            // usual installation process. We can calculate it again, like we
7472            // do during install time.
7473            //
7474            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7475            // unnecessary.
7476            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7477
7478            // Null out the abis so that they can be recalculated.
7479            pkg.applicationInfo.primaryCpuAbi = null;
7480            pkg.applicationInfo.secondaryCpuAbi = null;
7481            if (isMultiArch(pkg.applicationInfo)) {
7482                // Warn if we've set an abiOverride for multi-lib packages..
7483                // By definition, we need to copy both 32 and 64 bit libraries for
7484                // such packages.
7485                if (pkg.cpuAbiOverride != null
7486                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7487                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7488                }
7489
7490                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7491                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7492                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7493                    if (extractLibs) {
7494                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7495                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7496                                useIsaSpecificSubdirs);
7497                    } else {
7498                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7499                    }
7500                }
7501
7502                maybeThrowExceptionForMultiArchCopy(
7503                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7504
7505                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7506                    if (extractLibs) {
7507                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7508                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7509                                useIsaSpecificSubdirs);
7510                    } else {
7511                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7512                    }
7513                }
7514
7515                maybeThrowExceptionForMultiArchCopy(
7516                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7517
7518                if (abi64 >= 0) {
7519                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7520                }
7521
7522                if (abi32 >= 0) {
7523                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7524                    if (abi64 >= 0) {
7525                        pkg.applicationInfo.secondaryCpuAbi = abi;
7526                    } else {
7527                        pkg.applicationInfo.primaryCpuAbi = abi;
7528                    }
7529                }
7530            } else {
7531                String[] abiList = (cpuAbiOverride != null) ?
7532                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7533
7534                // Enable gross and lame hacks for apps that are built with old
7535                // SDK tools. We must scan their APKs for renderscript bitcode and
7536                // not launch them if it's present. Don't bother checking on devices
7537                // that don't have 64 bit support.
7538                boolean needsRenderScriptOverride = false;
7539                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7540                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7541                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7542                    needsRenderScriptOverride = true;
7543                }
7544
7545                final int copyRet;
7546                if (extractLibs) {
7547                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7548                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7549                } else {
7550                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7551                }
7552
7553                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7554                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7555                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7556                }
7557
7558                if (copyRet >= 0) {
7559                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7560                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7561                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7562                } else if (needsRenderScriptOverride) {
7563                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7564                }
7565            }
7566        } catch (IOException ioe) {
7567            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7568        } finally {
7569            IoUtils.closeQuietly(handle);
7570        }
7571
7572        // Now that we've calculated the ABIs and determined if it's an internal app,
7573        // we will go ahead and populate the nativeLibraryPath.
7574        setNativeLibraryPaths(pkg);
7575    }
7576
7577    /**
7578     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7579     * i.e, so that all packages can be run inside a single process if required.
7580     *
7581     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7582     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7583     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7584     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7585     * updating a package that belongs to a shared user.
7586     *
7587     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7588     * adds unnecessary complexity.
7589     */
7590    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7591            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
7592        String requiredInstructionSet = null;
7593        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7594            requiredInstructionSet = VMRuntime.getInstructionSet(
7595                     scannedPackage.applicationInfo.primaryCpuAbi);
7596        }
7597
7598        PackageSetting requirer = null;
7599        for (PackageSetting ps : packagesForUser) {
7600            // If packagesForUser contains scannedPackage, we skip it. This will happen
7601            // when scannedPackage is an update of an existing package. Without this check,
7602            // we will never be able to change the ABI of any package belonging to a shared
7603            // user, even if it's compatible with other packages.
7604            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7605                if (ps.primaryCpuAbiString == null) {
7606                    continue;
7607                }
7608
7609                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7610                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7611                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7612                    // this but there's not much we can do.
7613                    String errorMessage = "Instruction set mismatch, "
7614                            + ((requirer == null) ? "[caller]" : requirer)
7615                            + " requires " + requiredInstructionSet + " whereas " + ps
7616                            + " requires " + instructionSet;
7617                    Slog.w(TAG, errorMessage);
7618                }
7619
7620                if (requiredInstructionSet == null) {
7621                    requiredInstructionSet = instructionSet;
7622                    requirer = ps;
7623                }
7624            }
7625        }
7626
7627        if (requiredInstructionSet != null) {
7628            String adjustedAbi;
7629            if (requirer != null) {
7630                // requirer != null implies that either scannedPackage was null or that scannedPackage
7631                // did not require an ABI, in which case we have to adjust scannedPackage to match
7632                // the ABI of the set (which is the same as requirer's ABI)
7633                adjustedAbi = requirer.primaryCpuAbiString;
7634                if (scannedPackage != null) {
7635                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7636                }
7637            } else {
7638                // requirer == null implies that we're updating all ABIs in the set to
7639                // match scannedPackage.
7640                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7641            }
7642
7643            for (PackageSetting ps : packagesForUser) {
7644                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7645                    if (ps.primaryCpuAbiString != null) {
7646                        continue;
7647                    }
7648
7649                    ps.primaryCpuAbiString = adjustedAbi;
7650                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7651                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7652                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7653
7654                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7655                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7656                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7657                            ps.primaryCpuAbiString = null;
7658                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7659                            return;
7660                        } else {
7661                            mInstaller.rmdex(ps.codePathString,
7662                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7663                        }
7664                    }
7665                }
7666            }
7667        }
7668    }
7669
7670    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7671        synchronized (mPackages) {
7672            mResolverReplaced = true;
7673            // Set up information for custom user intent resolution activity.
7674            mResolveActivity.applicationInfo = pkg.applicationInfo;
7675            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7676            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7677            mResolveActivity.processName = pkg.applicationInfo.packageName;
7678            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7679            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7680                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7681            mResolveActivity.theme = 0;
7682            mResolveActivity.exported = true;
7683            mResolveActivity.enabled = true;
7684            mResolveInfo.activityInfo = mResolveActivity;
7685            mResolveInfo.priority = 0;
7686            mResolveInfo.preferredOrder = 0;
7687            mResolveInfo.match = 0;
7688            mResolveComponentName = mCustomResolverComponentName;
7689            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7690                    mResolveComponentName);
7691        }
7692    }
7693
7694    private static String calculateBundledApkRoot(final String codePathString) {
7695        final File codePath = new File(codePathString);
7696        final File codeRoot;
7697        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7698            codeRoot = Environment.getRootDirectory();
7699        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7700            codeRoot = Environment.getOemDirectory();
7701        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7702            codeRoot = Environment.getVendorDirectory();
7703        } else {
7704            // Unrecognized code path; take its top real segment as the apk root:
7705            // e.g. /something/app/blah.apk => /something
7706            try {
7707                File f = codePath.getCanonicalFile();
7708                File parent = f.getParentFile();    // non-null because codePath is a file
7709                File tmp;
7710                while ((tmp = parent.getParentFile()) != null) {
7711                    f = parent;
7712                    parent = tmp;
7713                }
7714                codeRoot = f;
7715                Slog.w(TAG, "Unrecognized code path "
7716                        + codePath + " - using " + codeRoot);
7717            } catch (IOException e) {
7718                // Can't canonicalize the code path -- shenanigans?
7719                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7720                return Environment.getRootDirectory().getPath();
7721            }
7722        }
7723        return codeRoot.getPath();
7724    }
7725
7726    /**
7727     * Derive and set the location of native libraries for the given package,
7728     * which varies depending on where and how the package was installed.
7729     */
7730    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7731        final ApplicationInfo info = pkg.applicationInfo;
7732        final String codePath = pkg.codePath;
7733        final File codeFile = new File(codePath);
7734        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7735        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7736
7737        info.nativeLibraryRootDir = null;
7738        info.nativeLibraryRootRequiresIsa = false;
7739        info.nativeLibraryDir = null;
7740        info.secondaryNativeLibraryDir = null;
7741
7742        if (isApkFile(codeFile)) {
7743            // Monolithic install
7744            if (bundledApp) {
7745                // If "/system/lib64/apkname" exists, assume that is the per-package
7746                // native library directory to use; otherwise use "/system/lib/apkname".
7747                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7748                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7749                        getPrimaryInstructionSet(info));
7750
7751                // This is a bundled system app so choose the path based on the ABI.
7752                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7753                // is just the default path.
7754                final String apkName = deriveCodePathName(codePath);
7755                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7756                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7757                        apkName).getAbsolutePath();
7758
7759                if (info.secondaryCpuAbi != null) {
7760                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7761                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7762                            secondaryLibDir, apkName).getAbsolutePath();
7763                }
7764            } else if (asecApp) {
7765                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7766                        .getAbsolutePath();
7767            } else {
7768                final String apkName = deriveCodePathName(codePath);
7769                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7770                        .getAbsolutePath();
7771            }
7772
7773            info.nativeLibraryRootRequiresIsa = false;
7774            info.nativeLibraryDir = info.nativeLibraryRootDir;
7775        } else {
7776            // Cluster install
7777            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7778            info.nativeLibraryRootRequiresIsa = true;
7779
7780            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7781                    getPrimaryInstructionSet(info)).getAbsolutePath();
7782
7783            if (info.secondaryCpuAbi != null) {
7784                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7785                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7786            }
7787        }
7788    }
7789
7790    /**
7791     * Calculate the abis and roots for a bundled app. These can uniquely
7792     * be determined from the contents of the system partition, i.e whether
7793     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7794     * of this information, and instead assume that the system was built
7795     * sensibly.
7796     */
7797    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7798                                           PackageSetting pkgSetting) {
7799        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7800
7801        // If "/system/lib64/apkname" exists, assume that is the per-package
7802        // native library directory to use; otherwise use "/system/lib/apkname".
7803        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7804        setBundledAppAbi(pkg, apkRoot, apkName);
7805        // pkgSetting might be null during rescan following uninstall of updates
7806        // to a bundled app, so accommodate that possibility.  The settings in
7807        // that case will be established later from the parsed package.
7808        //
7809        // If the settings aren't null, sync them up with what we've just derived.
7810        // note that apkRoot isn't stored in the package settings.
7811        if (pkgSetting != null) {
7812            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7813            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7814        }
7815    }
7816
7817    /**
7818     * Deduces the ABI of a bundled app and sets the relevant fields on the
7819     * parsed pkg object.
7820     *
7821     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7822     *        under which system libraries are installed.
7823     * @param apkName the name of the installed package.
7824     */
7825    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7826        final File codeFile = new File(pkg.codePath);
7827
7828        final boolean has64BitLibs;
7829        final boolean has32BitLibs;
7830        if (isApkFile(codeFile)) {
7831            // Monolithic install
7832            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7833            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7834        } else {
7835            // Cluster install
7836            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7837            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7838                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7839                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7840                has64BitLibs = (new File(rootDir, isa)).exists();
7841            } else {
7842                has64BitLibs = false;
7843            }
7844            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7845                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7846                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7847                has32BitLibs = (new File(rootDir, isa)).exists();
7848            } else {
7849                has32BitLibs = false;
7850            }
7851        }
7852
7853        if (has64BitLibs && !has32BitLibs) {
7854            // The package has 64 bit libs, but not 32 bit libs. Its primary
7855            // ABI should be 64 bit. We can safely assume here that the bundled
7856            // native libraries correspond to the most preferred ABI in the list.
7857
7858            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7859            pkg.applicationInfo.secondaryCpuAbi = null;
7860        } else if (has32BitLibs && !has64BitLibs) {
7861            // The package has 32 bit libs but not 64 bit libs. Its primary
7862            // ABI should be 32 bit.
7863
7864            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7865            pkg.applicationInfo.secondaryCpuAbi = null;
7866        } else if (has32BitLibs && has64BitLibs) {
7867            // The application has both 64 and 32 bit bundled libraries. We check
7868            // here that the app declares multiArch support, and warn if it doesn't.
7869            //
7870            // We will be lenient here and record both ABIs. The primary will be the
7871            // ABI that's higher on the list, i.e, a device that's configured to prefer
7872            // 64 bit apps will see a 64 bit primary ABI,
7873
7874            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7875                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7876            }
7877
7878            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7879                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7880                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7881            } else {
7882                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7883                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7884            }
7885        } else {
7886            pkg.applicationInfo.primaryCpuAbi = null;
7887            pkg.applicationInfo.secondaryCpuAbi = null;
7888        }
7889    }
7890
7891    private void killApplication(String pkgName, int appId, String reason) {
7892        // Request the ActivityManager to kill the process(only for existing packages)
7893        // so that we do not end up in a confused state while the user is still using the older
7894        // version of the application while the new one gets installed.
7895        IActivityManager am = ActivityManagerNative.getDefault();
7896        if (am != null) {
7897            try {
7898                am.killApplicationWithAppId(pkgName, appId, reason);
7899            } catch (RemoteException e) {
7900            }
7901        }
7902    }
7903
7904    void removePackageLI(PackageSetting ps, boolean chatty) {
7905        if (DEBUG_INSTALL) {
7906            if (chatty)
7907                Log.d(TAG, "Removing package " + ps.name);
7908        }
7909
7910        // writer
7911        synchronized (mPackages) {
7912            mPackages.remove(ps.name);
7913            final PackageParser.Package pkg = ps.pkg;
7914            if (pkg != null) {
7915                cleanPackageDataStructuresLILPw(pkg, chatty);
7916            }
7917        }
7918    }
7919
7920    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7921        if (DEBUG_INSTALL) {
7922            if (chatty)
7923                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7924        }
7925
7926        // writer
7927        synchronized (mPackages) {
7928            mPackages.remove(pkg.applicationInfo.packageName);
7929            cleanPackageDataStructuresLILPw(pkg, chatty);
7930        }
7931    }
7932
7933    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7934        int N = pkg.providers.size();
7935        StringBuilder r = null;
7936        int i;
7937        for (i=0; i<N; i++) {
7938            PackageParser.Provider p = pkg.providers.get(i);
7939            mProviders.removeProvider(p);
7940            if (p.info.authority == null) {
7941
7942                /* There was another ContentProvider with this authority when
7943                 * this app was installed so this authority is null,
7944                 * Ignore it as we don't have to unregister the provider.
7945                 */
7946                continue;
7947            }
7948            String names[] = p.info.authority.split(";");
7949            for (int j = 0; j < names.length; j++) {
7950                if (mProvidersByAuthority.get(names[j]) == p) {
7951                    mProvidersByAuthority.remove(names[j]);
7952                    if (DEBUG_REMOVE) {
7953                        if (chatty)
7954                            Log.d(TAG, "Unregistered content provider: " + names[j]
7955                                    + ", className = " + p.info.name + ", isSyncable = "
7956                                    + p.info.isSyncable);
7957                    }
7958                }
7959            }
7960            if (DEBUG_REMOVE && chatty) {
7961                if (r == null) {
7962                    r = new StringBuilder(256);
7963                } else {
7964                    r.append(' ');
7965                }
7966                r.append(p.info.name);
7967            }
7968        }
7969        if (r != null) {
7970            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7971        }
7972
7973        N = pkg.services.size();
7974        r = null;
7975        for (i=0; i<N; i++) {
7976            PackageParser.Service s = pkg.services.get(i);
7977            mServices.removeService(s);
7978            if (chatty) {
7979                if (r == null) {
7980                    r = new StringBuilder(256);
7981                } else {
7982                    r.append(' ');
7983                }
7984                r.append(s.info.name);
7985            }
7986        }
7987        if (r != null) {
7988            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7989        }
7990
7991        N = pkg.receivers.size();
7992        r = null;
7993        for (i=0; i<N; i++) {
7994            PackageParser.Activity a = pkg.receivers.get(i);
7995            mReceivers.removeActivity(a, "receiver");
7996            if (DEBUG_REMOVE && chatty) {
7997                if (r == null) {
7998                    r = new StringBuilder(256);
7999                } else {
8000                    r.append(' ');
8001                }
8002                r.append(a.info.name);
8003            }
8004        }
8005        if (r != null) {
8006            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8007        }
8008
8009        N = pkg.activities.size();
8010        r = null;
8011        for (i=0; i<N; i++) {
8012            PackageParser.Activity a = pkg.activities.get(i);
8013            mActivities.removeActivity(a, "activity");
8014            if (DEBUG_REMOVE && chatty) {
8015                if (r == null) {
8016                    r = new StringBuilder(256);
8017                } else {
8018                    r.append(' ');
8019                }
8020                r.append(a.info.name);
8021            }
8022        }
8023        if (r != null) {
8024            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8025        }
8026
8027        N = pkg.permissions.size();
8028        r = null;
8029        for (i=0; i<N; i++) {
8030            PackageParser.Permission p = pkg.permissions.get(i);
8031            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8032            if (bp == null) {
8033                bp = mSettings.mPermissionTrees.get(p.info.name);
8034            }
8035            if (bp != null && bp.perm == p) {
8036                bp.perm = null;
8037                if (DEBUG_REMOVE && chatty) {
8038                    if (r == null) {
8039                        r = new StringBuilder(256);
8040                    } else {
8041                        r.append(' ');
8042                    }
8043                    r.append(p.info.name);
8044                }
8045            }
8046            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8047                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8048                if (appOpPerms != null) {
8049                    appOpPerms.remove(pkg.packageName);
8050                }
8051            }
8052        }
8053        if (r != null) {
8054            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8055        }
8056
8057        N = pkg.requestedPermissions.size();
8058        r = null;
8059        for (i=0; i<N; i++) {
8060            String perm = pkg.requestedPermissions.get(i);
8061            BasePermission bp = mSettings.mPermissions.get(perm);
8062            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8063                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8064                if (appOpPerms != null) {
8065                    appOpPerms.remove(pkg.packageName);
8066                    if (appOpPerms.isEmpty()) {
8067                        mAppOpPermissionPackages.remove(perm);
8068                    }
8069                }
8070            }
8071        }
8072        if (r != null) {
8073            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8074        }
8075
8076        N = pkg.instrumentation.size();
8077        r = null;
8078        for (i=0; i<N; i++) {
8079            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8080            mInstrumentation.remove(a.getComponentName());
8081            if (DEBUG_REMOVE && chatty) {
8082                if (r == null) {
8083                    r = new StringBuilder(256);
8084                } else {
8085                    r.append(' ');
8086                }
8087                r.append(a.info.name);
8088            }
8089        }
8090        if (r != null) {
8091            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8092        }
8093
8094        r = null;
8095        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8096            // Only system apps can hold shared libraries.
8097            if (pkg.libraryNames != null) {
8098                for (i=0; i<pkg.libraryNames.size(); i++) {
8099                    String name = pkg.libraryNames.get(i);
8100                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8101                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8102                        mSharedLibraries.remove(name);
8103                        if (DEBUG_REMOVE && chatty) {
8104                            if (r == null) {
8105                                r = new StringBuilder(256);
8106                            } else {
8107                                r.append(' ');
8108                            }
8109                            r.append(name);
8110                        }
8111                    }
8112                }
8113            }
8114        }
8115        if (r != null) {
8116            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8117        }
8118    }
8119
8120    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8121        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8122            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8123                return true;
8124            }
8125        }
8126        return false;
8127    }
8128
8129    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8130    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8131    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8132
8133    private void updatePermissionsLPw(String changingPkg,
8134            PackageParser.Package pkgInfo, int flags) {
8135        // Make sure there are no dangling permission trees.
8136        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8137        while (it.hasNext()) {
8138            final BasePermission bp = it.next();
8139            if (bp.packageSetting == null) {
8140                // We may not yet have parsed the package, so just see if
8141                // we still know about its settings.
8142                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8143            }
8144            if (bp.packageSetting == null) {
8145                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8146                        + " from package " + bp.sourcePackage);
8147                it.remove();
8148            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8149                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8150                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8151                            + " from package " + bp.sourcePackage);
8152                    flags |= UPDATE_PERMISSIONS_ALL;
8153                    it.remove();
8154                }
8155            }
8156        }
8157
8158        // Make sure all dynamic permissions have been assigned to a package,
8159        // and make sure there are no dangling permissions.
8160        it = mSettings.mPermissions.values().iterator();
8161        while (it.hasNext()) {
8162            final BasePermission bp = it.next();
8163            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8164                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8165                        + bp.name + " pkg=" + bp.sourcePackage
8166                        + " info=" + bp.pendingInfo);
8167                if (bp.packageSetting == null && bp.pendingInfo != null) {
8168                    final BasePermission tree = findPermissionTreeLP(bp.name);
8169                    if (tree != null && tree.perm != null) {
8170                        bp.packageSetting = tree.packageSetting;
8171                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8172                                new PermissionInfo(bp.pendingInfo));
8173                        bp.perm.info.packageName = tree.perm.info.packageName;
8174                        bp.perm.info.name = bp.name;
8175                        bp.uid = tree.uid;
8176                    }
8177                }
8178            }
8179            if (bp.packageSetting == null) {
8180                // We may not yet have parsed the package, so just see if
8181                // we still know about its settings.
8182                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8183            }
8184            if (bp.packageSetting == null) {
8185                Slog.w(TAG, "Removing dangling permission: " + bp.name
8186                        + " from package " + bp.sourcePackage);
8187                it.remove();
8188            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8189                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8190                    Slog.i(TAG, "Removing old permission: " + bp.name
8191                            + " from package " + bp.sourcePackage);
8192                    flags |= UPDATE_PERMISSIONS_ALL;
8193                    it.remove();
8194                }
8195            }
8196        }
8197
8198        // Now update the permissions for all packages, in particular
8199        // replace the granted permissions of the system packages.
8200        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8201            for (PackageParser.Package pkg : mPackages.values()) {
8202                if (pkg != pkgInfo) {
8203                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8204                            changingPkg);
8205                }
8206            }
8207        }
8208
8209        if (pkgInfo != null) {
8210            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8211        }
8212    }
8213
8214    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8215            String packageOfInterest) {
8216        // IMPORTANT: There are two types of permissions: install and runtime.
8217        // Install time permissions are granted when the app is installed to
8218        // all device users and users added in the future. Runtime permissions
8219        // are granted at runtime explicitly to specific users. Normal and signature
8220        // protected permissions are install time permissions. Dangerous permissions
8221        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8222        // otherwise they are runtime permissions. This function does not manage
8223        // runtime permissions except for the case an app targeting Lollipop MR1
8224        // being upgraded to target a newer SDK, in which case dangerous permissions
8225        // are transformed from install time to runtime ones.
8226
8227        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8228        if (ps == null) {
8229            return;
8230        }
8231
8232        PermissionsState permissionsState = ps.getPermissionsState();
8233        PermissionsState origPermissions = permissionsState;
8234
8235        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8236
8237        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8238
8239        boolean changedInstallPermission = false;
8240
8241        if (replace) {
8242            ps.installPermissionsFixed = false;
8243            if (!ps.isSharedUser()) {
8244                origPermissions = new PermissionsState(permissionsState);
8245                permissionsState.reset();
8246            }
8247        }
8248
8249        permissionsState.setGlobalGids(mGlobalGids);
8250
8251        final int N = pkg.requestedPermissions.size();
8252        for (int i=0; i<N; i++) {
8253            final String name = pkg.requestedPermissions.get(i);
8254            final BasePermission bp = mSettings.mPermissions.get(name);
8255
8256            if (DEBUG_INSTALL) {
8257                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8258            }
8259
8260            if (bp == null || bp.packageSetting == null) {
8261                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8262                    Slog.w(TAG, "Unknown permission " + name
8263                            + " in package " + pkg.packageName);
8264                }
8265                continue;
8266            }
8267
8268            final String perm = bp.name;
8269            boolean allowedSig = false;
8270            int grant = GRANT_DENIED;
8271
8272            // Keep track of app op permissions.
8273            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8274                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8275                if (pkgs == null) {
8276                    pkgs = new ArraySet<>();
8277                    mAppOpPermissionPackages.put(bp.name, pkgs);
8278                }
8279                pkgs.add(pkg.packageName);
8280            }
8281
8282            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8283            switch (level) {
8284                case PermissionInfo.PROTECTION_NORMAL: {
8285                    // For all apps normal permissions are install time ones.
8286                    grant = GRANT_INSTALL;
8287                } break;
8288
8289                case PermissionInfo.PROTECTION_DANGEROUS: {
8290                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8291                        // For legacy apps dangerous permissions are install time ones.
8292                        grant = GRANT_INSTALL_LEGACY;
8293                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8294                        // For legacy apps that became modern, install becomes runtime.
8295                        grant = GRANT_UPGRADE;
8296                    } else {
8297                        // For modern apps keep runtime permissions unchanged.
8298                        grant = GRANT_RUNTIME;
8299                    }
8300                } break;
8301
8302                case PermissionInfo.PROTECTION_SIGNATURE: {
8303                    // For all apps signature permissions are install time ones.
8304                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8305                    if (allowedSig) {
8306                        grant = GRANT_INSTALL;
8307                    }
8308                } break;
8309            }
8310
8311            if (DEBUG_INSTALL) {
8312                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8313            }
8314
8315            if (grant != GRANT_DENIED) {
8316                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8317                    // If this is an existing, non-system package, then
8318                    // we can't add any new permissions to it.
8319                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8320                        // Except...  if this is a permission that was added
8321                        // to the platform (note: need to only do this when
8322                        // updating the platform).
8323                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8324                            grant = GRANT_DENIED;
8325                        }
8326                    }
8327                }
8328
8329                switch (grant) {
8330                    case GRANT_INSTALL: {
8331                        // Revoke this as runtime permission to handle the case of
8332                        // a runtime permission being downgraded to an install one.
8333                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8334                            if (origPermissions.getRuntimePermissionState(
8335                                    bp.name, userId) != null) {
8336                                // Revoke the runtime permission and clear the flags.
8337                                origPermissions.revokeRuntimePermission(bp, userId);
8338                                origPermissions.updatePermissionFlags(bp, userId,
8339                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8340                                // If we revoked a permission permission, we have to write.
8341                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8342                                        changedRuntimePermissionUserIds, userId);
8343                            }
8344                        }
8345                        // Grant an install permission.
8346                        if (permissionsState.grantInstallPermission(bp) !=
8347                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8348                            changedInstallPermission = true;
8349                        }
8350                    } break;
8351
8352                    case GRANT_INSTALL_LEGACY: {
8353                        // Grant an install permission.
8354                        if (permissionsState.grantInstallPermission(bp) !=
8355                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8356                            changedInstallPermission = true;
8357                        }
8358                    } break;
8359
8360                    case GRANT_RUNTIME: {
8361                        // Grant previously granted runtime permissions.
8362                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8363                            PermissionState permissionState = origPermissions
8364                                    .getRuntimePermissionState(bp.name, userId);
8365                            final int flags = permissionState != null
8366                                    ? permissionState.getFlags() : 0;
8367                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8368                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8369                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8370                                    // If we cannot put the permission as it was, we have to write.
8371                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8372                                            changedRuntimePermissionUserIds, userId);
8373                                }
8374                            }
8375                            // Propagate the permission flags.
8376                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8377                        }
8378                    } break;
8379
8380                    case GRANT_UPGRADE: {
8381                        // Grant runtime permissions for a previously held install permission.
8382                        PermissionState permissionState = origPermissions
8383                                .getInstallPermissionState(bp.name);
8384                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8385
8386                        if (origPermissions.revokeInstallPermission(bp)
8387                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8388                            // We will be transferring the permission flags, so clear them.
8389                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8390                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8391                            changedInstallPermission = true;
8392                        }
8393
8394                        // If the permission is not to be promoted to runtime we ignore it and
8395                        // also its other flags as they are not applicable to install permissions.
8396                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8397                            for (int userId : currentUserIds) {
8398                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8399                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8400                                    // Transfer the permission flags.
8401                                    permissionsState.updatePermissionFlags(bp, userId,
8402                                            flags, flags);
8403                                    // If we granted the permission, we have to write.
8404                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8405                                            changedRuntimePermissionUserIds, userId);
8406                                }
8407                            }
8408                        }
8409                    } break;
8410
8411                    default: {
8412                        if (packageOfInterest == null
8413                                || packageOfInterest.equals(pkg.packageName)) {
8414                            Slog.w(TAG, "Not granting permission " + perm
8415                                    + " to package " + pkg.packageName
8416                                    + " because it was previously installed without");
8417                        }
8418                    } break;
8419                }
8420            } else {
8421                if (permissionsState.revokeInstallPermission(bp) !=
8422                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8423                    // Also drop the permission flags.
8424                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8425                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8426                    changedInstallPermission = true;
8427                    Slog.i(TAG, "Un-granting permission " + perm
8428                            + " from package " + pkg.packageName
8429                            + " (protectionLevel=" + bp.protectionLevel
8430                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8431                            + ")");
8432                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8433                    // Don't print warning for app op permissions, since it is fine for them
8434                    // not to be granted, there is a UI for the user to decide.
8435                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8436                        Slog.w(TAG, "Not granting permission " + perm
8437                                + " to package " + pkg.packageName
8438                                + " (protectionLevel=" + bp.protectionLevel
8439                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8440                                + ")");
8441                    }
8442                }
8443            }
8444        }
8445
8446        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8447                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8448            // This is the first that we have heard about this package, so the
8449            // permissions we have now selected are fixed until explicitly
8450            // changed.
8451            ps.installPermissionsFixed = true;
8452        }
8453
8454        // Persist the runtime permissions state for users with changes.
8455        for (int userId : changedRuntimePermissionUserIds) {
8456            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
8457        }
8458    }
8459
8460    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8461        boolean allowed = false;
8462        final int NP = PackageParser.NEW_PERMISSIONS.length;
8463        for (int ip=0; ip<NP; ip++) {
8464            final PackageParser.NewPermissionInfo npi
8465                    = PackageParser.NEW_PERMISSIONS[ip];
8466            if (npi.name.equals(perm)
8467                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8468                allowed = true;
8469                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8470                        + pkg.packageName);
8471                break;
8472            }
8473        }
8474        return allowed;
8475    }
8476
8477    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8478            BasePermission bp, PermissionsState origPermissions) {
8479        boolean allowed;
8480        allowed = (compareSignatures(
8481                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8482                        == PackageManager.SIGNATURE_MATCH)
8483                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8484                        == PackageManager.SIGNATURE_MATCH);
8485        if (!allowed && (bp.protectionLevel
8486                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8487            if (isSystemApp(pkg)) {
8488                // For updated system applications, a system permission
8489                // is granted only if it had been defined by the original application.
8490                if (pkg.isUpdatedSystemApp()) {
8491                    final PackageSetting sysPs = mSettings
8492                            .getDisabledSystemPkgLPr(pkg.packageName);
8493                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8494                        // If the original was granted this permission, we take
8495                        // that grant decision as read and propagate it to the
8496                        // update.
8497                        if (sysPs.isPrivileged()) {
8498                            allowed = true;
8499                        }
8500                    } else {
8501                        // The system apk may have been updated with an older
8502                        // version of the one on the data partition, but which
8503                        // granted a new system permission that it didn't have
8504                        // before.  In this case we do want to allow the app to
8505                        // now get the new permission if the ancestral apk is
8506                        // privileged to get it.
8507                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8508                            for (int j=0;
8509                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8510                                if (perm.equals(
8511                                        sysPs.pkg.requestedPermissions.get(j))) {
8512                                    allowed = true;
8513                                    break;
8514                                }
8515                            }
8516                        }
8517                    }
8518                } else {
8519                    allowed = isPrivilegedApp(pkg);
8520                }
8521            }
8522        }
8523        if (!allowed) {
8524            if (!allowed && (bp.protectionLevel
8525                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8526                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.MNC) {
8527                // If this was a previously normal/dangerous permission that got moved
8528                // to a system permission as part of the runtime permission redesign, then
8529                // we still want to blindly grant it to old apps.
8530                allowed = true;
8531            }
8532            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8533                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8534                // If this permission is to be granted to the system installer and
8535                // this app is an installer, then it gets the permission.
8536                allowed = true;
8537            }
8538            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8539                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8540                // If this permission is to be granted to the system verifier and
8541                // this app is a verifier, then it gets the permission.
8542                allowed = true;
8543            }
8544            if (!allowed && (bp.protectionLevel
8545                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8546                    && isSystemApp(pkg)) {
8547                // Any pre-installed system app is allowed to get this permission.
8548                allowed = true;
8549            }
8550            if (!allowed && (bp.protectionLevel
8551                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8552                // For development permissions, a development permission
8553                // is granted only if it was already granted.
8554                allowed = origPermissions.hasInstallPermission(perm);
8555            }
8556        }
8557        return allowed;
8558    }
8559
8560    final class ActivityIntentResolver
8561            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8562        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8563                boolean defaultOnly, int userId) {
8564            if (!sUserManager.exists(userId)) return null;
8565            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8566            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8567        }
8568
8569        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8570                int userId) {
8571            if (!sUserManager.exists(userId)) return null;
8572            mFlags = flags;
8573            return super.queryIntent(intent, resolvedType,
8574                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8575        }
8576
8577        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8578                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8579            if (!sUserManager.exists(userId)) return null;
8580            if (packageActivities == null) {
8581                return null;
8582            }
8583            mFlags = flags;
8584            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8585            final int N = packageActivities.size();
8586            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8587                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8588
8589            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8590            for (int i = 0; i < N; ++i) {
8591                intentFilters = packageActivities.get(i).intents;
8592                if (intentFilters != null && intentFilters.size() > 0) {
8593                    PackageParser.ActivityIntentInfo[] array =
8594                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8595                    intentFilters.toArray(array);
8596                    listCut.add(array);
8597                }
8598            }
8599            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8600        }
8601
8602        public final void addActivity(PackageParser.Activity a, String type) {
8603            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8604            mActivities.put(a.getComponentName(), a);
8605            if (DEBUG_SHOW_INFO)
8606                Log.v(
8607                TAG, "  " + type + " " +
8608                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8609            if (DEBUG_SHOW_INFO)
8610                Log.v(TAG, "    Class=" + a.info.name);
8611            final int NI = a.intents.size();
8612            for (int j=0; j<NI; j++) {
8613                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8614                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8615                    intent.setPriority(0);
8616                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8617                            + a.className + " with priority > 0, forcing to 0");
8618                }
8619                if (DEBUG_SHOW_INFO) {
8620                    Log.v(TAG, "    IntentFilter:");
8621                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8622                }
8623                if (!intent.debugCheck()) {
8624                    Log.w(TAG, "==> For Activity " + a.info.name);
8625                }
8626                addFilter(intent);
8627            }
8628        }
8629
8630        public final void removeActivity(PackageParser.Activity a, String type) {
8631            mActivities.remove(a.getComponentName());
8632            if (DEBUG_SHOW_INFO) {
8633                Log.v(TAG, "  " + type + " "
8634                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8635                                : a.info.name) + ":");
8636                Log.v(TAG, "    Class=" + a.info.name);
8637            }
8638            final int NI = a.intents.size();
8639            for (int j=0; j<NI; j++) {
8640                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8641                if (DEBUG_SHOW_INFO) {
8642                    Log.v(TAG, "    IntentFilter:");
8643                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8644                }
8645                removeFilter(intent);
8646            }
8647        }
8648
8649        @Override
8650        protected boolean allowFilterResult(
8651                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8652            ActivityInfo filterAi = filter.activity.info;
8653            for (int i=dest.size()-1; i>=0; i--) {
8654                ActivityInfo destAi = dest.get(i).activityInfo;
8655                if (destAi.name == filterAi.name
8656                        && destAi.packageName == filterAi.packageName) {
8657                    return false;
8658                }
8659            }
8660            return true;
8661        }
8662
8663        @Override
8664        protected ActivityIntentInfo[] newArray(int size) {
8665            return new ActivityIntentInfo[size];
8666        }
8667
8668        @Override
8669        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8670            if (!sUserManager.exists(userId)) return true;
8671            PackageParser.Package p = filter.activity.owner;
8672            if (p != null) {
8673                PackageSetting ps = (PackageSetting)p.mExtras;
8674                if (ps != null) {
8675                    // System apps are never considered stopped for purposes of
8676                    // filtering, because there may be no way for the user to
8677                    // actually re-launch them.
8678                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8679                            && ps.getStopped(userId);
8680                }
8681            }
8682            return false;
8683        }
8684
8685        @Override
8686        protected boolean isPackageForFilter(String packageName,
8687                PackageParser.ActivityIntentInfo info) {
8688            return packageName.equals(info.activity.owner.packageName);
8689        }
8690
8691        @Override
8692        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8693                int match, int userId) {
8694            if (!sUserManager.exists(userId)) return null;
8695            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8696                return null;
8697            }
8698            final PackageParser.Activity activity = info.activity;
8699            if (mSafeMode && (activity.info.applicationInfo.flags
8700                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8701                return null;
8702            }
8703            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8704            if (ps == null) {
8705                return null;
8706            }
8707            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8708                    ps.readUserState(userId), userId);
8709            if (ai == null) {
8710                return null;
8711            }
8712            final ResolveInfo res = new ResolveInfo();
8713            res.activityInfo = ai;
8714            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8715                res.filter = info;
8716            }
8717            if (info != null) {
8718                res.handleAllWebDataURI = info.handleAllWebDataURI();
8719            }
8720            res.priority = info.getPriority();
8721            res.preferredOrder = activity.owner.mPreferredOrder;
8722            //System.out.println("Result: " + res.activityInfo.className +
8723            //                   " = " + res.priority);
8724            res.match = match;
8725            res.isDefault = info.hasDefault;
8726            res.labelRes = info.labelRes;
8727            res.nonLocalizedLabel = info.nonLocalizedLabel;
8728            if (userNeedsBadging(userId)) {
8729                res.noResourceId = true;
8730            } else {
8731                res.icon = info.icon;
8732            }
8733            res.iconResourceId = info.icon;
8734            res.system = res.activityInfo.applicationInfo.isSystemApp();
8735            return res;
8736        }
8737
8738        @Override
8739        protected void sortResults(List<ResolveInfo> results) {
8740            Collections.sort(results, mResolvePrioritySorter);
8741        }
8742
8743        @Override
8744        protected void dumpFilter(PrintWriter out, String prefix,
8745                PackageParser.ActivityIntentInfo filter) {
8746            out.print(prefix); out.print(
8747                    Integer.toHexString(System.identityHashCode(filter.activity)));
8748                    out.print(' ');
8749                    filter.activity.printComponentShortName(out);
8750                    out.print(" filter ");
8751                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8752        }
8753
8754        @Override
8755        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8756            return filter.activity;
8757        }
8758
8759        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8760            PackageParser.Activity activity = (PackageParser.Activity)label;
8761            out.print(prefix); out.print(
8762                    Integer.toHexString(System.identityHashCode(activity)));
8763                    out.print(' ');
8764                    activity.printComponentShortName(out);
8765            if (count > 1) {
8766                out.print(" ("); out.print(count); out.print(" filters)");
8767            }
8768            out.println();
8769        }
8770
8771//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8772//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8773//            final List<ResolveInfo> retList = Lists.newArrayList();
8774//            while (i.hasNext()) {
8775//                final ResolveInfo resolveInfo = i.next();
8776//                if (isEnabledLP(resolveInfo.activityInfo)) {
8777//                    retList.add(resolveInfo);
8778//                }
8779//            }
8780//            return retList;
8781//        }
8782
8783        // Keys are String (activity class name), values are Activity.
8784        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8785                = new ArrayMap<ComponentName, PackageParser.Activity>();
8786        private int mFlags;
8787    }
8788
8789    private final class ServiceIntentResolver
8790            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8791        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8792                boolean defaultOnly, int userId) {
8793            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8794            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8795        }
8796
8797        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8798                int userId) {
8799            if (!sUserManager.exists(userId)) return null;
8800            mFlags = flags;
8801            return super.queryIntent(intent, resolvedType,
8802                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8803        }
8804
8805        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8806                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8807            if (!sUserManager.exists(userId)) return null;
8808            if (packageServices == null) {
8809                return null;
8810            }
8811            mFlags = flags;
8812            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8813            final int N = packageServices.size();
8814            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8815                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8816
8817            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8818            for (int i = 0; i < N; ++i) {
8819                intentFilters = packageServices.get(i).intents;
8820                if (intentFilters != null && intentFilters.size() > 0) {
8821                    PackageParser.ServiceIntentInfo[] array =
8822                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8823                    intentFilters.toArray(array);
8824                    listCut.add(array);
8825                }
8826            }
8827            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8828        }
8829
8830        public final void addService(PackageParser.Service s) {
8831            mServices.put(s.getComponentName(), s);
8832            if (DEBUG_SHOW_INFO) {
8833                Log.v(TAG, "  "
8834                        + (s.info.nonLocalizedLabel != null
8835                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8836                Log.v(TAG, "    Class=" + s.info.name);
8837            }
8838            final int NI = s.intents.size();
8839            int j;
8840            for (j=0; j<NI; j++) {
8841                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8842                if (DEBUG_SHOW_INFO) {
8843                    Log.v(TAG, "    IntentFilter:");
8844                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8845                }
8846                if (!intent.debugCheck()) {
8847                    Log.w(TAG, "==> For Service " + s.info.name);
8848                }
8849                addFilter(intent);
8850            }
8851        }
8852
8853        public final void removeService(PackageParser.Service s) {
8854            mServices.remove(s.getComponentName());
8855            if (DEBUG_SHOW_INFO) {
8856                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8857                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8858                Log.v(TAG, "    Class=" + s.info.name);
8859            }
8860            final int NI = s.intents.size();
8861            int j;
8862            for (j=0; j<NI; j++) {
8863                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8864                if (DEBUG_SHOW_INFO) {
8865                    Log.v(TAG, "    IntentFilter:");
8866                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8867                }
8868                removeFilter(intent);
8869            }
8870        }
8871
8872        @Override
8873        protected boolean allowFilterResult(
8874                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8875            ServiceInfo filterSi = filter.service.info;
8876            for (int i=dest.size()-1; i>=0; i--) {
8877                ServiceInfo destAi = dest.get(i).serviceInfo;
8878                if (destAi.name == filterSi.name
8879                        && destAi.packageName == filterSi.packageName) {
8880                    return false;
8881                }
8882            }
8883            return true;
8884        }
8885
8886        @Override
8887        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8888            return new PackageParser.ServiceIntentInfo[size];
8889        }
8890
8891        @Override
8892        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8893            if (!sUserManager.exists(userId)) return true;
8894            PackageParser.Package p = filter.service.owner;
8895            if (p != null) {
8896                PackageSetting ps = (PackageSetting)p.mExtras;
8897                if (ps != null) {
8898                    // System apps are never considered stopped for purposes of
8899                    // filtering, because there may be no way for the user to
8900                    // actually re-launch them.
8901                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8902                            && ps.getStopped(userId);
8903                }
8904            }
8905            return false;
8906        }
8907
8908        @Override
8909        protected boolean isPackageForFilter(String packageName,
8910                PackageParser.ServiceIntentInfo info) {
8911            return packageName.equals(info.service.owner.packageName);
8912        }
8913
8914        @Override
8915        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8916                int match, int userId) {
8917            if (!sUserManager.exists(userId)) return null;
8918            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8919            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8920                return null;
8921            }
8922            final PackageParser.Service service = info.service;
8923            if (mSafeMode && (service.info.applicationInfo.flags
8924                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8925                return null;
8926            }
8927            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8928            if (ps == null) {
8929                return null;
8930            }
8931            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8932                    ps.readUserState(userId), userId);
8933            if (si == null) {
8934                return null;
8935            }
8936            final ResolveInfo res = new ResolveInfo();
8937            res.serviceInfo = si;
8938            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8939                res.filter = filter;
8940            }
8941            res.priority = info.getPriority();
8942            res.preferredOrder = service.owner.mPreferredOrder;
8943            res.match = match;
8944            res.isDefault = info.hasDefault;
8945            res.labelRes = info.labelRes;
8946            res.nonLocalizedLabel = info.nonLocalizedLabel;
8947            res.icon = info.icon;
8948            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8949            return res;
8950        }
8951
8952        @Override
8953        protected void sortResults(List<ResolveInfo> results) {
8954            Collections.sort(results, mResolvePrioritySorter);
8955        }
8956
8957        @Override
8958        protected void dumpFilter(PrintWriter out, String prefix,
8959                PackageParser.ServiceIntentInfo filter) {
8960            out.print(prefix); out.print(
8961                    Integer.toHexString(System.identityHashCode(filter.service)));
8962                    out.print(' ');
8963                    filter.service.printComponentShortName(out);
8964                    out.print(" filter ");
8965                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8966        }
8967
8968        @Override
8969        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8970            return filter.service;
8971        }
8972
8973        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8974            PackageParser.Service service = (PackageParser.Service)label;
8975            out.print(prefix); out.print(
8976                    Integer.toHexString(System.identityHashCode(service)));
8977                    out.print(' ');
8978                    service.printComponentShortName(out);
8979            if (count > 1) {
8980                out.print(" ("); out.print(count); out.print(" filters)");
8981            }
8982            out.println();
8983        }
8984
8985//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8986//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8987//            final List<ResolveInfo> retList = Lists.newArrayList();
8988//            while (i.hasNext()) {
8989//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8990//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8991//                    retList.add(resolveInfo);
8992//                }
8993//            }
8994//            return retList;
8995//        }
8996
8997        // Keys are String (activity class name), values are Activity.
8998        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8999                = new ArrayMap<ComponentName, PackageParser.Service>();
9000        private int mFlags;
9001    };
9002
9003    private final class ProviderIntentResolver
9004            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9005        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9006                boolean defaultOnly, int userId) {
9007            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9008            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9009        }
9010
9011        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9012                int userId) {
9013            if (!sUserManager.exists(userId))
9014                return null;
9015            mFlags = flags;
9016            return super.queryIntent(intent, resolvedType,
9017                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9018        }
9019
9020        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9021                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9022            if (!sUserManager.exists(userId))
9023                return null;
9024            if (packageProviders == null) {
9025                return null;
9026            }
9027            mFlags = flags;
9028            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9029            final int N = packageProviders.size();
9030            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9031                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9032
9033            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9034            for (int i = 0; i < N; ++i) {
9035                intentFilters = packageProviders.get(i).intents;
9036                if (intentFilters != null && intentFilters.size() > 0) {
9037                    PackageParser.ProviderIntentInfo[] array =
9038                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9039                    intentFilters.toArray(array);
9040                    listCut.add(array);
9041                }
9042            }
9043            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9044        }
9045
9046        public final void addProvider(PackageParser.Provider p) {
9047            if (mProviders.containsKey(p.getComponentName())) {
9048                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9049                return;
9050            }
9051
9052            mProviders.put(p.getComponentName(), p);
9053            if (DEBUG_SHOW_INFO) {
9054                Log.v(TAG, "  "
9055                        + (p.info.nonLocalizedLabel != null
9056                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9057                Log.v(TAG, "    Class=" + p.info.name);
9058            }
9059            final int NI = p.intents.size();
9060            int j;
9061            for (j = 0; j < NI; j++) {
9062                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9063                if (DEBUG_SHOW_INFO) {
9064                    Log.v(TAG, "    IntentFilter:");
9065                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9066                }
9067                if (!intent.debugCheck()) {
9068                    Log.w(TAG, "==> For Provider " + p.info.name);
9069                }
9070                addFilter(intent);
9071            }
9072        }
9073
9074        public final void removeProvider(PackageParser.Provider p) {
9075            mProviders.remove(p.getComponentName());
9076            if (DEBUG_SHOW_INFO) {
9077                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9078                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9079                Log.v(TAG, "    Class=" + p.info.name);
9080            }
9081            final int NI = p.intents.size();
9082            int j;
9083            for (j = 0; j < NI; j++) {
9084                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9085                if (DEBUG_SHOW_INFO) {
9086                    Log.v(TAG, "    IntentFilter:");
9087                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9088                }
9089                removeFilter(intent);
9090            }
9091        }
9092
9093        @Override
9094        protected boolean allowFilterResult(
9095                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9096            ProviderInfo filterPi = filter.provider.info;
9097            for (int i = dest.size() - 1; i >= 0; i--) {
9098                ProviderInfo destPi = dest.get(i).providerInfo;
9099                if (destPi.name == filterPi.name
9100                        && destPi.packageName == filterPi.packageName) {
9101                    return false;
9102                }
9103            }
9104            return true;
9105        }
9106
9107        @Override
9108        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9109            return new PackageParser.ProviderIntentInfo[size];
9110        }
9111
9112        @Override
9113        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9114            if (!sUserManager.exists(userId))
9115                return true;
9116            PackageParser.Package p = filter.provider.owner;
9117            if (p != null) {
9118                PackageSetting ps = (PackageSetting) p.mExtras;
9119                if (ps != null) {
9120                    // System apps are never considered stopped for purposes of
9121                    // filtering, because there may be no way for the user to
9122                    // actually re-launch them.
9123                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9124                            && ps.getStopped(userId);
9125                }
9126            }
9127            return false;
9128        }
9129
9130        @Override
9131        protected boolean isPackageForFilter(String packageName,
9132                PackageParser.ProviderIntentInfo info) {
9133            return packageName.equals(info.provider.owner.packageName);
9134        }
9135
9136        @Override
9137        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9138                int match, int userId) {
9139            if (!sUserManager.exists(userId))
9140                return null;
9141            final PackageParser.ProviderIntentInfo info = filter;
9142            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9143                return null;
9144            }
9145            final PackageParser.Provider provider = info.provider;
9146            if (mSafeMode && (provider.info.applicationInfo.flags
9147                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9148                return null;
9149            }
9150            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9151            if (ps == null) {
9152                return null;
9153            }
9154            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9155                    ps.readUserState(userId), userId);
9156            if (pi == null) {
9157                return null;
9158            }
9159            final ResolveInfo res = new ResolveInfo();
9160            res.providerInfo = pi;
9161            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9162                res.filter = filter;
9163            }
9164            res.priority = info.getPriority();
9165            res.preferredOrder = provider.owner.mPreferredOrder;
9166            res.match = match;
9167            res.isDefault = info.hasDefault;
9168            res.labelRes = info.labelRes;
9169            res.nonLocalizedLabel = info.nonLocalizedLabel;
9170            res.icon = info.icon;
9171            res.system = res.providerInfo.applicationInfo.isSystemApp();
9172            return res;
9173        }
9174
9175        @Override
9176        protected void sortResults(List<ResolveInfo> results) {
9177            Collections.sort(results, mResolvePrioritySorter);
9178        }
9179
9180        @Override
9181        protected void dumpFilter(PrintWriter out, String prefix,
9182                PackageParser.ProviderIntentInfo filter) {
9183            out.print(prefix);
9184            out.print(
9185                    Integer.toHexString(System.identityHashCode(filter.provider)));
9186            out.print(' ');
9187            filter.provider.printComponentShortName(out);
9188            out.print(" filter ");
9189            out.println(Integer.toHexString(System.identityHashCode(filter)));
9190        }
9191
9192        @Override
9193        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9194            return filter.provider;
9195        }
9196
9197        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9198            PackageParser.Provider provider = (PackageParser.Provider)label;
9199            out.print(prefix); out.print(
9200                    Integer.toHexString(System.identityHashCode(provider)));
9201                    out.print(' ');
9202                    provider.printComponentShortName(out);
9203            if (count > 1) {
9204                out.print(" ("); out.print(count); out.print(" filters)");
9205            }
9206            out.println();
9207        }
9208
9209        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9210                = new ArrayMap<ComponentName, PackageParser.Provider>();
9211        private int mFlags;
9212    };
9213
9214    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9215            new Comparator<ResolveInfo>() {
9216        public int compare(ResolveInfo r1, ResolveInfo r2) {
9217            int v1 = r1.priority;
9218            int v2 = r2.priority;
9219            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9220            if (v1 != v2) {
9221                return (v1 > v2) ? -1 : 1;
9222            }
9223            v1 = r1.preferredOrder;
9224            v2 = r2.preferredOrder;
9225            if (v1 != v2) {
9226                return (v1 > v2) ? -1 : 1;
9227            }
9228            if (r1.isDefault != r2.isDefault) {
9229                return r1.isDefault ? -1 : 1;
9230            }
9231            v1 = r1.match;
9232            v2 = r2.match;
9233            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9234            if (v1 != v2) {
9235                return (v1 > v2) ? -1 : 1;
9236            }
9237            if (r1.system != r2.system) {
9238                return r1.system ? -1 : 1;
9239            }
9240            return 0;
9241        }
9242    };
9243
9244    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9245            new Comparator<ProviderInfo>() {
9246        public int compare(ProviderInfo p1, ProviderInfo p2) {
9247            final int v1 = p1.initOrder;
9248            final int v2 = p2.initOrder;
9249            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9250        }
9251    };
9252
9253    final void sendPackageBroadcast(final String action, final String pkg,
9254            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9255            final int[] userIds) {
9256        mHandler.post(new Runnable() {
9257            @Override
9258            public void run() {
9259                try {
9260                    final IActivityManager am = ActivityManagerNative.getDefault();
9261                    if (am == null) return;
9262                    final int[] resolvedUserIds;
9263                    if (userIds == null) {
9264                        resolvedUserIds = am.getRunningUserIds();
9265                    } else {
9266                        resolvedUserIds = userIds;
9267                    }
9268                    for (int id : resolvedUserIds) {
9269                        final Intent intent = new Intent(action,
9270                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9271                        if (extras != null) {
9272                            intent.putExtras(extras);
9273                        }
9274                        if (targetPkg != null) {
9275                            intent.setPackage(targetPkg);
9276                        }
9277                        // Modify the UID when posting to other users
9278                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9279                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9280                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9281                            intent.putExtra(Intent.EXTRA_UID, uid);
9282                        }
9283                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9284                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9285                        if (DEBUG_BROADCASTS) {
9286                            RuntimeException here = new RuntimeException("here");
9287                            here.fillInStackTrace();
9288                            Slog.d(TAG, "Sending to user " + id + ": "
9289                                    + intent.toShortString(false, true, false, false)
9290                                    + " " + intent.getExtras(), here);
9291                        }
9292                        am.broadcastIntent(null, intent, null, finishedReceiver,
9293                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9294                                null, finishedReceiver != null, false, id);
9295                    }
9296                } catch (RemoteException ex) {
9297                }
9298            }
9299        });
9300    }
9301
9302    /**
9303     * Check if the external storage media is available. This is true if there
9304     * is a mounted external storage medium or if the external storage is
9305     * emulated.
9306     */
9307    private boolean isExternalMediaAvailable() {
9308        return mMediaMounted || Environment.isExternalStorageEmulated();
9309    }
9310
9311    @Override
9312    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9313        // writer
9314        synchronized (mPackages) {
9315            if (!isExternalMediaAvailable()) {
9316                // If the external storage is no longer mounted at this point,
9317                // the caller may not have been able to delete all of this
9318                // packages files and can not delete any more.  Bail.
9319                return null;
9320            }
9321            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9322            if (lastPackage != null) {
9323                pkgs.remove(lastPackage);
9324            }
9325            if (pkgs.size() > 0) {
9326                return pkgs.get(0);
9327            }
9328        }
9329        return null;
9330    }
9331
9332    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9333        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9334                userId, andCode ? 1 : 0, packageName);
9335        if (mSystemReady) {
9336            msg.sendToTarget();
9337        } else {
9338            if (mPostSystemReadyMessages == null) {
9339                mPostSystemReadyMessages = new ArrayList<>();
9340            }
9341            mPostSystemReadyMessages.add(msg);
9342        }
9343    }
9344
9345    void startCleaningPackages() {
9346        // reader
9347        synchronized (mPackages) {
9348            if (!isExternalMediaAvailable()) {
9349                return;
9350            }
9351            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9352                return;
9353            }
9354        }
9355        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9356        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9357        IActivityManager am = ActivityManagerNative.getDefault();
9358        if (am != null) {
9359            try {
9360                am.startService(null, intent, null, mContext.getOpPackageName(),
9361                        UserHandle.USER_OWNER);
9362            } catch (RemoteException e) {
9363            }
9364        }
9365    }
9366
9367    @Override
9368    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9369            int installFlags, String installerPackageName, VerificationParams verificationParams,
9370            String packageAbiOverride) {
9371        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9372                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9373    }
9374
9375    @Override
9376    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9377            int installFlags, String installerPackageName, VerificationParams verificationParams,
9378            String packageAbiOverride, int userId) {
9379        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9380
9381        final int callingUid = Binder.getCallingUid();
9382        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9383
9384        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9385            try {
9386                if (observer != null) {
9387                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9388                }
9389            } catch (RemoteException re) {
9390            }
9391            return;
9392        }
9393
9394        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9395            installFlags |= PackageManager.INSTALL_FROM_ADB;
9396
9397        } else {
9398            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9399            // about installerPackageName.
9400
9401            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9402            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9403        }
9404
9405        UserHandle user;
9406        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9407            user = UserHandle.ALL;
9408        } else {
9409            user = new UserHandle(userId);
9410        }
9411
9412        // Only system components can circumvent runtime permissions when installing.
9413        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9414                && mContext.checkCallingOrSelfPermission(Manifest.permission
9415                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9416            throw new SecurityException("You need the "
9417                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9418                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9419        }
9420
9421        verificationParams.setInstallerUid(callingUid);
9422
9423        final File originFile = new File(originPath);
9424        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9425
9426        final Message msg = mHandler.obtainMessage(INIT_COPY);
9427        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9428                null, verificationParams, user, packageAbiOverride);
9429        mHandler.sendMessage(msg);
9430    }
9431
9432    void installStage(String packageName, File stagedDir, String stagedCid,
9433            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9434            String installerPackageName, int installerUid, UserHandle user) {
9435        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9436                params.referrerUri, installerUid, null);
9437        verifParams.setInstallerUid(installerUid);
9438
9439        final OriginInfo origin;
9440        if (stagedDir != null) {
9441            origin = OriginInfo.fromStagedFile(stagedDir);
9442        } else {
9443            origin = OriginInfo.fromStagedContainer(stagedCid);
9444        }
9445
9446        final Message msg = mHandler.obtainMessage(INIT_COPY);
9447        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9448                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
9449        mHandler.sendMessage(msg);
9450    }
9451
9452    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9453        Bundle extras = new Bundle(1);
9454        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9455
9456        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9457                packageName, extras, null, null, new int[] {userId});
9458        try {
9459            IActivityManager am = ActivityManagerNative.getDefault();
9460            final boolean isSystem =
9461                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9462            if (isSystem && am.isUserRunning(userId, false)) {
9463                // The just-installed/enabled app is bundled on the system, so presumed
9464                // to be able to run automatically without needing an explicit launch.
9465                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9466                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9467                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9468                        .setPackage(packageName);
9469                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9470                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9471            }
9472        } catch (RemoteException e) {
9473            // shouldn't happen
9474            Slog.w(TAG, "Unable to bootstrap installed package", e);
9475        }
9476    }
9477
9478    @Override
9479    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9480            int userId) {
9481        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9482        PackageSetting pkgSetting;
9483        final int uid = Binder.getCallingUid();
9484        enforceCrossUserPermission(uid, userId, true, true,
9485                "setApplicationHiddenSetting for user " + userId);
9486
9487        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9488            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9489            return false;
9490        }
9491
9492        long callingId = Binder.clearCallingIdentity();
9493        try {
9494            boolean sendAdded = false;
9495            boolean sendRemoved = false;
9496            // writer
9497            synchronized (mPackages) {
9498                pkgSetting = mSettings.mPackages.get(packageName);
9499                if (pkgSetting == null) {
9500                    return false;
9501                }
9502                if (pkgSetting.getHidden(userId) != hidden) {
9503                    pkgSetting.setHidden(hidden, userId);
9504                    mSettings.writePackageRestrictionsLPr(userId);
9505                    if (hidden) {
9506                        sendRemoved = true;
9507                    } else {
9508                        sendAdded = true;
9509                    }
9510                }
9511            }
9512            if (sendAdded) {
9513                sendPackageAddedForUser(packageName, pkgSetting, userId);
9514                return true;
9515            }
9516            if (sendRemoved) {
9517                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9518                        "hiding pkg");
9519                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9520            }
9521        } finally {
9522            Binder.restoreCallingIdentity(callingId);
9523        }
9524        return false;
9525    }
9526
9527    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9528            int userId) {
9529        final PackageRemovedInfo info = new PackageRemovedInfo();
9530        info.removedPackage = packageName;
9531        info.removedUsers = new int[] {userId};
9532        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9533        info.sendBroadcast(false, false, false);
9534    }
9535
9536    /**
9537     * Returns true if application is not found or there was an error. Otherwise it returns
9538     * the hidden state of the package for the given user.
9539     */
9540    @Override
9541    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9542        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9543        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9544                false, "getApplicationHidden for user " + userId);
9545        PackageSetting pkgSetting;
9546        long callingId = Binder.clearCallingIdentity();
9547        try {
9548            // writer
9549            synchronized (mPackages) {
9550                pkgSetting = mSettings.mPackages.get(packageName);
9551                if (pkgSetting == null) {
9552                    return true;
9553                }
9554                return pkgSetting.getHidden(userId);
9555            }
9556        } finally {
9557            Binder.restoreCallingIdentity(callingId);
9558        }
9559    }
9560
9561    /**
9562     * @hide
9563     */
9564    @Override
9565    public int installExistingPackageAsUser(String packageName, int userId) {
9566        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9567                null);
9568        PackageSetting pkgSetting;
9569        final int uid = Binder.getCallingUid();
9570        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9571                + userId);
9572        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9573            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9574        }
9575
9576        long callingId = Binder.clearCallingIdentity();
9577        try {
9578            boolean sendAdded = false;
9579
9580            // writer
9581            synchronized (mPackages) {
9582                pkgSetting = mSettings.mPackages.get(packageName);
9583                if (pkgSetting == null) {
9584                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9585                }
9586                if (!pkgSetting.getInstalled(userId)) {
9587                    pkgSetting.setInstalled(true, userId);
9588                    pkgSetting.setHidden(false, userId);
9589                    mSettings.writePackageRestrictionsLPr(userId);
9590                    sendAdded = true;
9591                }
9592            }
9593
9594            if (sendAdded) {
9595                sendPackageAddedForUser(packageName, pkgSetting, userId);
9596            }
9597        } finally {
9598            Binder.restoreCallingIdentity(callingId);
9599        }
9600
9601        return PackageManager.INSTALL_SUCCEEDED;
9602    }
9603
9604    boolean isUserRestricted(int userId, String restrictionKey) {
9605        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9606        if (restrictions.getBoolean(restrictionKey, false)) {
9607            Log.w(TAG, "User is restricted: " + restrictionKey);
9608            return true;
9609        }
9610        return false;
9611    }
9612
9613    @Override
9614    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9615        mContext.enforceCallingOrSelfPermission(
9616                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9617                "Only package verification agents can verify applications");
9618
9619        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9620        final PackageVerificationResponse response = new PackageVerificationResponse(
9621                verificationCode, Binder.getCallingUid());
9622        msg.arg1 = id;
9623        msg.obj = response;
9624        mHandler.sendMessage(msg);
9625    }
9626
9627    @Override
9628    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9629            long millisecondsToDelay) {
9630        mContext.enforceCallingOrSelfPermission(
9631                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9632                "Only package verification agents can extend verification timeouts");
9633
9634        final PackageVerificationState state = mPendingVerification.get(id);
9635        final PackageVerificationResponse response = new PackageVerificationResponse(
9636                verificationCodeAtTimeout, Binder.getCallingUid());
9637
9638        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9639            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9640        }
9641        if (millisecondsToDelay < 0) {
9642            millisecondsToDelay = 0;
9643        }
9644        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9645                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9646            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9647        }
9648
9649        if ((state != null) && !state.timeoutExtended()) {
9650            state.extendTimeout();
9651
9652            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9653            msg.arg1 = id;
9654            msg.obj = response;
9655            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9656        }
9657    }
9658
9659    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9660            int verificationCode, UserHandle user) {
9661        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9662        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9663        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9664        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9665        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9666
9667        mContext.sendBroadcastAsUser(intent, user,
9668                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9669    }
9670
9671    private ComponentName matchComponentForVerifier(String packageName,
9672            List<ResolveInfo> receivers) {
9673        ActivityInfo targetReceiver = null;
9674
9675        final int NR = receivers.size();
9676        for (int i = 0; i < NR; i++) {
9677            final ResolveInfo info = receivers.get(i);
9678            if (info.activityInfo == null) {
9679                continue;
9680            }
9681
9682            if (packageName.equals(info.activityInfo.packageName)) {
9683                targetReceiver = info.activityInfo;
9684                break;
9685            }
9686        }
9687
9688        if (targetReceiver == null) {
9689            return null;
9690        }
9691
9692        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9693    }
9694
9695    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9696            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9697        if (pkgInfo.verifiers.length == 0) {
9698            return null;
9699        }
9700
9701        final int N = pkgInfo.verifiers.length;
9702        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9703        for (int i = 0; i < N; i++) {
9704            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9705
9706            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9707                    receivers);
9708            if (comp == null) {
9709                continue;
9710            }
9711
9712            final int verifierUid = getUidForVerifier(verifierInfo);
9713            if (verifierUid == -1) {
9714                continue;
9715            }
9716
9717            if (DEBUG_VERIFY) {
9718                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9719                        + " with the correct signature");
9720            }
9721            sufficientVerifiers.add(comp);
9722            verificationState.addSufficientVerifier(verifierUid);
9723        }
9724
9725        return sufficientVerifiers;
9726    }
9727
9728    private int getUidForVerifier(VerifierInfo verifierInfo) {
9729        synchronized (mPackages) {
9730            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9731            if (pkg == null) {
9732                return -1;
9733            } else if (pkg.mSignatures.length != 1) {
9734                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9735                        + " has more than one signature; ignoring");
9736                return -1;
9737            }
9738
9739            /*
9740             * If the public key of the package's signature does not match
9741             * our expected public key, then this is a different package and
9742             * we should skip.
9743             */
9744
9745            final byte[] expectedPublicKey;
9746            try {
9747                final Signature verifierSig = pkg.mSignatures[0];
9748                final PublicKey publicKey = verifierSig.getPublicKey();
9749                expectedPublicKey = publicKey.getEncoded();
9750            } catch (CertificateException e) {
9751                return -1;
9752            }
9753
9754            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9755
9756            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9757                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9758                        + " does not have the expected public key; ignoring");
9759                return -1;
9760            }
9761
9762            return pkg.applicationInfo.uid;
9763        }
9764    }
9765
9766    @Override
9767    public void finishPackageInstall(int token) {
9768        enforceSystemOrRoot("Only the system is allowed to finish installs");
9769
9770        if (DEBUG_INSTALL) {
9771            Slog.v(TAG, "BM finishing package install for " + token);
9772        }
9773
9774        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9775        mHandler.sendMessage(msg);
9776    }
9777
9778    /**
9779     * Get the verification agent timeout.
9780     *
9781     * @return verification timeout in milliseconds
9782     */
9783    private long getVerificationTimeout() {
9784        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9785                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9786                DEFAULT_VERIFICATION_TIMEOUT);
9787    }
9788
9789    /**
9790     * Get the default verification agent response code.
9791     *
9792     * @return default verification response code
9793     */
9794    private int getDefaultVerificationResponse() {
9795        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9796                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9797                DEFAULT_VERIFICATION_RESPONSE);
9798    }
9799
9800    /**
9801     * Check whether or not package verification has been enabled.
9802     *
9803     * @return true if verification should be performed
9804     */
9805    private boolean isVerificationEnabled(int userId, int installFlags) {
9806        if (!DEFAULT_VERIFY_ENABLE) {
9807            return false;
9808        }
9809
9810        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9811
9812        // Check if installing from ADB
9813        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9814            // Do not run verification in a test harness environment
9815            if (ActivityManager.isRunningInTestHarness()) {
9816                return false;
9817            }
9818            if (ensureVerifyAppsEnabled) {
9819                return true;
9820            }
9821            // Check if the developer does not want package verification for ADB installs
9822            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9823                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9824                return false;
9825            }
9826        }
9827
9828        if (ensureVerifyAppsEnabled) {
9829            return true;
9830        }
9831
9832        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9833                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9834    }
9835
9836    @Override
9837    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9838            throws RemoteException {
9839        mContext.enforceCallingOrSelfPermission(
9840                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9841                "Only intentfilter verification agents can verify applications");
9842
9843        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9844        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9845                Binder.getCallingUid(), verificationCode, failedDomains);
9846        msg.arg1 = id;
9847        msg.obj = response;
9848        mHandler.sendMessage(msg);
9849    }
9850
9851    @Override
9852    public int getIntentVerificationStatus(String packageName, int userId) {
9853        synchronized (mPackages) {
9854            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9855        }
9856    }
9857
9858    @Override
9859    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9860        mContext.enforceCallingOrSelfPermission(
9861                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9862
9863        boolean result = false;
9864        synchronized (mPackages) {
9865            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9866        }
9867        if (result) {
9868            scheduleWritePackageRestrictionsLocked(userId);
9869        }
9870        return result;
9871    }
9872
9873    @Override
9874    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9875        synchronized (mPackages) {
9876            return mSettings.getIntentFilterVerificationsLPr(packageName);
9877        }
9878    }
9879
9880    @Override
9881    public List<IntentFilter> getAllIntentFilters(String packageName) {
9882        if (TextUtils.isEmpty(packageName)) {
9883            return Collections.<IntentFilter>emptyList();
9884        }
9885        synchronized (mPackages) {
9886            PackageParser.Package pkg = mPackages.get(packageName);
9887            if (pkg == null || pkg.activities == null) {
9888                return Collections.<IntentFilter>emptyList();
9889            }
9890            final int count = pkg.activities.size();
9891            ArrayList<IntentFilter> result = new ArrayList<>();
9892            for (int n=0; n<count; n++) {
9893                PackageParser.Activity activity = pkg.activities.get(n);
9894                if (activity.intents != null || activity.intents.size() > 0) {
9895                    result.addAll(activity.intents);
9896                }
9897            }
9898            return result;
9899        }
9900    }
9901
9902    @Override
9903    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9904        mContext.enforceCallingOrSelfPermission(
9905                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
9906
9907        synchronized (mPackages) {
9908            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
9909            if (packageName != null) {
9910                result |= updateIntentVerificationStatus(packageName,
9911                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9912                        UserHandle.myUserId());
9913                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
9914                        packageName, userId);
9915            }
9916            return result;
9917        }
9918    }
9919
9920    @Override
9921    public String getDefaultBrowserPackageName(int userId) {
9922        synchronized (mPackages) {
9923            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9924        }
9925    }
9926
9927    /**
9928     * Get the "allow unknown sources" setting.
9929     *
9930     * @return the current "allow unknown sources" setting
9931     */
9932    private int getUnknownSourcesSettings() {
9933        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9934                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9935                -1);
9936    }
9937
9938    @Override
9939    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9940        final int uid = Binder.getCallingUid();
9941        // writer
9942        synchronized (mPackages) {
9943            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9944            if (targetPackageSetting == null) {
9945                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9946            }
9947
9948            PackageSetting installerPackageSetting;
9949            if (installerPackageName != null) {
9950                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9951                if (installerPackageSetting == null) {
9952                    throw new IllegalArgumentException("Unknown installer package: "
9953                            + installerPackageName);
9954                }
9955            } else {
9956                installerPackageSetting = null;
9957            }
9958
9959            Signature[] callerSignature;
9960            Object obj = mSettings.getUserIdLPr(uid);
9961            if (obj != null) {
9962                if (obj instanceof SharedUserSetting) {
9963                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9964                } else if (obj instanceof PackageSetting) {
9965                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9966                } else {
9967                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9968                }
9969            } else {
9970                throw new SecurityException("Unknown calling uid " + uid);
9971            }
9972
9973            // Verify: can't set installerPackageName to a package that is
9974            // not signed with the same cert as the caller.
9975            if (installerPackageSetting != null) {
9976                if (compareSignatures(callerSignature,
9977                        installerPackageSetting.signatures.mSignatures)
9978                        != PackageManager.SIGNATURE_MATCH) {
9979                    throw new SecurityException(
9980                            "Caller does not have same cert as new installer package "
9981                            + installerPackageName);
9982                }
9983            }
9984
9985            // Verify: if target already has an installer package, it must
9986            // be signed with the same cert as the caller.
9987            if (targetPackageSetting.installerPackageName != null) {
9988                PackageSetting setting = mSettings.mPackages.get(
9989                        targetPackageSetting.installerPackageName);
9990                // If the currently set package isn't valid, then it's always
9991                // okay to change it.
9992                if (setting != null) {
9993                    if (compareSignatures(callerSignature,
9994                            setting.signatures.mSignatures)
9995                            != PackageManager.SIGNATURE_MATCH) {
9996                        throw new SecurityException(
9997                                "Caller does not have same cert as old installer package "
9998                                + targetPackageSetting.installerPackageName);
9999                    }
10000                }
10001            }
10002
10003            // Okay!
10004            targetPackageSetting.installerPackageName = installerPackageName;
10005            scheduleWriteSettingsLocked();
10006        }
10007    }
10008
10009    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10010        // Queue up an async operation since the package installation may take a little while.
10011        mHandler.post(new Runnable() {
10012            public void run() {
10013                mHandler.removeCallbacks(this);
10014                 // Result object to be returned
10015                PackageInstalledInfo res = new PackageInstalledInfo();
10016                res.returnCode = currentStatus;
10017                res.uid = -1;
10018                res.pkg = null;
10019                res.removedInfo = new PackageRemovedInfo();
10020                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10021                    args.doPreInstall(res.returnCode);
10022                    synchronized (mInstallLock) {
10023                        installPackageLI(args, res);
10024                    }
10025                    args.doPostInstall(res.returnCode, res.uid);
10026                }
10027
10028                // A restore should be performed at this point if (a) the install
10029                // succeeded, (b) the operation is not an update, and (c) the new
10030                // package has not opted out of backup participation.
10031                final boolean update = res.removedInfo.removedPackage != null;
10032                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10033                boolean doRestore = !update
10034                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10035
10036                // Set up the post-install work request bookkeeping.  This will be used
10037                // and cleaned up by the post-install event handling regardless of whether
10038                // there's a restore pass performed.  Token values are >= 1.
10039                int token;
10040                if (mNextInstallToken < 0) mNextInstallToken = 1;
10041                token = mNextInstallToken++;
10042
10043                PostInstallData data = new PostInstallData(args, res);
10044                mRunningInstalls.put(token, data);
10045                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10046
10047                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10048                    // Pass responsibility to the Backup Manager.  It will perform a
10049                    // restore if appropriate, then pass responsibility back to the
10050                    // Package Manager to run the post-install observer callbacks
10051                    // and broadcasts.
10052                    IBackupManager bm = IBackupManager.Stub.asInterface(
10053                            ServiceManager.getService(Context.BACKUP_SERVICE));
10054                    if (bm != null) {
10055                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10056                                + " to BM for possible restore");
10057                        try {
10058                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10059                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10060                            } else {
10061                                doRestore = false;
10062                            }
10063                        } catch (RemoteException e) {
10064                            // can't happen; the backup manager is local
10065                        } catch (Exception e) {
10066                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10067                            doRestore = false;
10068                        }
10069                    } else {
10070                        Slog.e(TAG, "Backup Manager not found!");
10071                        doRestore = false;
10072                    }
10073                }
10074
10075                if (!doRestore) {
10076                    // No restore possible, or the Backup Manager was mysteriously not
10077                    // available -- just fire the post-install work request directly.
10078                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10079                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10080                    mHandler.sendMessage(msg);
10081                }
10082            }
10083        });
10084    }
10085
10086    private abstract class HandlerParams {
10087        private static final int MAX_RETRIES = 4;
10088
10089        /**
10090         * Number of times startCopy() has been attempted and had a non-fatal
10091         * error.
10092         */
10093        private int mRetries = 0;
10094
10095        /** User handle for the user requesting the information or installation. */
10096        private final UserHandle mUser;
10097
10098        HandlerParams(UserHandle user) {
10099            mUser = user;
10100        }
10101
10102        UserHandle getUser() {
10103            return mUser;
10104        }
10105
10106        final boolean startCopy() {
10107            boolean res;
10108            try {
10109                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10110
10111                if (++mRetries > MAX_RETRIES) {
10112                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10113                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10114                    handleServiceError();
10115                    return false;
10116                } else {
10117                    handleStartCopy();
10118                    res = true;
10119                }
10120            } catch (RemoteException e) {
10121                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10122                mHandler.sendEmptyMessage(MCS_RECONNECT);
10123                res = false;
10124            }
10125            handleReturnCode();
10126            return res;
10127        }
10128
10129        final void serviceError() {
10130            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10131            handleServiceError();
10132            handleReturnCode();
10133        }
10134
10135        abstract void handleStartCopy() throws RemoteException;
10136        abstract void handleServiceError();
10137        abstract void handleReturnCode();
10138    }
10139
10140    class MeasureParams extends HandlerParams {
10141        private final PackageStats mStats;
10142        private boolean mSuccess;
10143
10144        private final IPackageStatsObserver mObserver;
10145
10146        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10147            super(new UserHandle(stats.userHandle));
10148            mObserver = observer;
10149            mStats = stats;
10150        }
10151
10152        @Override
10153        public String toString() {
10154            return "MeasureParams{"
10155                + Integer.toHexString(System.identityHashCode(this))
10156                + " " + mStats.packageName + "}";
10157        }
10158
10159        @Override
10160        void handleStartCopy() throws RemoteException {
10161            synchronized (mInstallLock) {
10162                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10163            }
10164
10165            if (mSuccess) {
10166                final boolean mounted;
10167                if (Environment.isExternalStorageEmulated()) {
10168                    mounted = true;
10169                } else {
10170                    final String status = Environment.getExternalStorageState();
10171                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10172                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10173                }
10174
10175                if (mounted) {
10176                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10177
10178                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10179                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10180
10181                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10182                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10183
10184                    // Always subtract cache size, since it's a subdirectory
10185                    mStats.externalDataSize -= mStats.externalCacheSize;
10186
10187                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10188                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10189
10190                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10191                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10192                }
10193            }
10194        }
10195
10196        @Override
10197        void handleReturnCode() {
10198            if (mObserver != null) {
10199                try {
10200                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10201                } catch (RemoteException e) {
10202                    Slog.i(TAG, "Observer no longer exists.");
10203                }
10204            }
10205        }
10206
10207        @Override
10208        void handleServiceError() {
10209            Slog.e(TAG, "Could not measure application " + mStats.packageName
10210                            + " external storage");
10211        }
10212    }
10213
10214    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10215            throws RemoteException {
10216        long result = 0;
10217        for (File path : paths) {
10218            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10219        }
10220        return result;
10221    }
10222
10223    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10224        for (File path : paths) {
10225            try {
10226                mcs.clearDirectory(path.getAbsolutePath());
10227            } catch (RemoteException e) {
10228            }
10229        }
10230    }
10231
10232    static class OriginInfo {
10233        /**
10234         * Location where install is coming from, before it has been
10235         * copied/renamed into place. This could be a single monolithic APK
10236         * file, or a cluster directory. This location may be untrusted.
10237         */
10238        final File file;
10239        final String cid;
10240
10241        /**
10242         * Flag indicating that {@link #file} or {@link #cid} has already been
10243         * staged, meaning downstream users don't need to defensively copy the
10244         * contents.
10245         */
10246        final boolean staged;
10247
10248        /**
10249         * Flag indicating that {@link #file} or {@link #cid} is an already
10250         * installed app that is being moved.
10251         */
10252        final boolean existing;
10253
10254        final String resolvedPath;
10255        final File resolvedFile;
10256
10257        static OriginInfo fromNothing() {
10258            return new OriginInfo(null, null, false, false);
10259        }
10260
10261        static OriginInfo fromUntrustedFile(File file) {
10262            return new OriginInfo(file, null, false, false);
10263        }
10264
10265        static OriginInfo fromExistingFile(File file) {
10266            return new OriginInfo(file, null, false, true);
10267        }
10268
10269        static OriginInfo fromStagedFile(File file) {
10270            return new OriginInfo(file, null, true, false);
10271        }
10272
10273        static OriginInfo fromStagedContainer(String cid) {
10274            return new OriginInfo(null, cid, true, false);
10275        }
10276
10277        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10278            this.file = file;
10279            this.cid = cid;
10280            this.staged = staged;
10281            this.existing = existing;
10282
10283            if (cid != null) {
10284                resolvedPath = PackageHelper.getSdDir(cid);
10285                resolvedFile = new File(resolvedPath);
10286            } else if (file != null) {
10287                resolvedPath = file.getAbsolutePath();
10288                resolvedFile = file;
10289            } else {
10290                resolvedPath = null;
10291                resolvedFile = null;
10292            }
10293        }
10294    }
10295
10296    class MoveInfo {
10297        final int moveId;
10298        final String fromUuid;
10299        final String toUuid;
10300        final String packageName;
10301        final String dataAppName;
10302        final int appId;
10303        final String seinfo;
10304
10305        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10306                String dataAppName, int appId, String seinfo) {
10307            this.moveId = moveId;
10308            this.fromUuid = fromUuid;
10309            this.toUuid = toUuid;
10310            this.packageName = packageName;
10311            this.dataAppName = dataAppName;
10312            this.appId = appId;
10313            this.seinfo = seinfo;
10314        }
10315    }
10316
10317    class InstallParams extends HandlerParams {
10318        final OriginInfo origin;
10319        final MoveInfo move;
10320        final IPackageInstallObserver2 observer;
10321        int installFlags;
10322        final String installerPackageName;
10323        final String volumeUuid;
10324        final VerificationParams verificationParams;
10325        private InstallArgs mArgs;
10326        private int mRet;
10327        final String packageAbiOverride;
10328
10329        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10330                int installFlags, String installerPackageName, String volumeUuid,
10331                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
10332            super(user);
10333            this.origin = origin;
10334            this.move = move;
10335            this.observer = observer;
10336            this.installFlags = installFlags;
10337            this.installerPackageName = installerPackageName;
10338            this.volumeUuid = volumeUuid;
10339            this.verificationParams = verificationParams;
10340            this.packageAbiOverride = packageAbiOverride;
10341        }
10342
10343        @Override
10344        public String toString() {
10345            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10346                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10347        }
10348
10349        public ManifestDigest getManifestDigest() {
10350            if (verificationParams == null) {
10351                return null;
10352            }
10353            return verificationParams.getManifestDigest();
10354        }
10355
10356        private int installLocationPolicy(PackageInfoLite pkgLite) {
10357            String packageName = pkgLite.packageName;
10358            int installLocation = pkgLite.installLocation;
10359            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10360            // reader
10361            synchronized (mPackages) {
10362                PackageParser.Package pkg = mPackages.get(packageName);
10363                if (pkg != null) {
10364                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10365                        // Check for downgrading.
10366                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10367                            try {
10368                                checkDowngrade(pkg, pkgLite);
10369                            } catch (PackageManagerException e) {
10370                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10371                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10372                            }
10373                        }
10374                        // Check for updated system application.
10375                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10376                            if (onSd) {
10377                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10378                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10379                            }
10380                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10381                        } else {
10382                            if (onSd) {
10383                                // Install flag overrides everything.
10384                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10385                            }
10386                            // If current upgrade specifies particular preference
10387                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10388                                // Application explicitly specified internal.
10389                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10390                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10391                                // App explictly prefers external. Let policy decide
10392                            } else {
10393                                // Prefer previous location
10394                                if (isExternal(pkg)) {
10395                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10396                                }
10397                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10398                            }
10399                        }
10400                    } else {
10401                        // Invalid install. Return error code
10402                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10403                    }
10404                }
10405            }
10406            // All the special cases have been taken care of.
10407            // Return result based on recommended install location.
10408            if (onSd) {
10409                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10410            }
10411            return pkgLite.recommendedInstallLocation;
10412        }
10413
10414        /*
10415         * Invoke remote method to get package information and install
10416         * location values. Override install location based on default
10417         * policy if needed and then create install arguments based
10418         * on the install location.
10419         */
10420        public void handleStartCopy() throws RemoteException {
10421            int ret = PackageManager.INSTALL_SUCCEEDED;
10422
10423            // If we're already staged, we've firmly committed to an install location
10424            if (origin.staged) {
10425                if (origin.file != null) {
10426                    installFlags |= PackageManager.INSTALL_INTERNAL;
10427                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10428                } else if (origin.cid != null) {
10429                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10430                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10431                } else {
10432                    throw new IllegalStateException("Invalid stage location");
10433                }
10434            }
10435
10436            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10437            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10438
10439            PackageInfoLite pkgLite = null;
10440
10441            if (onInt && onSd) {
10442                // Check if both bits are set.
10443                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10444                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10445            } else {
10446                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10447                        packageAbiOverride);
10448
10449                /*
10450                 * If we have too little free space, try to free cache
10451                 * before giving up.
10452                 */
10453                if (!origin.staged && pkgLite.recommendedInstallLocation
10454                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10455                    // TODO: focus freeing disk space on the target device
10456                    final StorageManager storage = StorageManager.from(mContext);
10457                    final long lowThreshold = storage.getStorageLowBytes(
10458                            Environment.getDataDirectory());
10459
10460                    final long sizeBytes = mContainerService.calculateInstalledSize(
10461                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10462
10463                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10464                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10465                                installFlags, packageAbiOverride);
10466                    }
10467
10468                    /*
10469                     * The cache free must have deleted the file we
10470                     * downloaded to install.
10471                     *
10472                     * TODO: fix the "freeCache" call to not delete
10473                     *       the file we care about.
10474                     */
10475                    if (pkgLite.recommendedInstallLocation
10476                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10477                        pkgLite.recommendedInstallLocation
10478                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10479                    }
10480                }
10481            }
10482
10483            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10484                int loc = pkgLite.recommendedInstallLocation;
10485                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10486                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10487                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10488                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10489                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10490                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10491                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10492                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10493                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10494                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10495                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10496                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10497                } else {
10498                    // Override with defaults if needed.
10499                    loc = installLocationPolicy(pkgLite);
10500                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10501                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10502                    } else if (!onSd && !onInt) {
10503                        // Override install location with flags
10504                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10505                            // Set the flag to install on external media.
10506                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10507                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10508                        } else {
10509                            // Make sure the flag for installing on external
10510                            // media is unset
10511                            installFlags |= PackageManager.INSTALL_INTERNAL;
10512                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10513                        }
10514                    }
10515                }
10516            }
10517
10518            final InstallArgs args = createInstallArgs(this);
10519            mArgs = args;
10520
10521            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10522                 /*
10523                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10524                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10525                 */
10526                int userIdentifier = getUser().getIdentifier();
10527                if (userIdentifier == UserHandle.USER_ALL
10528                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10529                    userIdentifier = UserHandle.USER_OWNER;
10530                }
10531
10532                /*
10533                 * Determine if we have any installed package verifiers. If we
10534                 * do, then we'll defer to them to verify the packages.
10535                 */
10536                final int requiredUid = mRequiredVerifierPackage == null ? -1
10537                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10538                if (!origin.existing && requiredUid != -1
10539                        && isVerificationEnabled(userIdentifier, installFlags)) {
10540                    final Intent verification = new Intent(
10541                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10542                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10543                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10544                            PACKAGE_MIME_TYPE);
10545                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10546
10547                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10548                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10549                            0 /* TODO: Which userId? */);
10550
10551                    if (DEBUG_VERIFY) {
10552                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10553                                + verification.toString() + " with " + pkgLite.verifiers.length
10554                                + " optional verifiers");
10555                    }
10556
10557                    final int verificationId = mPendingVerificationToken++;
10558
10559                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10560
10561                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10562                            installerPackageName);
10563
10564                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10565                            installFlags);
10566
10567                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10568                            pkgLite.packageName);
10569
10570                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10571                            pkgLite.versionCode);
10572
10573                    if (verificationParams != null) {
10574                        if (verificationParams.getVerificationURI() != null) {
10575                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10576                                 verificationParams.getVerificationURI());
10577                        }
10578                        if (verificationParams.getOriginatingURI() != null) {
10579                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10580                                  verificationParams.getOriginatingURI());
10581                        }
10582                        if (verificationParams.getReferrer() != null) {
10583                            verification.putExtra(Intent.EXTRA_REFERRER,
10584                                  verificationParams.getReferrer());
10585                        }
10586                        if (verificationParams.getOriginatingUid() >= 0) {
10587                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10588                                  verificationParams.getOriginatingUid());
10589                        }
10590                        if (verificationParams.getInstallerUid() >= 0) {
10591                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10592                                  verificationParams.getInstallerUid());
10593                        }
10594                    }
10595
10596                    final PackageVerificationState verificationState = new PackageVerificationState(
10597                            requiredUid, args);
10598
10599                    mPendingVerification.append(verificationId, verificationState);
10600
10601                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10602                            receivers, verificationState);
10603
10604                    /*
10605                     * If any sufficient verifiers were listed in the package
10606                     * manifest, attempt to ask them.
10607                     */
10608                    if (sufficientVerifiers != null) {
10609                        final int N = sufficientVerifiers.size();
10610                        if (N == 0) {
10611                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10612                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10613                        } else {
10614                            for (int i = 0; i < N; i++) {
10615                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10616
10617                                final Intent sufficientIntent = new Intent(verification);
10618                                sufficientIntent.setComponent(verifierComponent);
10619
10620                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
10621                            }
10622                        }
10623                    }
10624
10625                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10626                            mRequiredVerifierPackage, receivers);
10627                    if (ret == PackageManager.INSTALL_SUCCEEDED
10628                            && mRequiredVerifierPackage != null) {
10629                        /*
10630                         * Send the intent to the required verification agent,
10631                         * but only start the verification timeout after the
10632                         * target BroadcastReceivers have run.
10633                         */
10634                        verification.setComponent(requiredVerifierComponent);
10635                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
10636                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10637                                new BroadcastReceiver() {
10638                                    @Override
10639                                    public void onReceive(Context context, Intent intent) {
10640                                        final Message msg = mHandler
10641                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10642                                        msg.arg1 = verificationId;
10643                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10644                                    }
10645                                }, null, 0, null, null);
10646
10647                        /*
10648                         * We don't want the copy to proceed until verification
10649                         * succeeds, so null out this field.
10650                         */
10651                        mArgs = null;
10652                    }
10653                } else {
10654                    /*
10655                     * No package verification is enabled, so immediately start
10656                     * the remote call to initiate copy using temporary file.
10657                     */
10658                    ret = args.copyApk(mContainerService, true);
10659                }
10660            }
10661
10662            mRet = ret;
10663        }
10664
10665        @Override
10666        void handleReturnCode() {
10667            // If mArgs is null, then MCS couldn't be reached. When it
10668            // reconnects, it will try again to install. At that point, this
10669            // will succeed.
10670            if (mArgs != null) {
10671                processPendingInstall(mArgs, mRet);
10672            }
10673        }
10674
10675        @Override
10676        void handleServiceError() {
10677            mArgs = createInstallArgs(this);
10678            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10679        }
10680
10681        public boolean isForwardLocked() {
10682            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10683        }
10684    }
10685
10686    /**
10687     * Used during creation of InstallArgs
10688     *
10689     * @param installFlags package installation flags
10690     * @return true if should be installed on external storage
10691     */
10692    private static boolean installOnExternalAsec(int installFlags) {
10693        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10694            return false;
10695        }
10696        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10697            return true;
10698        }
10699        return false;
10700    }
10701
10702    /**
10703     * Used during creation of InstallArgs
10704     *
10705     * @param installFlags package installation flags
10706     * @return true if should be installed as forward locked
10707     */
10708    private static boolean installForwardLocked(int installFlags) {
10709        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10710    }
10711
10712    private InstallArgs createInstallArgs(InstallParams params) {
10713        if (params.move != null) {
10714            return new MoveInstallArgs(params);
10715        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10716            return new AsecInstallArgs(params);
10717        } else {
10718            return new FileInstallArgs(params);
10719        }
10720    }
10721
10722    /**
10723     * Create args that describe an existing installed package. Typically used
10724     * when cleaning up old installs, or used as a move source.
10725     */
10726    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10727            String resourcePath, String[] instructionSets) {
10728        final boolean isInAsec;
10729        if (installOnExternalAsec(installFlags)) {
10730            /* Apps on SD card are always in ASEC containers. */
10731            isInAsec = true;
10732        } else if (installForwardLocked(installFlags)
10733                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10734            /*
10735             * Forward-locked apps are only in ASEC containers if they're the
10736             * new style
10737             */
10738            isInAsec = true;
10739        } else {
10740            isInAsec = false;
10741        }
10742
10743        if (isInAsec) {
10744            return new AsecInstallArgs(codePath, instructionSets,
10745                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10746        } else {
10747            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10748        }
10749    }
10750
10751    static abstract class InstallArgs {
10752        /** @see InstallParams#origin */
10753        final OriginInfo origin;
10754        /** @see InstallParams#move */
10755        final MoveInfo move;
10756
10757        final IPackageInstallObserver2 observer;
10758        // Always refers to PackageManager flags only
10759        final int installFlags;
10760        final String installerPackageName;
10761        final String volumeUuid;
10762        final ManifestDigest manifestDigest;
10763        final UserHandle user;
10764        final String abiOverride;
10765
10766        // The list of instruction sets supported by this app. This is currently
10767        // only used during the rmdex() phase to clean up resources. We can get rid of this
10768        // if we move dex files under the common app path.
10769        /* nullable */ String[] instructionSets;
10770
10771        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10772                int installFlags, String installerPackageName, String volumeUuid,
10773                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10774                String abiOverride) {
10775            this.origin = origin;
10776            this.move = move;
10777            this.installFlags = installFlags;
10778            this.observer = observer;
10779            this.installerPackageName = installerPackageName;
10780            this.volumeUuid = volumeUuid;
10781            this.manifestDigest = manifestDigest;
10782            this.user = user;
10783            this.instructionSets = instructionSets;
10784            this.abiOverride = abiOverride;
10785        }
10786
10787        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10788        abstract int doPreInstall(int status);
10789
10790        /**
10791         * Rename package into final resting place. All paths on the given
10792         * scanned package should be updated to reflect the rename.
10793         */
10794        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10795        abstract int doPostInstall(int status, int uid);
10796
10797        /** @see PackageSettingBase#codePathString */
10798        abstract String getCodePath();
10799        /** @see PackageSettingBase#resourcePathString */
10800        abstract String getResourcePath();
10801
10802        // Need installer lock especially for dex file removal.
10803        abstract void cleanUpResourcesLI();
10804        abstract boolean doPostDeleteLI(boolean delete);
10805
10806        /**
10807         * Called before the source arguments are copied. This is used mostly
10808         * for MoveParams when it needs to read the source file to put it in the
10809         * destination.
10810         */
10811        int doPreCopy() {
10812            return PackageManager.INSTALL_SUCCEEDED;
10813        }
10814
10815        /**
10816         * Called after the source arguments are copied. This is used mostly for
10817         * MoveParams when it needs to read the source file to put it in the
10818         * destination.
10819         *
10820         * @return
10821         */
10822        int doPostCopy(int uid) {
10823            return PackageManager.INSTALL_SUCCEEDED;
10824        }
10825
10826        protected boolean isFwdLocked() {
10827            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10828        }
10829
10830        protected boolean isExternalAsec() {
10831            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10832        }
10833
10834        UserHandle getUser() {
10835            return user;
10836        }
10837    }
10838
10839    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10840        if (!allCodePaths.isEmpty()) {
10841            if (instructionSets == null) {
10842                throw new IllegalStateException("instructionSet == null");
10843            }
10844            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10845            for (String codePath : allCodePaths) {
10846                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10847                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10848                    if (retCode < 0) {
10849                        Slog.w(TAG, "Couldn't remove dex file for package: "
10850                                + " at location " + codePath + ", retcode=" + retCode);
10851                        // we don't consider this to be a failure of the core package deletion
10852                    }
10853                }
10854            }
10855        }
10856    }
10857
10858    /**
10859     * Logic to handle installation of non-ASEC applications, including copying
10860     * and renaming logic.
10861     */
10862    class FileInstallArgs extends InstallArgs {
10863        private File codeFile;
10864        private File resourceFile;
10865
10866        // Example topology:
10867        // /data/app/com.example/base.apk
10868        // /data/app/com.example/split_foo.apk
10869        // /data/app/com.example/lib/arm/libfoo.so
10870        // /data/app/com.example/lib/arm64/libfoo.so
10871        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10872
10873        /** New install */
10874        FileInstallArgs(InstallParams params) {
10875            super(params.origin, params.move, params.observer, params.installFlags,
10876                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10877                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10878            if (isFwdLocked()) {
10879                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10880            }
10881        }
10882
10883        /** Existing install */
10884        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10885            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10886                    null);
10887            this.codeFile = (codePath != null) ? new File(codePath) : null;
10888            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10889        }
10890
10891        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10892            if (origin.staged) {
10893                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
10894                codeFile = origin.file;
10895                resourceFile = origin.file;
10896                return PackageManager.INSTALL_SUCCEEDED;
10897            }
10898
10899            try {
10900                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10901                codeFile = tempDir;
10902                resourceFile = tempDir;
10903            } catch (IOException e) {
10904                Slog.w(TAG, "Failed to create copy file: " + e);
10905                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10906            }
10907
10908            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10909                @Override
10910                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10911                    if (!FileUtils.isValidExtFilename(name)) {
10912                        throw new IllegalArgumentException("Invalid filename: " + name);
10913                    }
10914                    try {
10915                        final File file = new File(codeFile, name);
10916                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10917                                O_RDWR | O_CREAT, 0644);
10918                        Os.chmod(file.getAbsolutePath(), 0644);
10919                        return new ParcelFileDescriptor(fd);
10920                    } catch (ErrnoException e) {
10921                        throw new RemoteException("Failed to open: " + e.getMessage());
10922                    }
10923                }
10924            };
10925
10926            int ret = PackageManager.INSTALL_SUCCEEDED;
10927            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10928            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10929                Slog.e(TAG, "Failed to copy package");
10930                return ret;
10931            }
10932
10933            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10934            NativeLibraryHelper.Handle handle = null;
10935            try {
10936                handle = NativeLibraryHelper.Handle.create(codeFile);
10937                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10938                        abiOverride);
10939            } catch (IOException e) {
10940                Slog.e(TAG, "Copying native libraries failed", e);
10941                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10942            } finally {
10943                IoUtils.closeQuietly(handle);
10944            }
10945
10946            return ret;
10947        }
10948
10949        int doPreInstall(int status) {
10950            if (status != PackageManager.INSTALL_SUCCEEDED) {
10951                cleanUp();
10952            }
10953            return status;
10954        }
10955
10956        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10957            if (status != PackageManager.INSTALL_SUCCEEDED) {
10958                cleanUp();
10959                return false;
10960            }
10961
10962            final File targetDir = codeFile.getParentFile();
10963            final File beforeCodeFile = codeFile;
10964            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10965
10966            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10967            try {
10968                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10969            } catch (ErrnoException e) {
10970                Slog.w(TAG, "Failed to rename", e);
10971                return false;
10972            }
10973
10974            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10975                Slog.w(TAG, "Failed to restorecon");
10976                return false;
10977            }
10978
10979            // Reflect the rename internally
10980            codeFile = afterCodeFile;
10981            resourceFile = afterCodeFile;
10982
10983            // Reflect the rename in scanned details
10984            pkg.codePath = afterCodeFile.getAbsolutePath();
10985            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10986                    pkg.baseCodePath);
10987            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10988                    pkg.splitCodePaths);
10989
10990            // Reflect the rename in app info
10991            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10992            pkg.applicationInfo.setCodePath(pkg.codePath);
10993            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10994            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10995            pkg.applicationInfo.setResourcePath(pkg.codePath);
10996            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10997            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10998
10999            return true;
11000        }
11001
11002        int doPostInstall(int status, int uid) {
11003            if (status != PackageManager.INSTALL_SUCCEEDED) {
11004                cleanUp();
11005            }
11006            return status;
11007        }
11008
11009        @Override
11010        String getCodePath() {
11011            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11012        }
11013
11014        @Override
11015        String getResourcePath() {
11016            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11017        }
11018
11019        private boolean cleanUp() {
11020            if (codeFile == null || !codeFile.exists()) {
11021                return false;
11022            }
11023
11024            if (codeFile.isDirectory()) {
11025                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11026            } else {
11027                codeFile.delete();
11028            }
11029
11030            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11031                resourceFile.delete();
11032            }
11033
11034            return true;
11035        }
11036
11037        void cleanUpResourcesLI() {
11038            // Try enumerating all code paths before deleting
11039            List<String> allCodePaths = Collections.EMPTY_LIST;
11040            if (codeFile != null && codeFile.exists()) {
11041                try {
11042                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11043                    allCodePaths = pkg.getAllCodePaths();
11044                } catch (PackageParserException e) {
11045                    // Ignored; we tried our best
11046                }
11047            }
11048
11049            cleanUp();
11050            removeDexFiles(allCodePaths, instructionSets);
11051        }
11052
11053        boolean doPostDeleteLI(boolean delete) {
11054            // XXX err, shouldn't we respect the delete flag?
11055            cleanUpResourcesLI();
11056            return true;
11057        }
11058    }
11059
11060    private boolean isAsecExternal(String cid) {
11061        final String asecPath = PackageHelper.getSdFilesystem(cid);
11062        return !asecPath.startsWith(mAsecInternalPath);
11063    }
11064
11065    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11066            PackageManagerException {
11067        if (copyRet < 0) {
11068            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11069                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11070                throw new PackageManagerException(copyRet, message);
11071            }
11072        }
11073    }
11074
11075    /**
11076     * Extract the MountService "container ID" from the full code path of an
11077     * .apk.
11078     */
11079    static String cidFromCodePath(String fullCodePath) {
11080        int eidx = fullCodePath.lastIndexOf("/");
11081        String subStr1 = fullCodePath.substring(0, eidx);
11082        int sidx = subStr1.lastIndexOf("/");
11083        return subStr1.substring(sidx+1, eidx);
11084    }
11085
11086    /**
11087     * Logic to handle installation of ASEC applications, including copying and
11088     * renaming logic.
11089     */
11090    class AsecInstallArgs extends InstallArgs {
11091        static final String RES_FILE_NAME = "pkg.apk";
11092        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11093
11094        String cid;
11095        String packagePath;
11096        String resourcePath;
11097
11098        /** New install */
11099        AsecInstallArgs(InstallParams params) {
11100            super(params.origin, params.move, params.observer, params.installFlags,
11101                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11102                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11103        }
11104
11105        /** Existing install */
11106        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11107                        boolean isExternal, boolean isForwardLocked) {
11108            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11109                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11110                    instructionSets, null);
11111            // Hackily pretend we're still looking at a full code path
11112            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11113                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11114            }
11115
11116            // Extract cid from fullCodePath
11117            int eidx = fullCodePath.lastIndexOf("/");
11118            String subStr1 = fullCodePath.substring(0, eidx);
11119            int sidx = subStr1.lastIndexOf("/");
11120            cid = subStr1.substring(sidx+1, eidx);
11121            setMountPath(subStr1);
11122        }
11123
11124        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11125            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11126                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11127                    instructionSets, null);
11128            this.cid = cid;
11129            setMountPath(PackageHelper.getSdDir(cid));
11130        }
11131
11132        void createCopyFile() {
11133            cid = mInstallerService.allocateExternalStageCidLegacy();
11134        }
11135
11136        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11137            if (origin.staged) {
11138                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11139                cid = origin.cid;
11140                setMountPath(PackageHelper.getSdDir(cid));
11141                return PackageManager.INSTALL_SUCCEEDED;
11142            }
11143
11144            if (temp) {
11145                createCopyFile();
11146            } else {
11147                /*
11148                 * Pre-emptively destroy the container since it's destroyed if
11149                 * copying fails due to it existing anyway.
11150                 */
11151                PackageHelper.destroySdDir(cid);
11152            }
11153
11154            final String newMountPath = imcs.copyPackageToContainer(
11155                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11156                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11157
11158            if (newMountPath != null) {
11159                setMountPath(newMountPath);
11160                return PackageManager.INSTALL_SUCCEEDED;
11161            } else {
11162                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11163            }
11164        }
11165
11166        @Override
11167        String getCodePath() {
11168            return packagePath;
11169        }
11170
11171        @Override
11172        String getResourcePath() {
11173            return resourcePath;
11174        }
11175
11176        int doPreInstall(int status) {
11177            if (status != PackageManager.INSTALL_SUCCEEDED) {
11178                // Destroy container
11179                PackageHelper.destroySdDir(cid);
11180            } else {
11181                boolean mounted = PackageHelper.isContainerMounted(cid);
11182                if (!mounted) {
11183                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11184                            Process.SYSTEM_UID);
11185                    if (newMountPath != null) {
11186                        setMountPath(newMountPath);
11187                    } else {
11188                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11189                    }
11190                }
11191            }
11192            return status;
11193        }
11194
11195        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11196            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11197            String newMountPath = null;
11198            if (PackageHelper.isContainerMounted(cid)) {
11199                // Unmount the container
11200                if (!PackageHelper.unMountSdDir(cid)) {
11201                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11202                    return false;
11203                }
11204            }
11205            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11206                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11207                        " which might be stale. Will try to clean up.");
11208                // Clean up the stale container and proceed to recreate.
11209                if (!PackageHelper.destroySdDir(newCacheId)) {
11210                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11211                    return false;
11212                }
11213                // Successfully cleaned up stale container. Try to rename again.
11214                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11215                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11216                            + " inspite of cleaning it up.");
11217                    return false;
11218                }
11219            }
11220            if (!PackageHelper.isContainerMounted(newCacheId)) {
11221                Slog.w(TAG, "Mounting container " + newCacheId);
11222                newMountPath = PackageHelper.mountSdDir(newCacheId,
11223                        getEncryptKey(), Process.SYSTEM_UID);
11224            } else {
11225                newMountPath = PackageHelper.getSdDir(newCacheId);
11226            }
11227            if (newMountPath == null) {
11228                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11229                return false;
11230            }
11231            Log.i(TAG, "Succesfully renamed " + cid +
11232                    " to " + newCacheId +
11233                    " at new path: " + newMountPath);
11234            cid = newCacheId;
11235
11236            final File beforeCodeFile = new File(packagePath);
11237            setMountPath(newMountPath);
11238            final File afterCodeFile = new File(packagePath);
11239
11240            // Reflect the rename in scanned details
11241            pkg.codePath = afterCodeFile.getAbsolutePath();
11242            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11243                    pkg.baseCodePath);
11244            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11245                    pkg.splitCodePaths);
11246
11247            // Reflect the rename in app info
11248            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11249            pkg.applicationInfo.setCodePath(pkg.codePath);
11250            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11251            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11252            pkg.applicationInfo.setResourcePath(pkg.codePath);
11253            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11254            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11255
11256            return true;
11257        }
11258
11259        private void setMountPath(String mountPath) {
11260            final File mountFile = new File(mountPath);
11261
11262            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11263            if (monolithicFile.exists()) {
11264                packagePath = monolithicFile.getAbsolutePath();
11265                if (isFwdLocked()) {
11266                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11267                } else {
11268                    resourcePath = packagePath;
11269                }
11270            } else {
11271                packagePath = mountFile.getAbsolutePath();
11272                resourcePath = packagePath;
11273            }
11274        }
11275
11276        int doPostInstall(int status, int uid) {
11277            if (status != PackageManager.INSTALL_SUCCEEDED) {
11278                cleanUp();
11279            } else {
11280                final int groupOwner;
11281                final String protectedFile;
11282                if (isFwdLocked()) {
11283                    groupOwner = UserHandle.getSharedAppGid(uid);
11284                    protectedFile = RES_FILE_NAME;
11285                } else {
11286                    groupOwner = -1;
11287                    protectedFile = null;
11288                }
11289
11290                if (uid < Process.FIRST_APPLICATION_UID
11291                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11292                    Slog.e(TAG, "Failed to finalize " + cid);
11293                    PackageHelper.destroySdDir(cid);
11294                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11295                }
11296
11297                boolean mounted = PackageHelper.isContainerMounted(cid);
11298                if (!mounted) {
11299                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11300                }
11301            }
11302            return status;
11303        }
11304
11305        private void cleanUp() {
11306            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11307
11308            // Destroy secure container
11309            PackageHelper.destroySdDir(cid);
11310        }
11311
11312        private List<String> getAllCodePaths() {
11313            final File codeFile = new File(getCodePath());
11314            if (codeFile != null && codeFile.exists()) {
11315                try {
11316                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11317                    return pkg.getAllCodePaths();
11318                } catch (PackageParserException e) {
11319                    // Ignored; we tried our best
11320                }
11321            }
11322            return Collections.EMPTY_LIST;
11323        }
11324
11325        void cleanUpResourcesLI() {
11326            // Enumerate all code paths before deleting
11327            cleanUpResourcesLI(getAllCodePaths());
11328        }
11329
11330        private void cleanUpResourcesLI(List<String> allCodePaths) {
11331            cleanUp();
11332            removeDexFiles(allCodePaths, instructionSets);
11333        }
11334
11335        String getPackageName() {
11336            return getAsecPackageName(cid);
11337        }
11338
11339        boolean doPostDeleteLI(boolean delete) {
11340            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11341            final List<String> allCodePaths = getAllCodePaths();
11342            boolean mounted = PackageHelper.isContainerMounted(cid);
11343            if (mounted) {
11344                // Unmount first
11345                if (PackageHelper.unMountSdDir(cid)) {
11346                    mounted = false;
11347                }
11348            }
11349            if (!mounted && delete) {
11350                cleanUpResourcesLI(allCodePaths);
11351            }
11352            return !mounted;
11353        }
11354
11355        @Override
11356        int doPreCopy() {
11357            if (isFwdLocked()) {
11358                if (!PackageHelper.fixSdPermissions(cid,
11359                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11360                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11361                }
11362            }
11363
11364            return PackageManager.INSTALL_SUCCEEDED;
11365        }
11366
11367        @Override
11368        int doPostCopy(int uid) {
11369            if (isFwdLocked()) {
11370                if (uid < Process.FIRST_APPLICATION_UID
11371                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11372                                RES_FILE_NAME)) {
11373                    Slog.e(TAG, "Failed to finalize " + cid);
11374                    PackageHelper.destroySdDir(cid);
11375                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11376                }
11377            }
11378
11379            return PackageManager.INSTALL_SUCCEEDED;
11380        }
11381    }
11382
11383    /**
11384     * Logic to handle movement of existing installed applications.
11385     */
11386    class MoveInstallArgs extends InstallArgs {
11387        private File codeFile;
11388        private File resourceFile;
11389
11390        /** New install */
11391        MoveInstallArgs(InstallParams params) {
11392            super(params.origin, params.move, params.observer, params.installFlags,
11393                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11394                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
11395        }
11396
11397        int copyApk(IMediaContainerService imcs, boolean temp) {
11398            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11399                    + move.fromUuid + " to " + move.toUuid);
11400            synchronized (mInstaller) {
11401                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11402                        move.dataAppName, move.appId, move.seinfo) != 0) {
11403                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11404                }
11405            }
11406
11407            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11408            resourceFile = codeFile;
11409            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11410
11411            return PackageManager.INSTALL_SUCCEEDED;
11412        }
11413
11414        int doPreInstall(int status) {
11415            if (status != PackageManager.INSTALL_SUCCEEDED) {
11416                cleanUp(move.toUuid);
11417            }
11418            return status;
11419        }
11420
11421        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11422            if (status != PackageManager.INSTALL_SUCCEEDED) {
11423                cleanUp(move.toUuid);
11424                return false;
11425            }
11426
11427            // Reflect the move in app info
11428            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11429            pkg.applicationInfo.setCodePath(pkg.codePath);
11430            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11431            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11432            pkg.applicationInfo.setResourcePath(pkg.codePath);
11433            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11434            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11435
11436            return true;
11437        }
11438
11439        int doPostInstall(int status, int uid) {
11440            if (status == PackageManager.INSTALL_SUCCEEDED) {
11441                cleanUp(move.fromUuid);
11442            } else {
11443                cleanUp(move.toUuid);
11444            }
11445            return status;
11446        }
11447
11448        @Override
11449        String getCodePath() {
11450            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11451        }
11452
11453        @Override
11454        String getResourcePath() {
11455            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11456        }
11457
11458        private boolean cleanUp(String volumeUuid) {
11459            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11460                    move.dataAppName);
11461            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11462            synchronized (mInstallLock) {
11463                // Clean up both app data and code
11464                removeDataDirsLI(volumeUuid, move.packageName);
11465                if (codeFile.isDirectory()) {
11466                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11467                } else {
11468                    codeFile.delete();
11469                }
11470            }
11471            return true;
11472        }
11473
11474        void cleanUpResourcesLI() {
11475            throw new UnsupportedOperationException();
11476        }
11477
11478        boolean doPostDeleteLI(boolean delete) {
11479            throw new UnsupportedOperationException();
11480        }
11481    }
11482
11483    static String getAsecPackageName(String packageCid) {
11484        int idx = packageCid.lastIndexOf("-");
11485        if (idx == -1) {
11486            return packageCid;
11487        }
11488        return packageCid.substring(0, idx);
11489    }
11490
11491    // Utility method used to create code paths based on package name and available index.
11492    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11493        String idxStr = "";
11494        int idx = 1;
11495        // Fall back to default value of idx=1 if prefix is not
11496        // part of oldCodePath
11497        if (oldCodePath != null) {
11498            String subStr = oldCodePath;
11499            // Drop the suffix right away
11500            if (suffix != null && subStr.endsWith(suffix)) {
11501                subStr = subStr.substring(0, subStr.length() - suffix.length());
11502            }
11503            // If oldCodePath already contains prefix find out the
11504            // ending index to either increment or decrement.
11505            int sidx = subStr.lastIndexOf(prefix);
11506            if (sidx != -1) {
11507                subStr = subStr.substring(sidx + prefix.length());
11508                if (subStr != null) {
11509                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11510                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11511                    }
11512                    try {
11513                        idx = Integer.parseInt(subStr);
11514                        if (idx <= 1) {
11515                            idx++;
11516                        } else {
11517                            idx--;
11518                        }
11519                    } catch(NumberFormatException e) {
11520                    }
11521                }
11522            }
11523        }
11524        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11525        return prefix + idxStr;
11526    }
11527
11528    private File getNextCodePath(File targetDir, String packageName) {
11529        int suffix = 1;
11530        File result;
11531        do {
11532            result = new File(targetDir, packageName + "-" + suffix);
11533            suffix++;
11534        } while (result.exists());
11535        return result;
11536    }
11537
11538    // Utility method that returns the relative package path with respect
11539    // to the installation directory. Like say for /data/data/com.test-1.apk
11540    // string com.test-1 is returned.
11541    static String deriveCodePathName(String codePath) {
11542        if (codePath == null) {
11543            return null;
11544        }
11545        final File codeFile = new File(codePath);
11546        final String name = codeFile.getName();
11547        if (codeFile.isDirectory()) {
11548            return name;
11549        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11550            final int lastDot = name.lastIndexOf('.');
11551            return name.substring(0, lastDot);
11552        } else {
11553            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11554            return null;
11555        }
11556    }
11557
11558    class PackageInstalledInfo {
11559        String name;
11560        int uid;
11561        // The set of users that originally had this package installed.
11562        int[] origUsers;
11563        // The set of users that now have this package installed.
11564        int[] newUsers;
11565        PackageParser.Package pkg;
11566        int returnCode;
11567        String returnMsg;
11568        PackageRemovedInfo removedInfo;
11569
11570        public void setError(int code, String msg) {
11571            returnCode = code;
11572            returnMsg = msg;
11573            Slog.w(TAG, msg);
11574        }
11575
11576        public void setError(String msg, PackageParserException e) {
11577            returnCode = e.error;
11578            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11579            Slog.w(TAG, msg, e);
11580        }
11581
11582        public void setError(String msg, PackageManagerException e) {
11583            returnCode = e.error;
11584            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11585            Slog.w(TAG, msg, e);
11586        }
11587
11588        // In some error cases we want to convey more info back to the observer
11589        String origPackage;
11590        String origPermission;
11591    }
11592
11593    /*
11594     * Install a non-existing package.
11595     */
11596    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11597            UserHandle user, String installerPackageName, String volumeUuid,
11598            PackageInstalledInfo res) {
11599        // Remember this for later, in case we need to rollback this install
11600        String pkgName = pkg.packageName;
11601
11602        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11603        final boolean dataDirExists = Environment
11604                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11605        synchronized(mPackages) {
11606            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11607                // A package with the same name is already installed, though
11608                // it has been renamed to an older name.  The package we
11609                // are trying to install should be installed as an update to
11610                // the existing one, but that has not been requested, so bail.
11611                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11612                        + " without first uninstalling package running as "
11613                        + mSettings.mRenamedPackages.get(pkgName));
11614                return;
11615            }
11616            if (mPackages.containsKey(pkgName)) {
11617                // Don't allow installation over an existing package with the same name.
11618                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11619                        + " without first uninstalling.");
11620                return;
11621            }
11622        }
11623
11624        try {
11625            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11626                    System.currentTimeMillis(), user);
11627
11628            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11629            // delete the partially installed application. the data directory will have to be
11630            // restored if it was already existing
11631            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11632                // remove package from internal structures.  Note that we want deletePackageX to
11633                // delete the package data and cache directories that it created in
11634                // scanPackageLocked, unless those directories existed before we even tried to
11635                // install.
11636                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11637                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11638                                res.removedInfo, true);
11639            }
11640
11641        } catch (PackageManagerException e) {
11642            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11643        }
11644    }
11645
11646    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11647        // Can't rotate keys during boot or if sharedUser.
11648        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11649                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11650            return false;
11651        }
11652        // app is using upgradeKeySets; make sure all are valid
11653        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11654        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11655        for (int i = 0; i < upgradeKeySets.length; i++) {
11656            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11657                Slog.wtf(TAG, "Package "
11658                         + (oldPs.name != null ? oldPs.name : "<null>")
11659                         + " contains upgrade-key-set reference to unknown key-set: "
11660                         + upgradeKeySets[i]
11661                         + " reverting to signatures check.");
11662                return false;
11663            }
11664        }
11665        return true;
11666    }
11667
11668    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11669        // Upgrade keysets are being used.  Determine if new package has a superset of the
11670        // required keys.
11671        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11672        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11673        for (int i = 0; i < upgradeKeySets.length; i++) {
11674            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11675            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11676                return true;
11677            }
11678        }
11679        return false;
11680    }
11681
11682    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11683            UserHandle user, String installerPackageName, String volumeUuid,
11684            PackageInstalledInfo res) {
11685        final PackageParser.Package oldPackage;
11686        final String pkgName = pkg.packageName;
11687        final int[] allUsers;
11688        final boolean[] perUserInstalled;
11689        final boolean weFroze;
11690
11691        // First find the old package info and check signatures
11692        synchronized(mPackages) {
11693            oldPackage = mPackages.get(pkgName);
11694            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11695            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11696            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11697                if(!checkUpgradeKeySetLP(ps, pkg)) {
11698                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11699                            "New package not signed by keys specified by upgrade-keysets: "
11700                            + pkgName);
11701                    return;
11702                }
11703            } else {
11704                // default to original signature matching
11705                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11706                    != PackageManager.SIGNATURE_MATCH) {
11707                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11708                            "New package has a different signature: " + pkgName);
11709                    return;
11710                }
11711            }
11712
11713            // In case of rollback, remember per-user/profile install state
11714            allUsers = sUserManager.getUserIds();
11715            perUserInstalled = new boolean[allUsers.length];
11716            for (int i = 0; i < allUsers.length; i++) {
11717                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11718            }
11719
11720            // Mark the app as frozen to prevent launching during the upgrade
11721            // process, and then kill all running instances
11722            if (!ps.frozen) {
11723                ps.frozen = true;
11724                weFroze = true;
11725            } else {
11726                weFroze = false;
11727            }
11728        }
11729
11730        // Now that we're guarded by frozen state, kill app during upgrade
11731        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11732
11733        try {
11734            boolean sysPkg = (isSystemApp(oldPackage));
11735            if (sysPkg) {
11736                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11737                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11738            } else {
11739                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11740                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11741            }
11742        } finally {
11743            // Regardless of success or failure of upgrade steps above, always
11744            // unfreeze the package if we froze it
11745            if (weFroze) {
11746                unfreezePackage(pkgName);
11747            }
11748        }
11749    }
11750
11751    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11752            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11753            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11754            String volumeUuid, PackageInstalledInfo res) {
11755        String pkgName = deletedPackage.packageName;
11756        boolean deletedPkg = true;
11757        boolean updatedSettings = false;
11758
11759        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11760                + deletedPackage);
11761        long origUpdateTime;
11762        if (pkg.mExtras != null) {
11763            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11764        } else {
11765            origUpdateTime = 0;
11766        }
11767
11768        // First delete the existing package while retaining the data directory
11769        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11770                res.removedInfo, true)) {
11771            // If the existing package wasn't successfully deleted
11772            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11773            deletedPkg = false;
11774        } else {
11775            // Successfully deleted the old package; proceed with replace.
11776
11777            // If deleted package lived in a container, give users a chance to
11778            // relinquish resources before killing.
11779            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11780                if (DEBUG_INSTALL) {
11781                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11782                }
11783                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11784                final ArrayList<String> pkgList = new ArrayList<String>(1);
11785                pkgList.add(deletedPackage.applicationInfo.packageName);
11786                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11787            }
11788
11789            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11790            try {
11791                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11792                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11793                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11794                        perUserInstalled, res, user);
11795                updatedSettings = true;
11796            } catch (PackageManagerException e) {
11797                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11798            }
11799        }
11800
11801        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11802            // remove package from internal structures.  Note that we want deletePackageX to
11803            // delete the package data and cache directories that it created in
11804            // scanPackageLocked, unless those directories existed before we even tried to
11805            // install.
11806            if(updatedSettings) {
11807                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11808                deletePackageLI(
11809                        pkgName, null, true, allUsers, perUserInstalled,
11810                        PackageManager.DELETE_KEEP_DATA,
11811                                res.removedInfo, true);
11812            }
11813            // Since we failed to install the new package we need to restore the old
11814            // package that we deleted.
11815            if (deletedPkg) {
11816                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11817                File restoreFile = new File(deletedPackage.codePath);
11818                // Parse old package
11819                boolean oldExternal = isExternal(deletedPackage);
11820                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11821                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11822                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11823                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11824                try {
11825                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11826                } catch (PackageManagerException e) {
11827                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11828                            + e.getMessage());
11829                    return;
11830                }
11831                // Restore of old package succeeded. Update permissions.
11832                // writer
11833                synchronized (mPackages) {
11834                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11835                            UPDATE_PERMISSIONS_ALL);
11836                    // can downgrade to reader
11837                    mSettings.writeLPr();
11838                }
11839                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11840            }
11841        }
11842    }
11843
11844    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11845            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11846            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11847            String volumeUuid, PackageInstalledInfo res) {
11848        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11849                + ", old=" + deletedPackage);
11850        boolean disabledSystem = false;
11851        boolean updatedSettings = false;
11852        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11853        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11854                != 0) {
11855            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11856        }
11857        String packageName = deletedPackage.packageName;
11858        if (packageName == null) {
11859            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11860                    "Attempt to delete null packageName.");
11861            return;
11862        }
11863        PackageParser.Package oldPkg;
11864        PackageSetting oldPkgSetting;
11865        // reader
11866        synchronized (mPackages) {
11867            oldPkg = mPackages.get(packageName);
11868            oldPkgSetting = mSettings.mPackages.get(packageName);
11869            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11870                    (oldPkgSetting == null)) {
11871                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11872                        "Couldn't find package:" + packageName + " information");
11873                return;
11874            }
11875        }
11876
11877        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11878        res.removedInfo.removedPackage = packageName;
11879        // Remove existing system package
11880        removePackageLI(oldPkgSetting, true);
11881        // writer
11882        synchronized (mPackages) {
11883            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11884            if (!disabledSystem && deletedPackage != null) {
11885                // We didn't need to disable the .apk as a current system package,
11886                // which means we are replacing another update that is already
11887                // installed.  We need to make sure to delete the older one's .apk.
11888                res.removedInfo.args = createInstallArgsForExisting(0,
11889                        deletedPackage.applicationInfo.getCodePath(),
11890                        deletedPackage.applicationInfo.getResourcePath(),
11891                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11892            } else {
11893                res.removedInfo.args = null;
11894            }
11895        }
11896
11897        // Successfully disabled the old package. Now proceed with re-installation
11898        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11899
11900        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11901        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11902
11903        PackageParser.Package newPackage = null;
11904        try {
11905            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11906            if (newPackage.mExtras != null) {
11907                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11908                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11909                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11910
11911                // is the update attempting to change shared user? that isn't going to work...
11912                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11913                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11914                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11915                            + " to " + newPkgSetting.sharedUser);
11916                    updatedSettings = true;
11917                }
11918            }
11919
11920            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11921                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11922                        perUserInstalled, res, user);
11923                updatedSettings = true;
11924            }
11925
11926        } catch (PackageManagerException e) {
11927            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11928        }
11929
11930        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11931            // Re installation failed. Restore old information
11932            // Remove new pkg information
11933            if (newPackage != null) {
11934                removeInstalledPackageLI(newPackage, true);
11935            }
11936            // Add back the old system package
11937            try {
11938                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11939            } catch (PackageManagerException e) {
11940                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11941            }
11942            // Restore the old system information in Settings
11943            synchronized (mPackages) {
11944                if (disabledSystem) {
11945                    mSettings.enableSystemPackageLPw(packageName);
11946                }
11947                if (updatedSettings) {
11948                    mSettings.setInstallerPackageName(packageName,
11949                            oldPkgSetting.installerPackageName);
11950                }
11951                mSettings.writeLPr();
11952            }
11953        }
11954    }
11955
11956    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11957            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11958            UserHandle user) {
11959        String pkgName = newPackage.packageName;
11960        synchronized (mPackages) {
11961            //write settings. the installStatus will be incomplete at this stage.
11962            //note that the new package setting would have already been
11963            //added to mPackages. It hasn't been persisted yet.
11964            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11965            mSettings.writeLPr();
11966        }
11967
11968        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11969
11970        synchronized (mPackages) {
11971            updatePermissionsLPw(newPackage.packageName, newPackage,
11972                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11973                            ? UPDATE_PERMISSIONS_ALL : 0));
11974            // For system-bundled packages, we assume that installing an upgraded version
11975            // of the package implies that the user actually wants to run that new code,
11976            // so we enable the package.
11977            PackageSetting ps = mSettings.mPackages.get(pkgName);
11978            if (ps != null) {
11979                if (isSystemApp(newPackage)) {
11980                    // NB: implicit assumption that system package upgrades apply to all users
11981                    if (DEBUG_INSTALL) {
11982                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11983                    }
11984                    if (res.origUsers != null) {
11985                        for (int userHandle : res.origUsers) {
11986                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11987                                    userHandle, installerPackageName);
11988                        }
11989                    }
11990                    // Also convey the prior install/uninstall state
11991                    if (allUsers != null && perUserInstalled != null) {
11992                        for (int i = 0; i < allUsers.length; i++) {
11993                            if (DEBUG_INSTALL) {
11994                                Slog.d(TAG, "    user " + allUsers[i]
11995                                        + " => " + perUserInstalled[i]);
11996                            }
11997                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11998                        }
11999                        // these install state changes will be persisted in the
12000                        // upcoming call to mSettings.writeLPr().
12001                    }
12002                }
12003                // It's implied that when a user requests installation, they want the app to be
12004                // installed and enabled.
12005                int userId = user.getIdentifier();
12006                if (userId != UserHandle.USER_ALL) {
12007                    ps.setInstalled(true, userId);
12008                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12009                }
12010            }
12011            res.name = pkgName;
12012            res.uid = newPackage.applicationInfo.uid;
12013            res.pkg = newPackage;
12014            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12015            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12016            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12017            //to update install status
12018            mSettings.writeLPr();
12019        }
12020    }
12021
12022    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12023        final int installFlags = args.installFlags;
12024        final String installerPackageName = args.installerPackageName;
12025        final String volumeUuid = args.volumeUuid;
12026        final File tmpPackageFile = new File(args.getCodePath());
12027        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12028        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12029                || (args.volumeUuid != null));
12030        boolean replace = false;
12031        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12032        if (args.move != null) {
12033            // moving a complete application; perfom an initial scan on the new install location
12034            scanFlags |= SCAN_INITIAL;
12035        }
12036        // Result object to be returned
12037        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12038
12039        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12040        // Retrieve PackageSettings and parse package
12041        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12042                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12043                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12044        PackageParser pp = new PackageParser();
12045        pp.setSeparateProcesses(mSeparateProcesses);
12046        pp.setDisplayMetrics(mMetrics);
12047
12048        final PackageParser.Package pkg;
12049        try {
12050            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12051        } catch (PackageParserException e) {
12052            res.setError("Failed parse during installPackageLI", e);
12053            return;
12054        }
12055
12056        // Mark that we have an install time CPU ABI override.
12057        pkg.cpuAbiOverride = args.abiOverride;
12058
12059        String pkgName = res.name = pkg.packageName;
12060        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12061            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12062                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12063                return;
12064            }
12065        }
12066
12067        try {
12068            pp.collectCertificates(pkg, parseFlags);
12069            pp.collectManifestDigest(pkg);
12070        } catch (PackageParserException e) {
12071            res.setError("Failed collect during installPackageLI", e);
12072            return;
12073        }
12074
12075        /* If the installer passed in a manifest digest, compare it now. */
12076        if (args.manifestDigest != null) {
12077            if (DEBUG_INSTALL) {
12078                final String parsedManifest = pkg.manifestDigest == null ? "null"
12079                        : pkg.manifestDigest.toString();
12080                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12081                        + parsedManifest);
12082            }
12083
12084            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12085                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12086                return;
12087            }
12088        } else if (DEBUG_INSTALL) {
12089            final String parsedManifest = pkg.manifestDigest == null
12090                    ? "null" : pkg.manifestDigest.toString();
12091            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12092        }
12093
12094        // Get rid of all references to package scan path via parser.
12095        pp = null;
12096        String oldCodePath = null;
12097        boolean systemApp = false;
12098        synchronized (mPackages) {
12099            // Check if installing already existing package
12100            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12101                String oldName = mSettings.mRenamedPackages.get(pkgName);
12102                if (pkg.mOriginalPackages != null
12103                        && pkg.mOriginalPackages.contains(oldName)
12104                        && mPackages.containsKey(oldName)) {
12105                    // This package is derived from an original package,
12106                    // and this device has been updating from that original
12107                    // name.  We must continue using the original name, so
12108                    // rename the new package here.
12109                    pkg.setPackageName(oldName);
12110                    pkgName = pkg.packageName;
12111                    replace = true;
12112                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12113                            + oldName + " pkgName=" + pkgName);
12114                } else if (mPackages.containsKey(pkgName)) {
12115                    // This package, under its official name, already exists
12116                    // on the device; we should replace it.
12117                    replace = true;
12118                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12119                }
12120
12121                // Prevent apps opting out from runtime permissions
12122                if (replace) {
12123                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12124                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12125                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12126                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12127                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12128                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12129                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12130                                        + " doesn't support runtime permissions but the old"
12131                                        + " target SDK " + oldTargetSdk + " does.");
12132                        return;
12133                    }
12134                }
12135            }
12136
12137            PackageSetting ps = mSettings.mPackages.get(pkgName);
12138            if (ps != null) {
12139                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12140
12141                // Quick sanity check that we're signed correctly if updating;
12142                // we'll check this again later when scanning, but we want to
12143                // bail early here before tripping over redefined permissions.
12144                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12145                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12146                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12147                                + pkg.packageName + " upgrade keys do not match the "
12148                                + "previously installed version");
12149                        return;
12150                    }
12151                } else {
12152                    try {
12153                        verifySignaturesLP(ps, pkg);
12154                    } catch (PackageManagerException e) {
12155                        res.setError(e.error, e.getMessage());
12156                        return;
12157                    }
12158                }
12159
12160                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12161                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12162                    systemApp = (ps.pkg.applicationInfo.flags &
12163                            ApplicationInfo.FLAG_SYSTEM) != 0;
12164                }
12165                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12166            }
12167
12168            // Check whether the newly-scanned package wants to define an already-defined perm
12169            int N = pkg.permissions.size();
12170            for (int i = N-1; i >= 0; i--) {
12171                PackageParser.Permission perm = pkg.permissions.get(i);
12172                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12173                if (bp != null) {
12174                    // If the defining package is signed with our cert, it's okay.  This
12175                    // also includes the "updating the same package" case, of course.
12176                    // "updating same package" could also involve key-rotation.
12177                    final boolean sigsOk;
12178                    if (bp.sourcePackage.equals(pkg.packageName)
12179                            && (bp.packageSetting instanceof PackageSetting)
12180                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12181                                    scanFlags))) {
12182                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12183                    } else {
12184                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12185                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12186                    }
12187                    if (!sigsOk) {
12188                        // If the owning package is the system itself, we log but allow
12189                        // install to proceed; we fail the install on all other permission
12190                        // redefinitions.
12191                        if (!bp.sourcePackage.equals("android")) {
12192                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12193                                    + pkg.packageName + " attempting to redeclare permission "
12194                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12195                            res.origPermission = perm.info.name;
12196                            res.origPackage = bp.sourcePackage;
12197                            return;
12198                        } else {
12199                            Slog.w(TAG, "Package " + pkg.packageName
12200                                    + " attempting to redeclare system permission "
12201                                    + perm.info.name + "; ignoring new declaration");
12202                            pkg.permissions.remove(i);
12203                        }
12204                    }
12205                }
12206            }
12207
12208        }
12209
12210        if (systemApp && onExternal) {
12211            // Disable updates to system apps on sdcard
12212            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12213                    "Cannot install updates to system apps on sdcard");
12214            return;
12215        }
12216
12217        if (args.move != null) {
12218            // We did an in-place move, so dex is ready to roll
12219            scanFlags |= SCAN_NO_DEX;
12220            scanFlags |= SCAN_MOVE;
12221        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12222            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12223            scanFlags |= SCAN_NO_DEX;
12224
12225            try {
12226                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12227                        true /* extract libs */);
12228            } catch (PackageManagerException pme) {
12229                Slog.e(TAG, "Error deriving application ABI", pme);
12230                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12231                return;
12232            }
12233
12234            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12235            int result = mPackageDexOptimizer
12236                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12237                            false /* defer */, false /* inclDependencies */);
12238            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12239                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12240                return;
12241            }
12242        }
12243
12244        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12245            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12246            return;
12247        }
12248
12249        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12250
12251        if (replace) {
12252            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
12253                    installerPackageName, volumeUuid, res);
12254        } else {
12255            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12256                    args.user, installerPackageName, volumeUuid, res);
12257        }
12258        synchronized (mPackages) {
12259            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12260            if (ps != null) {
12261                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12262            }
12263        }
12264    }
12265
12266    private void startIntentFilterVerifications(int userId, boolean replacing,
12267            PackageParser.Package pkg) {
12268        if (mIntentFilterVerifierComponent == null) {
12269            Slog.w(TAG, "No IntentFilter verification will not be done as "
12270                    + "there is no IntentFilterVerifier available!");
12271            return;
12272        }
12273
12274        final int verifierUid = getPackageUid(
12275                mIntentFilterVerifierComponent.getPackageName(),
12276                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12277
12278        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12279        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12280        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12281        mHandler.sendMessage(msg);
12282    }
12283
12284    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12285            PackageParser.Package pkg) {
12286        int size = pkg.activities.size();
12287        if (size == 0) {
12288            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12289                    "No activity, so no need to verify any IntentFilter!");
12290            return;
12291        }
12292
12293        final boolean hasDomainURLs = hasDomainURLs(pkg);
12294        if (!hasDomainURLs) {
12295            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12296                    "No domain URLs, so no need to verify any IntentFilter!");
12297            return;
12298        }
12299
12300        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12301                + " if any IntentFilter from the " + size
12302                + " Activities needs verification ...");
12303
12304        int count = 0;
12305        final String packageName = pkg.packageName;
12306
12307        synchronized (mPackages) {
12308            // If this is a new install and we see that we've already run verification for this
12309            // package, we have nothing to do: it means the state was restored from backup.
12310            if (!replacing) {
12311                IntentFilterVerificationInfo ivi =
12312                        mSettings.getIntentFilterVerificationLPr(packageName);
12313                if (ivi != null) {
12314                    if (DEBUG_DOMAIN_VERIFICATION) {
12315                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12316                                + ivi.getStatusString());
12317                    }
12318                    return;
12319                }
12320            }
12321
12322            // If any filters need to be verified, then all need to be.
12323            boolean needToVerify = false;
12324            for (PackageParser.Activity a : pkg.activities) {
12325                for (ActivityIntentInfo filter : a.intents) {
12326                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12327                        if (DEBUG_DOMAIN_VERIFICATION) {
12328                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12329                        }
12330                        needToVerify = true;
12331                        break;
12332                    }
12333                }
12334            }
12335
12336            if (needToVerify) {
12337                final int verificationId = mIntentFilterVerificationToken++;
12338                for (PackageParser.Activity a : pkg.activities) {
12339                    for (ActivityIntentInfo filter : a.intents) {
12340                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12341                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12342                                    "Verification needed for IntentFilter:" + filter.toString());
12343                            mIntentFilterVerifier.addOneIntentFilterVerification(
12344                                    verifierUid, userId, verificationId, filter, packageName);
12345                            count++;
12346                        }
12347                    }
12348                }
12349            }
12350        }
12351
12352        if (count > 0) {
12353            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12354                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12355                    +  " for userId:" + userId);
12356            mIntentFilterVerifier.startVerifications(userId);
12357        } else {
12358            if (DEBUG_DOMAIN_VERIFICATION) {
12359                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12360            }
12361        }
12362    }
12363
12364    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12365        final ComponentName cn  = filter.activity.getComponentName();
12366        final String packageName = cn.getPackageName();
12367
12368        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12369                packageName);
12370        if (ivi == null) {
12371            return true;
12372        }
12373        int status = ivi.getStatus();
12374        switch (status) {
12375            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12376            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12377                return true;
12378
12379            default:
12380                // Nothing to do
12381                return false;
12382        }
12383    }
12384
12385    private static boolean isMultiArch(PackageSetting ps) {
12386        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12387    }
12388
12389    private static boolean isMultiArch(ApplicationInfo info) {
12390        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12391    }
12392
12393    private static boolean isExternal(PackageParser.Package pkg) {
12394        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12395    }
12396
12397    private static boolean isExternal(PackageSetting ps) {
12398        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12399    }
12400
12401    private static boolean isExternal(ApplicationInfo info) {
12402        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12403    }
12404
12405    private static boolean isSystemApp(PackageParser.Package pkg) {
12406        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12407    }
12408
12409    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12410        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12411    }
12412
12413    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12414        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12415    }
12416
12417    private static boolean isSystemApp(PackageSetting ps) {
12418        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12419    }
12420
12421    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12422        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12423    }
12424
12425    private int packageFlagsToInstallFlags(PackageSetting ps) {
12426        int installFlags = 0;
12427        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12428            // This existing package was an external ASEC install when we have
12429            // the external flag without a UUID
12430            installFlags |= PackageManager.INSTALL_EXTERNAL;
12431        }
12432        if (ps.isForwardLocked()) {
12433            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12434        }
12435        return installFlags;
12436    }
12437
12438    private void deleteTempPackageFiles() {
12439        final FilenameFilter filter = new FilenameFilter() {
12440            public boolean accept(File dir, String name) {
12441                return name.startsWith("vmdl") && name.endsWith(".tmp");
12442            }
12443        };
12444        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12445            file.delete();
12446        }
12447    }
12448
12449    @Override
12450    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12451            int flags) {
12452        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12453                flags);
12454    }
12455
12456    @Override
12457    public void deletePackage(final String packageName,
12458            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12459        mContext.enforceCallingOrSelfPermission(
12460                android.Manifest.permission.DELETE_PACKAGES, null);
12461        Preconditions.checkNotNull(packageName);
12462        Preconditions.checkNotNull(observer);
12463        final int uid = Binder.getCallingUid();
12464        if (UserHandle.getUserId(uid) != userId) {
12465            mContext.enforceCallingPermission(
12466                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12467                    "deletePackage for user " + userId);
12468        }
12469        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12470            try {
12471                observer.onPackageDeleted(packageName,
12472                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12473            } catch (RemoteException re) {
12474            }
12475            return;
12476        }
12477
12478        boolean uninstallBlocked = false;
12479        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12480            int[] users = sUserManager.getUserIds();
12481            for (int i = 0; i < users.length; ++i) {
12482                if (getBlockUninstallForUser(packageName, users[i])) {
12483                    uninstallBlocked = true;
12484                    break;
12485                }
12486            }
12487        } else {
12488            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12489        }
12490        if (uninstallBlocked) {
12491            try {
12492                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12493                        null);
12494            } catch (RemoteException re) {
12495            }
12496            return;
12497        }
12498
12499        if (DEBUG_REMOVE) {
12500            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12501        }
12502        // Queue up an async operation since the package deletion may take a little while.
12503        mHandler.post(new Runnable() {
12504            public void run() {
12505                mHandler.removeCallbacks(this);
12506                final int returnCode = deletePackageX(packageName, userId, flags);
12507                if (observer != null) {
12508                    try {
12509                        observer.onPackageDeleted(packageName, returnCode, null);
12510                    } catch (RemoteException e) {
12511                        Log.i(TAG, "Observer no longer exists.");
12512                    } //end catch
12513                } //end if
12514            } //end run
12515        });
12516    }
12517
12518    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12519        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12520                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12521        try {
12522            if (dpm != null) {
12523                if (dpm.isDeviceOwner(packageName)) {
12524                    return true;
12525                }
12526                int[] users;
12527                if (userId == UserHandle.USER_ALL) {
12528                    users = sUserManager.getUserIds();
12529                } else {
12530                    users = new int[]{userId};
12531                }
12532                for (int i = 0; i < users.length; ++i) {
12533                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12534                        return true;
12535                    }
12536                }
12537            }
12538        } catch (RemoteException e) {
12539        }
12540        return false;
12541    }
12542
12543    /**
12544     *  This method is an internal method that could be get invoked either
12545     *  to delete an installed package or to clean up a failed installation.
12546     *  After deleting an installed package, a broadcast is sent to notify any
12547     *  listeners that the package has been installed. For cleaning up a failed
12548     *  installation, the broadcast is not necessary since the package's
12549     *  installation wouldn't have sent the initial broadcast either
12550     *  The key steps in deleting a package are
12551     *  deleting the package information in internal structures like mPackages,
12552     *  deleting the packages base directories through installd
12553     *  updating mSettings to reflect current status
12554     *  persisting settings for later use
12555     *  sending a broadcast if necessary
12556     */
12557    private int deletePackageX(String packageName, int userId, int flags) {
12558        final PackageRemovedInfo info = new PackageRemovedInfo();
12559        final boolean res;
12560
12561        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12562                ? UserHandle.ALL : new UserHandle(userId);
12563
12564        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12565            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12566            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12567        }
12568
12569        boolean removedForAllUsers = false;
12570        boolean systemUpdate = false;
12571
12572        // for the uninstall-updates case and restricted profiles, remember the per-
12573        // userhandle installed state
12574        int[] allUsers;
12575        boolean[] perUserInstalled;
12576        synchronized (mPackages) {
12577            PackageSetting ps = mSettings.mPackages.get(packageName);
12578            allUsers = sUserManager.getUserIds();
12579            perUserInstalled = new boolean[allUsers.length];
12580            for (int i = 0; i < allUsers.length; i++) {
12581                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12582            }
12583        }
12584
12585        synchronized (mInstallLock) {
12586            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12587            res = deletePackageLI(packageName, removeForUser,
12588                    true, allUsers, perUserInstalled,
12589                    flags | REMOVE_CHATTY, info, true);
12590            systemUpdate = info.isRemovedPackageSystemUpdate;
12591            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12592                removedForAllUsers = true;
12593            }
12594            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12595                    + " removedForAllUsers=" + removedForAllUsers);
12596        }
12597
12598        if (res) {
12599            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12600
12601            // If the removed package was a system update, the old system package
12602            // was re-enabled; we need to broadcast this information
12603            if (systemUpdate) {
12604                Bundle extras = new Bundle(1);
12605                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12606                        ? info.removedAppId : info.uid);
12607                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12608
12609                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12610                        extras, null, null, null);
12611                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12612                        extras, null, null, null);
12613                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12614                        null, packageName, null, null);
12615            }
12616        }
12617        // Force a gc here.
12618        Runtime.getRuntime().gc();
12619        // Delete the resources here after sending the broadcast to let
12620        // other processes clean up before deleting resources.
12621        if (info.args != null) {
12622            synchronized (mInstallLock) {
12623                info.args.doPostDeleteLI(true);
12624            }
12625        }
12626
12627        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12628    }
12629
12630    class PackageRemovedInfo {
12631        String removedPackage;
12632        int uid = -1;
12633        int removedAppId = -1;
12634        int[] removedUsers = null;
12635        boolean isRemovedPackageSystemUpdate = false;
12636        // Clean up resources deleted packages.
12637        InstallArgs args = null;
12638
12639        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12640            Bundle extras = new Bundle(1);
12641            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12642            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12643            if (replacing) {
12644                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12645            }
12646            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12647            if (removedPackage != null) {
12648                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12649                        extras, null, null, removedUsers);
12650                if (fullRemove && !replacing) {
12651                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12652                            extras, null, null, removedUsers);
12653                }
12654            }
12655            if (removedAppId >= 0) {
12656                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12657                        removedUsers);
12658            }
12659        }
12660    }
12661
12662    /*
12663     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12664     * flag is not set, the data directory is removed as well.
12665     * make sure this flag is set for partially installed apps. If not its meaningless to
12666     * delete a partially installed application.
12667     */
12668    private void removePackageDataLI(PackageSetting ps,
12669            int[] allUserHandles, boolean[] perUserInstalled,
12670            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12671        String packageName = ps.name;
12672        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12673        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12674        // Retrieve object to delete permissions for shared user later on
12675        final PackageSetting deletedPs;
12676        // reader
12677        synchronized (mPackages) {
12678            deletedPs = mSettings.mPackages.get(packageName);
12679            if (outInfo != null) {
12680                outInfo.removedPackage = packageName;
12681                outInfo.removedUsers = deletedPs != null
12682                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12683                        : null;
12684            }
12685        }
12686        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12687            removeDataDirsLI(ps.volumeUuid, packageName);
12688            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12689        }
12690        // writer
12691        synchronized (mPackages) {
12692            if (deletedPs != null) {
12693                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12694                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12695                    clearDefaultBrowserIfNeeded(packageName);
12696                    if (outInfo != null) {
12697                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12698                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12699                    }
12700                    updatePermissionsLPw(deletedPs.name, null, 0);
12701                    if (deletedPs.sharedUser != null) {
12702                        // Remove permissions associated with package. Since runtime
12703                        // permissions are per user we have to kill the removed package
12704                        // or packages running under the shared user of the removed
12705                        // package if revoking the permissions requested only by the removed
12706                        // package is successful and this causes a change in gids.
12707                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12708                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12709                                    userId);
12710                            if (userIdToKill == UserHandle.USER_ALL
12711                                    || userIdToKill >= UserHandle.USER_OWNER) {
12712                                // If gids changed for this user, kill all affected packages.
12713                                mHandler.post(new Runnable() {
12714                                    @Override
12715                                    public void run() {
12716                                        // This has to happen with no lock held.
12717                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12718                                                KILL_APP_REASON_GIDS_CHANGED);
12719                                    }
12720                                });
12721                                break;
12722                            }
12723                        }
12724                    }
12725                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12726                }
12727                // make sure to preserve per-user disabled state if this removal was just
12728                // a downgrade of a system app to the factory package
12729                if (allUserHandles != null && perUserInstalled != null) {
12730                    if (DEBUG_REMOVE) {
12731                        Slog.d(TAG, "Propagating install state across downgrade");
12732                    }
12733                    for (int i = 0; i < allUserHandles.length; i++) {
12734                        if (DEBUG_REMOVE) {
12735                            Slog.d(TAG, "    user " + allUserHandles[i]
12736                                    + " => " + perUserInstalled[i]);
12737                        }
12738                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12739                    }
12740                }
12741            }
12742            // can downgrade to reader
12743            if (writeSettings) {
12744                // Save settings now
12745                mSettings.writeLPr();
12746            }
12747        }
12748        if (outInfo != null) {
12749            // A user ID was deleted here. Go through all users and remove it
12750            // from KeyStore.
12751            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12752        }
12753    }
12754
12755    static boolean locationIsPrivileged(File path) {
12756        try {
12757            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12758                    .getCanonicalPath();
12759            return path.getCanonicalPath().startsWith(privilegedAppDir);
12760        } catch (IOException e) {
12761            Slog.e(TAG, "Unable to access code path " + path);
12762        }
12763        return false;
12764    }
12765
12766    /*
12767     * Tries to delete system package.
12768     */
12769    private boolean deleteSystemPackageLI(PackageSetting newPs,
12770            int[] allUserHandles, boolean[] perUserInstalled,
12771            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12772        final boolean applyUserRestrictions
12773                = (allUserHandles != null) && (perUserInstalled != null);
12774        PackageSetting disabledPs = null;
12775        // Confirm if the system package has been updated
12776        // An updated system app can be deleted. This will also have to restore
12777        // the system pkg from system partition
12778        // reader
12779        synchronized (mPackages) {
12780            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12781        }
12782        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12783                + " disabledPs=" + disabledPs);
12784        if (disabledPs == null) {
12785            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12786            return false;
12787        } else if (DEBUG_REMOVE) {
12788            Slog.d(TAG, "Deleting system pkg from data partition");
12789        }
12790        if (DEBUG_REMOVE) {
12791            if (applyUserRestrictions) {
12792                Slog.d(TAG, "Remembering install states:");
12793                for (int i = 0; i < allUserHandles.length; i++) {
12794                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12795                }
12796            }
12797        }
12798        // Delete the updated package
12799        outInfo.isRemovedPackageSystemUpdate = true;
12800        if (disabledPs.versionCode < newPs.versionCode) {
12801            // Delete data for downgrades
12802            flags &= ~PackageManager.DELETE_KEEP_DATA;
12803        } else {
12804            // Preserve data by setting flag
12805            flags |= PackageManager.DELETE_KEEP_DATA;
12806        }
12807        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12808                allUserHandles, perUserInstalled, outInfo, writeSettings);
12809        if (!ret) {
12810            return false;
12811        }
12812        // writer
12813        synchronized (mPackages) {
12814            // Reinstate the old system package
12815            mSettings.enableSystemPackageLPw(newPs.name);
12816            // Remove any native libraries from the upgraded package.
12817            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12818        }
12819        // Install the system package
12820        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12821        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12822        if (locationIsPrivileged(disabledPs.codePath)) {
12823            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12824        }
12825
12826        final PackageParser.Package newPkg;
12827        try {
12828            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12829        } catch (PackageManagerException e) {
12830            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12831            return false;
12832        }
12833
12834        // writer
12835        synchronized (mPackages) {
12836            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12837
12838            // Propagate the permissions state as we do want to drop on the floor
12839            // runtime permissions. The update permissions method below will take
12840            // care of removing obsolete permissions and grant install permissions.
12841            ps.getPermissionsState().copyFrom(disabledPs.getPermissionsState());
12842            updatePermissionsLPw(newPkg.packageName, newPkg,
12843                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12844
12845            if (applyUserRestrictions) {
12846                if (DEBUG_REMOVE) {
12847                    Slog.d(TAG, "Propagating install state across reinstall");
12848                }
12849                for (int i = 0; i < allUserHandles.length; i++) {
12850                    if (DEBUG_REMOVE) {
12851                        Slog.d(TAG, "    user " + allUserHandles[i]
12852                                + " => " + perUserInstalled[i]);
12853                    }
12854                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12855                }
12856                // Regardless of writeSettings we need to ensure that this restriction
12857                // state propagation is persisted
12858                mSettings.writeAllUsersPackageRestrictionsLPr();
12859            }
12860            // can downgrade to reader here
12861            if (writeSettings) {
12862                mSettings.writeLPr();
12863            }
12864        }
12865        return true;
12866    }
12867
12868    private boolean deleteInstalledPackageLI(PackageSetting ps,
12869            boolean deleteCodeAndResources, int flags,
12870            int[] allUserHandles, boolean[] perUserInstalled,
12871            PackageRemovedInfo outInfo, boolean writeSettings) {
12872        if (outInfo != null) {
12873            outInfo.uid = ps.appId;
12874        }
12875
12876        // Delete package data from internal structures and also remove data if flag is set
12877        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12878
12879        // Delete application code and resources
12880        if (deleteCodeAndResources && (outInfo != null)) {
12881            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12882                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12883            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12884        }
12885        return true;
12886    }
12887
12888    @Override
12889    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12890            int userId) {
12891        mContext.enforceCallingOrSelfPermission(
12892                android.Manifest.permission.DELETE_PACKAGES, null);
12893        synchronized (mPackages) {
12894            PackageSetting ps = mSettings.mPackages.get(packageName);
12895            if (ps == null) {
12896                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12897                return false;
12898            }
12899            if (!ps.getInstalled(userId)) {
12900                // Can't block uninstall for an app that is not installed or enabled.
12901                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12902                return false;
12903            }
12904            ps.setBlockUninstall(blockUninstall, userId);
12905            mSettings.writePackageRestrictionsLPr(userId);
12906        }
12907        return true;
12908    }
12909
12910    @Override
12911    public boolean getBlockUninstallForUser(String packageName, int userId) {
12912        synchronized (mPackages) {
12913            PackageSetting ps = mSettings.mPackages.get(packageName);
12914            if (ps == null) {
12915                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12916                return false;
12917            }
12918            return ps.getBlockUninstall(userId);
12919        }
12920    }
12921
12922    /*
12923     * This method handles package deletion in general
12924     */
12925    private boolean deletePackageLI(String packageName, UserHandle user,
12926            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12927            int flags, PackageRemovedInfo outInfo,
12928            boolean writeSettings) {
12929        if (packageName == null) {
12930            Slog.w(TAG, "Attempt to delete null packageName.");
12931            return false;
12932        }
12933        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12934        PackageSetting ps;
12935        boolean dataOnly = false;
12936        int removeUser = -1;
12937        int appId = -1;
12938        synchronized (mPackages) {
12939            ps = mSettings.mPackages.get(packageName);
12940            if (ps == null) {
12941                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12942                return false;
12943            }
12944            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12945                    && user.getIdentifier() != UserHandle.USER_ALL) {
12946                // The caller is asking that the package only be deleted for a single
12947                // user.  To do this, we just mark its uninstalled state and delete
12948                // its data.  If this is a system app, we only allow this to happen if
12949                // they have set the special DELETE_SYSTEM_APP which requests different
12950                // semantics than normal for uninstalling system apps.
12951                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12952                ps.setUserState(user.getIdentifier(),
12953                        COMPONENT_ENABLED_STATE_DEFAULT,
12954                        false, //installed
12955                        true,  //stopped
12956                        true,  //notLaunched
12957                        false, //hidden
12958                        null, null, null,
12959                        false, // blockUninstall
12960                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12961                if (!isSystemApp(ps)) {
12962                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12963                        // Other user still have this package installed, so all
12964                        // we need to do is clear this user's data and save that
12965                        // it is uninstalled.
12966                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12967                        removeUser = user.getIdentifier();
12968                        appId = ps.appId;
12969                        scheduleWritePackageRestrictionsLocked(removeUser);
12970                    } else {
12971                        // We need to set it back to 'installed' so the uninstall
12972                        // broadcasts will be sent correctly.
12973                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12974                        ps.setInstalled(true, user.getIdentifier());
12975                    }
12976                } else {
12977                    // This is a system app, so we assume that the
12978                    // other users still have this package installed, so all
12979                    // we need to do is clear this user's data and save that
12980                    // it is uninstalled.
12981                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12982                    removeUser = user.getIdentifier();
12983                    appId = ps.appId;
12984                    scheduleWritePackageRestrictionsLocked(removeUser);
12985                }
12986            }
12987        }
12988
12989        if (removeUser >= 0) {
12990            // From above, we determined that we are deleting this only
12991            // for a single user.  Continue the work here.
12992            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12993            if (outInfo != null) {
12994                outInfo.removedPackage = packageName;
12995                outInfo.removedAppId = appId;
12996                outInfo.removedUsers = new int[] {removeUser};
12997            }
12998            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12999            removeKeystoreDataIfNeeded(removeUser, appId);
13000            schedulePackageCleaning(packageName, removeUser, false);
13001            synchronized (mPackages) {
13002                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13003                    scheduleWritePackageRestrictionsLocked(removeUser);
13004                }
13005                resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, removeUser);
13006            }
13007            return true;
13008        }
13009
13010        if (dataOnly) {
13011            // Delete application data first
13012            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13013            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13014            return true;
13015        }
13016
13017        boolean ret = false;
13018        if (isSystemApp(ps)) {
13019            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13020            // When an updated system application is deleted we delete the existing resources as well and
13021            // fall back to existing code in system partition
13022            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13023                    flags, outInfo, writeSettings);
13024        } else {
13025            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13026            // Kill application pre-emptively especially for apps on sd.
13027            killApplication(packageName, ps.appId, "uninstall pkg");
13028            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13029                    allUserHandles, perUserInstalled,
13030                    outInfo, writeSettings);
13031        }
13032
13033        return ret;
13034    }
13035
13036    private final class ClearStorageConnection implements ServiceConnection {
13037        IMediaContainerService mContainerService;
13038
13039        @Override
13040        public void onServiceConnected(ComponentName name, IBinder service) {
13041            synchronized (this) {
13042                mContainerService = IMediaContainerService.Stub.asInterface(service);
13043                notifyAll();
13044            }
13045        }
13046
13047        @Override
13048        public void onServiceDisconnected(ComponentName name) {
13049        }
13050    }
13051
13052    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13053        final boolean mounted;
13054        if (Environment.isExternalStorageEmulated()) {
13055            mounted = true;
13056        } else {
13057            final String status = Environment.getExternalStorageState();
13058
13059            mounted = status.equals(Environment.MEDIA_MOUNTED)
13060                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13061        }
13062
13063        if (!mounted) {
13064            return;
13065        }
13066
13067        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13068        int[] users;
13069        if (userId == UserHandle.USER_ALL) {
13070            users = sUserManager.getUserIds();
13071        } else {
13072            users = new int[] { userId };
13073        }
13074        final ClearStorageConnection conn = new ClearStorageConnection();
13075        if (mContext.bindServiceAsUser(
13076                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13077            try {
13078                for (int curUser : users) {
13079                    long timeout = SystemClock.uptimeMillis() + 5000;
13080                    synchronized (conn) {
13081                        long now = SystemClock.uptimeMillis();
13082                        while (conn.mContainerService == null && now < timeout) {
13083                            try {
13084                                conn.wait(timeout - now);
13085                            } catch (InterruptedException e) {
13086                            }
13087                        }
13088                    }
13089                    if (conn.mContainerService == null) {
13090                        return;
13091                    }
13092
13093                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13094                    clearDirectory(conn.mContainerService,
13095                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13096                    if (allData) {
13097                        clearDirectory(conn.mContainerService,
13098                                userEnv.buildExternalStorageAppDataDirs(packageName));
13099                        clearDirectory(conn.mContainerService,
13100                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13101                    }
13102                }
13103            } finally {
13104                mContext.unbindService(conn);
13105            }
13106        }
13107    }
13108
13109    @Override
13110    public void clearApplicationUserData(final String packageName,
13111            final IPackageDataObserver observer, final int userId) {
13112        mContext.enforceCallingOrSelfPermission(
13113                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13114        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13115        // Queue up an async operation since the package deletion may take a little while.
13116        mHandler.post(new Runnable() {
13117            public void run() {
13118                mHandler.removeCallbacks(this);
13119                final boolean succeeded;
13120                synchronized (mInstallLock) {
13121                    succeeded = clearApplicationUserDataLI(packageName, userId);
13122                }
13123                clearExternalStorageDataSync(packageName, userId, true);
13124                if (succeeded) {
13125                    // invoke DeviceStorageMonitor's update method to clear any notifications
13126                    DeviceStorageMonitorInternal
13127                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13128                    if (dsm != null) {
13129                        dsm.checkMemory();
13130                    }
13131                }
13132                if(observer != null) {
13133                    try {
13134                        observer.onRemoveCompleted(packageName, succeeded);
13135                    } catch (RemoteException e) {
13136                        Log.i(TAG, "Observer no longer exists.");
13137                    }
13138                } //end if observer
13139            } //end run
13140        });
13141    }
13142
13143    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13144        if (packageName == null) {
13145            Slog.w(TAG, "Attempt to delete null packageName.");
13146            return false;
13147        }
13148
13149        // Try finding details about the requested package
13150        PackageParser.Package pkg;
13151        synchronized (mPackages) {
13152            pkg = mPackages.get(packageName);
13153            if (pkg == null) {
13154                final PackageSetting ps = mSettings.mPackages.get(packageName);
13155                if (ps != null) {
13156                    pkg = ps.pkg;
13157                }
13158            }
13159
13160            if (pkg == null) {
13161                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13162                return false;
13163            }
13164
13165            PackageSetting ps = (PackageSetting) pkg.mExtras;
13166            resetUserChangesToRuntimePermissionsAndFlagsLocked(ps, userId);
13167        }
13168
13169        // Always delete data directories for package, even if we found no other
13170        // record of app. This helps users recover from UID mismatches without
13171        // resorting to a full data wipe.
13172        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13173        if (retCode < 0) {
13174            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13175            return false;
13176        }
13177
13178        final int appId = pkg.applicationInfo.uid;
13179        removeKeystoreDataIfNeeded(userId, appId);
13180
13181        // Create a native library symlink only if we have native libraries
13182        // and if the native libraries are 32 bit libraries. We do not provide
13183        // this symlink for 64 bit libraries.
13184        if (pkg.applicationInfo.primaryCpuAbi != null &&
13185                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13186            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13187            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13188                    nativeLibPath, userId) < 0) {
13189                Slog.w(TAG, "Failed linking native library dir");
13190                return false;
13191            }
13192        }
13193
13194        return true;
13195    }
13196
13197    /**
13198     * Reverts user permission state changes (permissions and flags).
13199     *
13200     * @param ps The package for which to reset.
13201     * @param userId The device user for which to do a reset.
13202     */
13203    private void resetUserChangesToRuntimePermissionsAndFlagsLocked(
13204            final PackageSetting ps, final int userId) {
13205        if (ps.pkg == null) {
13206            return;
13207        }
13208
13209        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13210                | FLAG_PERMISSION_USER_FIXED
13211                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13212
13213        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13214                | FLAG_PERMISSION_POLICY_FIXED;
13215
13216        boolean writeInstallPermissions = false;
13217        boolean writeRuntimePermissions = false;
13218
13219        final int permissionCount = ps.pkg.requestedPermissions.size();
13220        for (int i = 0; i < permissionCount; i++) {
13221            String permission = ps.pkg.requestedPermissions.get(i);
13222
13223            BasePermission bp = mSettings.mPermissions.get(permission);
13224            if (bp == null) {
13225                continue;
13226            }
13227
13228            // If shared user we just reset the state to which only this app contributed.
13229            if (ps.sharedUser != null) {
13230                boolean used = false;
13231                final int packageCount = ps.sharedUser.packages.size();
13232                for (int j = 0; j < packageCount; j++) {
13233                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13234                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13235                            && pkg.pkg.requestedPermissions.contains(permission)) {
13236                        used = true;
13237                        break;
13238                    }
13239                }
13240                if (used) {
13241                    continue;
13242                }
13243            }
13244
13245            PermissionsState permissionsState = ps.getPermissionsState();
13246
13247            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13248
13249            // Always clear the user settable flags.
13250            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13251                    bp.name) != null;
13252            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13253                if (hasInstallState) {
13254                    writeInstallPermissions = true;
13255                } else {
13256                    writeRuntimePermissions = true;
13257                }
13258            }
13259
13260            // Below is only runtime permission handling.
13261            if (!bp.isRuntime()) {
13262                continue;
13263            }
13264
13265            // Never clobber system or policy.
13266            if ((oldFlags & policyOrSystemFlags) != 0) {
13267                continue;
13268            }
13269
13270            // If this permission was granted by default, make sure it is.
13271            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13272                if (permissionsState.grantRuntimePermission(bp, userId)
13273                        != PERMISSION_OPERATION_FAILURE) {
13274                    writeRuntimePermissions = true;
13275                }
13276            } else {
13277                // Otherwise, reset the permission.
13278                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13279                switch (revokeResult) {
13280                    case PERMISSION_OPERATION_SUCCESS: {
13281                        writeRuntimePermissions = true;
13282                    } break;
13283
13284                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13285                        writeRuntimePermissions = true;
13286                        // If gids changed for this user, kill all affected packages.
13287                        mHandler.post(new Runnable() {
13288                            @Override
13289                            public void run() {
13290                                // This has to happen with no lock held.
13291                                killSettingPackagesForUser(ps, userId,
13292                                        KILL_APP_REASON_GIDS_CHANGED);
13293                            }
13294                        });
13295                    } break;
13296                }
13297            }
13298        }
13299
13300        // Synchronously write as we are taking permissions away.
13301        if (writeRuntimePermissions) {
13302            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13303        }
13304
13305        // Synchronously write as we are taking permissions away.
13306        if (writeInstallPermissions) {
13307            mSettings.writeLPr();
13308        }
13309    }
13310
13311    /**
13312     * Remove entries from the keystore daemon. Will only remove it if the
13313     * {@code appId} is valid.
13314     */
13315    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13316        if (appId < 0) {
13317            return;
13318        }
13319
13320        final KeyStore keyStore = KeyStore.getInstance();
13321        if (keyStore != null) {
13322            if (userId == UserHandle.USER_ALL) {
13323                for (final int individual : sUserManager.getUserIds()) {
13324                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13325                }
13326            } else {
13327                keyStore.clearUid(UserHandle.getUid(userId, appId));
13328            }
13329        } else {
13330            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13331        }
13332    }
13333
13334    @Override
13335    public void deleteApplicationCacheFiles(final String packageName,
13336            final IPackageDataObserver observer) {
13337        mContext.enforceCallingOrSelfPermission(
13338                android.Manifest.permission.DELETE_CACHE_FILES, null);
13339        // Queue up an async operation since the package deletion may take a little while.
13340        final int userId = UserHandle.getCallingUserId();
13341        mHandler.post(new Runnable() {
13342            public void run() {
13343                mHandler.removeCallbacks(this);
13344                final boolean succeded;
13345                synchronized (mInstallLock) {
13346                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13347                }
13348                clearExternalStorageDataSync(packageName, userId, false);
13349                if (observer != null) {
13350                    try {
13351                        observer.onRemoveCompleted(packageName, succeded);
13352                    } catch (RemoteException e) {
13353                        Log.i(TAG, "Observer no longer exists.");
13354                    }
13355                } //end if observer
13356            } //end run
13357        });
13358    }
13359
13360    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13361        if (packageName == null) {
13362            Slog.w(TAG, "Attempt to delete null packageName.");
13363            return false;
13364        }
13365        PackageParser.Package p;
13366        synchronized (mPackages) {
13367            p = mPackages.get(packageName);
13368        }
13369        if (p == null) {
13370            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13371            return false;
13372        }
13373        final ApplicationInfo applicationInfo = p.applicationInfo;
13374        if (applicationInfo == null) {
13375            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13376            return false;
13377        }
13378        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13379        if (retCode < 0) {
13380            Slog.w(TAG, "Couldn't remove cache files for package: "
13381                       + packageName + " u" + userId);
13382            return false;
13383        }
13384        return true;
13385    }
13386
13387    @Override
13388    public void getPackageSizeInfo(final String packageName, int userHandle,
13389            final IPackageStatsObserver observer) {
13390        mContext.enforceCallingOrSelfPermission(
13391                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13392        if (packageName == null) {
13393            throw new IllegalArgumentException("Attempt to get size of null packageName");
13394        }
13395
13396        PackageStats stats = new PackageStats(packageName, userHandle);
13397
13398        /*
13399         * Queue up an async operation since the package measurement may take a
13400         * little while.
13401         */
13402        Message msg = mHandler.obtainMessage(INIT_COPY);
13403        msg.obj = new MeasureParams(stats, observer);
13404        mHandler.sendMessage(msg);
13405    }
13406
13407    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13408            PackageStats pStats) {
13409        if (packageName == null) {
13410            Slog.w(TAG, "Attempt to get size of null packageName.");
13411            return false;
13412        }
13413        PackageParser.Package p;
13414        boolean dataOnly = false;
13415        String libDirRoot = null;
13416        String asecPath = null;
13417        PackageSetting ps = null;
13418        synchronized (mPackages) {
13419            p = mPackages.get(packageName);
13420            ps = mSettings.mPackages.get(packageName);
13421            if(p == null) {
13422                dataOnly = true;
13423                if((ps == null) || (ps.pkg == null)) {
13424                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13425                    return false;
13426                }
13427                p = ps.pkg;
13428            }
13429            if (ps != null) {
13430                libDirRoot = ps.legacyNativeLibraryPathString;
13431            }
13432            if (p != null && (isExternal(p) || p.isForwardLocked())) {
13433                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13434                if (secureContainerId != null) {
13435                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13436                }
13437            }
13438        }
13439        String publicSrcDir = null;
13440        if(!dataOnly) {
13441            final ApplicationInfo applicationInfo = p.applicationInfo;
13442            if (applicationInfo == null) {
13443                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13444                return false;
13445            }
13446            if (p.isForwardLocked()) {
13447                publicSrcDir = applicationInfo.getBaseResourcePath();
13448            }
13449        }
13450        // TODO: extend to measure size of split APKs
13451        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13452        // not just the first level.
13453        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13454        // just the primary.
13455        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13456        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
13457                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13458        if (res < 0) {
13459            return false;
13460        }
13461
13462        // Fix-up for forward-locked applications in ASEC containers.
13463        if (!isExternal(p)) {
13464            pStats.codeSize += pStats.externalCodeSize;
13465            pStats.externalCodeSize = 0L;
13466        }
13467
13468        return true;
13469    }
13470
13471
13472    @Override
13473    public void addPackageToPreferred(String packageName) {
13474        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13475    }
13476
13477    @Override
13478    public void removePackageFromPreferred(String packageName) {
13479        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13480    }
13481
13482    @Override
13483    public List<PackageInfo> getPreferredPackages(int flags) {
13484        return new ArrayList<PackageInfo>();
13485    }
13486
13487    private int getUidTargetSdkVersionLockedLPr(int uid) {
13488        Object obj = mSettings.getUserIdLPr(uid);
13489        if (obj instanceof SharedUserSetting) {
13490            final SharedUserSetting sus = (SharedUserSetting) obj;
13491            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13492            final Iterator<PackageSetting> it = sus.packages.iterator();
13493            while (it.hasNext()) {
13494                final PackageSetting ps = it.next();
13495                if (ps.pkg != null) {
13496                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13497                    if (v < vers) vers = v;
13498                }
13499            }
13500            return vers;
13501        } else if (obj instanceof PackageSetting) {
13502            final PackageSetting ps = (PackageSetting) obj;
13503            if (ps.pkg != null) {
13504                return ps.pkg.applicationInfo.targetSdkVersion;
13505            }
13506        }
13507        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13508    }
13509
13510    @Override
13511    public void addPreferredActivity(IntentFilter filter, int match,
13512            ComponentName[] set, ComponentName activity, int userId) {
13513        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13514                "Adding preferred");
13515    }
13516
13517    private void addPreferredActivityInternal(IntentFilter filter, int match,
13518            ComponentName[] set, ComponentName activity, boolean always, int userId,
13519            String opname) {
13520        // writer
13521        int callingUid = Binder.getCallingUid();
13522        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13523        if (filter.countActions() == 0) {
13524            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13525            return;
13526        }
13527        synchronized (mPackages) {
13528            if (mContext.checkCallingOrSelfPermission(
13529                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13530                    != PackageManager.PERMISSION_GRANTED) {
13531                if (getUidTargetSdkVersionLockedLPr(callingUid)
13532                        < Build.VERSION_CODES.FROYO) {
13533                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13534                            + callingUid);
13535                    return;
13536                }
13537                mContext.enforceCallingOrSelfPermission(
13538                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13539            }
13540
13541            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13542            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13543                    + userId + ":");
13544            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13545            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13546            scheduleWritePackageRestrictionsLocked(userId);
13547        }
13548    }
13549
13550    @Override
13551    public void replacePreferredActivity(IntentFilter filter, int match,
13552            ComponentName[] set, ComponentName activity, int userId) {
13553        if (filter.countActions() != 1) {
13554            throw new IllegalArgumentException(
13555                    "replacePreferredActivity expects filter to have only 1 action.");
13556        }
13557        if (filter.countDataAuthorities() != 0
13558                || filter.countDataPaths() != 0
13559                || filter.countDataSchemes() > 1
13560                || filter.countDataTypes() != 0) {
13561            throw new IllegalArgumentException(
13562                    "replacePreferredActivity expects filter to have no data authorities, " +
13563                    "paths, or types; and at most one scheme.");
13564        }
13565
13566        final int callingUid = Binder.getCallingUid();
13567        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13568        synchronized (mPackages) {
13569            if (mContext.checkCallingOrSelfPermission(
13570                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13571                    != PackageManager.PERMISSION_GRANTED) {
13572                if (getUidTargetSdkVersionLockedLPr(callingUid)
13573                        < Build.VERSION_CODES.FROYO) {
13574                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13575                            + Binder.getCallingUid());
13576                    return;
13577                }
13578                mContext.enforceCallingOrSelfPermission(
13579                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13580            }
13581
13582            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13583            if (pir != null) {
13584                // Get all of the existing entries that exactly match this filter.
13585                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13586                if (existing != null && existing.size() == 1) {
13587                    PreferredActivity cur = existing.get(0);
13588                    if (DEBUG_PREFERRED) {
13589                        Slog.i(TAG, "Checking replace of preferred:");
13590                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13591                        if (!cur.mPref.mAlways) {
13592                            Slog.i(TAG, "  -- CUR; not mAlways!");
13593                        } else {
13594                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13595                            Slog.i(TAG, "  -- CUR: mSet="
13596                                    + Arrays.toString(cur.mPref.mSetComponents));
13597                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13598                            Slog.i(TAG, "  -- NEW: mMatch="
13599                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13600                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13601                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13602                        }
13603                    }
13604                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13605                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13606                            && cur.mPref.sameSet(set)) {
13607                        // Setting the preferred activity to what it happens to be already
13608                        if (DEBUG_PREFERRED) {
13609                            Slog.i(TAG, "Replacing with same preferred activity "
13610                                    + cur.mPref.mShortComponent + " for user "
13611                                    + userId + ":");
13612                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13613                        }
13614                        return;
13615                    }
13616                }
13617
13618                if (existing != null) {
13619                    if (DEBUG_PREFERRED) {
13620                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13621                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13622                    }
13623                    for (int i = 0; i < existing.size(); i++) {
13624                        PreferredActivity pa = existing.get(i);
13625                        if (DEBUG_PREFERRED) {
13626                            Slog.i(TAG, "Removing existing preferred activity "
13627                                    + pa.mPref.mComponent + ":");
13628                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13629                        }
13630                        pir.removeFilter(pa);
13631                    }
13632                }
13633            }
13634            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13635                    "Replacing preferred");
13636        }
13637    }
13638
13639    @Override
13640    public void clearPackagePreferredActivities(String packageName) {
13641        final int uid = Binder.getCallingUid();
13642        // writer
13643        synchronized (mPackages) {
13644            PackageParser.Package pkg = mPackages.get(packageName);
13645            if (pkg == null || pkg.applicationInfo.uid != uid) {
13646                if (mContext.checkCallingOrSelfPermission(
13647                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13648                        != PackageManager.PERMISSION_GRANTED) {
13649                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13650                            < Build.VERSION_CODES.FROYO) {
13651                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13652                                + Binder.getCallingUid());
13653                        return;
13654                    }
13655                    mContext.enforceCallingOrSelfPermission(
13656                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13657                }
13658            }
13659
13660            int user = UserHandle.getCallingUserId();
13661            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13662                scheduleWritePackageRestrictionsLocked(user);
13663            }
13664        }
13665    }
13666
13667    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13668    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13669        ArrayList<PreferredActivity> removed = null;
13670        boolean changed = false;
13671        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13672            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13673            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13674            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13675                continue;
13676            }
13677            Iterator<PreferredActivity> it = pir.filterIterator();
13678            while (it.hasNext()) {
13679                PreferredActivity pa = it.next();
13680                // Mark entry for removal only if it matches the package name
13681                // and the entry is of type "always".
13682                if (packageName == null ||
13683                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13684                                && pa.mPref.mAlways)) {
13685                    if (removed == null) {
13686                        removed = new ArrayList<PreferredActivity>();
13687                    }
13688                    removed.add(pa);
13689                }
13690            }
13691            if (removed != null) {
13692                for (int j=0; j<removed.size(); j++) {
13693                    PreferredActivity pa = removed.get(j);
13694                    pir.removeFilter(pa);
13695                }
13696                changed = true;
13697            }
13698        }
13699        return changed;
13700    }
13701
13702    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13703    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13704        if (userId == UserHandle.USER_ALL) {
13705            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13706                    sUserManager.getUserIds())) {
13707                for (int oneUserId : sUserManager.getUserIds()) {
13708                    scheduleWritePackageRestrictionsLocked(oneUserId);
13709                }
13710            }
13711        } else {
13712            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13713                scheduleWritePackageRestrictionsLocked(userId);
13714            }
13715        }
13716    }
13717
13718
13719    void clearDefaultBrowserIfNeeded(String packageName) {
13720        for (int oneUserId : sUserManager.getUserIds()) {
13721            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
13722            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
13723            if (packageName.equals(defaultBrowserPackageName)) {
13724                setDefaultBrowserPackageName(null, oneUserId);
13725            }
13726        }
13727    }
13728
13729    @Override
13730    public void resetPreferredActivities(int userId) {
13731        mContext.enforceCallingOrSelfPermission(
13732                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13733        // writer
13734        synchronized (mPackages) {
13735            clearPackagePreferredActivitiesLPw(null, userId);
13736            mSettings.applyDefaultPreferredAppsLPw(this, userId);
13737            applyFactoryDefaultBrowserLPw(userId);
13738            primeDomainVerificationsLPw(userId);
13739
13740            scheduleWritePackageRestrictionsLocked(userId);
13741        }
13742    }
13743
13744    @Override
13745    public int getPreferredActivities(List<IntentFilter> outFilters,
13746            List<ComponentName> outActivities, String packageName) {
13747
13748        int num = 0;
13749        final int userId = UserHandle.getCallingUserId();
13750        // reader
13751        synchronized (mPackages) {
13752            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13753            if (pir != null) {
13754                final Iterator<PreferredActivity> it = pir.filterIterator();
13755                while (it.hasNext()) {
13756                    final PreferredActivity pa = it.next();
13757                    if (packageName == null
13758                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
13759                                    && pa.mPref.mAlways)) {
13760                        if (outFilters != null) {
13761                            outFilters.add(new IntentFilter(pa));
13762                        }
13763                        if (outActivities != null) {
13764                            outActivities.add(pa.mPref.mComponent);
13765                        }
13766                    }
13767                }
13768            }
13769        }
13770
13771        return num;
13772    }
13773
13774    @Override
13775    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
13776            int userId) {
13777        int callingUid = Binder.getCallingUid();
13778        if (callingUid != Process.SYSTEM_UID) {
13779            throw new SecurityException(
13780                    "addPersistentPreferredActivity can only be run by the system");
13781        }
13782        if (filter.countActions() == 0) {
13783            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13784            return;
13785        }
13786        synchronized (mPackages) {
13787            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
13788                    " :");
13789            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13790            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
13791                    new PersistentPreferredActivity(filter, activity));
13792            scheduleWritePackageRestrictionsLocked(userId);
13793        }
13794    }
13795
13796    @Override
13797    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
13798        int callingUid = Binder.getCallingUid();
13799        if (callingUid != Process.SYSTEM_UID) {
13800            throw new SecurityException(
13801                    "clearPackagePersistentPreferredActivities can only be run by the system");
13802        }
13803        ArrayList<PersistentPreferredActivity> removed = null;
13804        boolean changed = false;
13805        synchronized (mPackages) {
13806            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
13807                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
13808                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
13809                        .valueAt(i);
13810                if (userId != thisUserId) {
13811                    continue;
13812                }
13813                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
13814                while (it.hasNext()) {
13815                    PersistentPreferredActivity ppa = it.next();
13816                    // Mark entry for removal only if it matches the package name.
13817                    if (ppa.mComponent.getPackageName().equals(packageName)) {
13818                        if (removed == null) {
13819                            removed = new ArrayList<PersistentPreferredActivity>();
13820                        }
13821                        removed.add(ppa);
13822                    }
13823                }
13824                if (removed != null) {
13825                    for (int j=0; j<removed.size(); j++) {
13826                        PersistentPreferredActivity ppa = removed.get(j);
13827                        ppir.removeFilter(ppa);
13828                    }
13829                    changed = true;
13830                }
13831            }
13832
13833            if (changed) {
13834                scheduleWritePackageRestrictionsLocked(userId);
13835            }
13836        }
13837    }
13838
13839    /**
13840     * Common machinery for picking apart a restored XML blob and passing
13841     * it to a caller-supplied functor to be applied to the running system.
13842     */
13843    private void restoreFromXml(XmlPullParser parser, int userId,
13844            String expectedStartTag, BlobXmlRestorer functor)
13845            throws IOException, XmlPullParserException {
13846        int type;
13847        while ((type = parser.next()) != XmlPullParser.START_TAG
13848                && type != XmlPullParser.END_DOCUMENT) {
13849        }
13850        if (type != XmlPullParser.START_TAG) {
13851            // oops didn't find a start tag?!
13852            if (DEBUG_BACKUP) {
13853                Slog.e(TAG, "Didn't find start tag during restore");
13854            }
13855            return;
13856        }
13857
13858        // this is supposed to be TAG_PREFERRED_BACKUP
13859        if (!expectedStartTag.equals(parser.getName())) {
13860            if (DEBUG_BACKUP) {
13861                Slog.e(TAG, "Found unexpected tag " + parser.getName());
13862            }
13863            return;
13864        }
13865
13866        // skip interfering stuff, then we're aligned with the backing implementation
13867        while ((type = parser.next()) == XmlPullParser.TEXT) { }
13868        functor.apply(parser, userId);
13869    }
13870
13871    private interface BlobXmlRestorer {
13872        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
13873    }
13874
13875    /**
13876     * Non-Binder method, support for the backup/restore mechanism: write the
13877     * full set of preferred activities in its canonical XML format.  Returns the
13878     * XML output as a byte array, or null if there is none.
13879     */
13880    @Override
13881    public byte[] getPreferredActivityBackup(int userId) {
13882        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13883            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13884        }
13885
13886        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13887        try {
13888            final XmlSerializer serializer = new FastXmlSerializer();
13889            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13890            serializer.startDocument(null, true);
13891            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13892
13893            synchronized (mPackages) {
13894                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13895            }
13896
13897            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13898            serializer.endDocument();
13899            serializer.flush();
13900        } catch (Exception e) {
13901            if (DEBUG_BACKUP) {
13902                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13903            }
13904            return null;
13905        }
13906
13907        return dataStream.toByteArray();
13908    }
13909
13910    @Override
13911    public void restorePreferredActivities(byte[] backup, int userId) {
13912        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13913            throw new SecurityException("Only the system may call restorePreferredActivities()");
13914        }
13915
13916        try {
13917            final XmlPullParser parser = Xml.newPullParser();
13918            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13919            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
13920                    new BlobXmlRestorer() {
13921                        @Override
13922                        public void apply(XmlPullParser parser, int userId)
13923                                throws XmlPullParserException, IOException {
13924                            synchronized (mPackages) {
13925                                mSettings.readPreferredActivitiesLPw(parser, userId);
13926                            }
13927                        }
13928                    } );
13929        } catch (Exception e) {
13930            if (DEBUG_BACKUP) {
13931                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13932            }
13933        }
13934    }
13935
13936    /**
13937     * Non-Binder method, support for the backup/restore mechanism: write the
13938     * default browser (etc) settings in its canonical XML format.  Returns the default
13939     * browser XML representation as a byte array, or null if there is none.
13940     */
13941    @Override
13942    public byte[] getDefaultAppsBackup(int userId) {
13943        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13944            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
13945        }
13946
13947        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13948        try {
13949            final XmlSerializer serializer = new FastXmlSerializer();
13950            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
13951            serializer.startDocument(null, true);
13952            serializer.startTag(null, TAG_DEFAULT_APPS);
13953
13954            synchronized (mPackages) {
13955                mSettings.writeDefaultAppsLPr(serializer, userId);
13956            }
13957
13958            serializer.endTag(null, TAG_DEFAULT_APPS);
13959            serializer.endDocument();
13960            serializer.flush();
13961        } catch (Exception e) {
13962            if (DEBUG_BACKUP) {
13963                Slog.e(TAG, "Unable to write default apps for backup", e);
13964            }
13965            return null;
13966        }
13967
13968        return dataStream.toByteArray();
13969    }
13970
13971    @Override
13972    public void restoreDefaultApps(byte[] backup, int userId) {
13973        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13974            throw new SecurityException("Only the system may call restoreDefaultApps()");
13975        }
13976
13977        try {
13978            final XmlPullParser parser = Xml.newPullParser();
13979            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
13980            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
13981                    new BlobXmlRestorer() {
13982                        @Override
13983                        public void apply(XmlPullParser parser, int userId)
13984                                throws XmlPullParserException, IOException {
13985                            synchronized (mPackages) {
13986                                mSettings.readDefaultAppsLPw(parser, userId);
13987                            }
13988                        }
13989                    } );
13990        } catch (Exception e) {
13991            if (DEBUG_BACKUP) {
13992                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
13993            }
13994        }
13995    }
13996
13997    @Override
13998    public byte[] getIntentFilterVerificationBackup(int userId) {
13999        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14000            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14001        }
14002
14003        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14004        try {
14005            final XmlSerializer serializer = new FastXmlSerializer();
14006            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14007            serializer.startDocument(null, true);
14008            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14009
14010            synchronized (mPackages) {
14011                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14012            }
14013
14014            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14015            serializer.endDocument();
14016            serializer.flush();
14017        } catch (Exception e) {
14018            if (DEBUG_BACKUP) {
14019                Slog.e(TAG, "Unable to write default apps for backup", e);
14020            }
14021            return null;
14022        }
14023
14024        return dataStream.toByteArray();
14025    }
14026
14027    @Override
14028    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14029        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14030            throw new SecurityException("Only the system may call restorePreferredActivities()");
14031        }
14032
14033        try {
14034            final XmlPullParser parser = Xml.newPullParser();
14035            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14036            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14037                    new BlobXmlRestorer() {
14038                        @Override
14039                        public void apply(XmlPullParser parser, int userId)
14040                                throws XmlPullParserException, IOException {
14041                            synchronized (mPackages) {
14042                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14043                                mSettings.writeLPr();
14044                            }
14045                        }
14046                    } );
14047        } catch (Exception e) {
14048            if (DEBUG_BACKUP) {
14049                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14050            }
14051        }
14052    }
14053
14054    @Override
14055    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14056            int sourceUserId, int targetUserId, int flags) {
14057        mContext.enforceCallingOrSelfPermission(
14058                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14059        int callingUid = Binder.getCallingUid();
14060        enforceOwnerRights(ownerPackage, callingUid);
14061        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14062        if (intentFilter.countActions() == 0) {
14063            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14064            return;
14065        }
14066        synchronized (mPackages) {
14067            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14068                    ownerPackage, targetUserId, flags);
14069            CrossProfileIntentResolver resolver =
14070                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14071            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14072            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14073            if (existing != null) {
14074                int size = existing.size();
14075                for (int i = 0; i < size; i++) {
14076                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14077                        return;
14078                    }
14079                }
14080            }
14081            resolver.addFilter(newFilter);
14082            scheduleWritePackageRestrictionsLocked(sourceUserId);
14083        }
14084    }
14085
14086    @Override
14087    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14088        mContext.enforceCallingOrSelfPermission(
14089                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14090        int callingUid = Binder.getCallingUid();
14091        enforceOwnerRights(ownerPackage, callingUid);
14092        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14093        synchronized (mPackages) {
14094            CrossProfileIntentResolver resolver =
14095                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14096            ArraySet<CrossProfileIntentFilter> set =
14097                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14098            for (CrossProfileIntentFilter filter : set) {
14099                if (filter.getOwnerPackage().equals(ownerPackage)) {
14100                    resolver.removeFilter(filter);
14101                }
14102            }
14103            scheduleWritePackageRestrictionsLocked(sourceUserId);
14104        }
14105    }
14106
14107    // Enforcing that callingUid is owning pkg on userId
14108    private void enforceOwnerRights(String pkg, int callingUid) {
14109        // The system owns everything.
14110        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14111            return;
14112        }
14113        int callingUserId = UserHandle.getUserId(callingUid);
14114        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14115        if (pi == null) {
14116            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14117                    + callingUserId);
14118        }
14119        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14120            throw new SecurityException("Calling uid " + callingUid
14121                    + " does not own package " + pkg);
14122        }
14123    }
14124
14125    @Override
14126    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14127        Intent intent = new Intent(Intent.ACTION_MAIN);
14128        intent.addCategory(Intent.CATEGORY_HOME);
14129
14130        final int callingUserId = UserHandle.getCallingUserId();
14131        List<ResolveInfo> list = queryIntentActivities(intent, null,
14132                PackageManager.GET_META_DATA, callingUserId);
14133        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14134                true, false, false, callingUserId);
14135
14136        allHomeCandidates.clear();
14137        if (list != null) {
14138            for (ResolveInfo ri : list) {
14139                allHomeCandidates.add(ri);
14140            }
14141        }
14142        return (preferred == null || preferred.activityInfo == null)
14143                ? null
14144                : new ComponentName(preferred.activityInfo.packageName,
14145                        preferred.activityInfo.name);
14146    }
14147
14148    @Override
14149    public void setApplicationEnabledSetting(String appPackageName,
14150            int newState, int flags, int userId, String callingPackage) {
14151        if (!sUserManager.exists(userId)) return;
14152        if (callingPackage == null) {
14153            callingPackage = Integer.toString(Binder.getCallingUid());
14154        }
14155        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14156    }
14157
14158    @Override
14159    public void setComponentEnabledSetting(ComponentName componentName,
14160            int newState, int flags, int userId) {
14161        if (!sUserManager.exists(userId)) return;
14162        setEnabledSetting(componentName.getPackageName(),
14163                componentName.getClassName(), newState, flags, userId, null);
14164    }
14165
14166    private void setEnabledSetting(final String packageName, String className, int newState,
14167            final int flags, int userId, String callingPackage) {
14168        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14169              || newState == COMPONENT_ENABLED_STATE_ENABLED
14170              || newState == COMPONENT_ENABLED_STATE_DISABLED
14171              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14172              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14173            throw new IllegalArgumentException("Invalid new component state: "
14174                    + newState);
14175        }
14176        PackageSetting pkgSetting;
14177        final int uid = Binder.getCallingUid();
14178        final int permission = mContext.checkCallingOrSelfPermission(
14179                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14180        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14181        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14182        boolean sendNow = false;
14183        boolean isApp = (className == null);
14184        String componentName = isApp ? packageName : className;
14185        int packageUid = -1;
14186        ArrayList<String> components;
14187
14188        // writer
14189        synchronized (mPackages) {
14190            pkgSetting = mSettings.mPackages.get(packageName);
14191            if (pkgSetting == null) {
14192                if (className == null) {
14193                    throw new IllegalArgumentException(
14194                            "Unknown package: " + packageName);
14195                }
14196                throw new IllegalArgumentException(
14197                        "Unknown component: " + packageName
14198                        + "/" + className);
14199            }
14200            // Allow root and verify that userId is not being specified by a different user
14201            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14202                throw new SecurityException(
14203                        "Permission Denial: attempt to change component state from pid="
14204                        + Binder.getCallingPid()
14205                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14206            }
14207            if (className == null) {
14208                // We're dealing with an application/package level state change
14209                if (pkgSetting.getEnabled(userId) == newState) {
14210                    // Nothing to do
14211                    return;
14212                }
14213                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14214                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14215                    // Don't care about who enables an app.
14216                    callingPackage = null;
14217                }
14218                pkgSetting.setEnabled(newState, userId, callingPackage);
14219                // pkgSetting.pkg.mSetEnabled = newState;
14220            } else {
14221                // We're dealing with a component level state change
14222                // First, verify that this is a valid class name.
14223                PackageParser.Package pkg = pkgSetting.pkg;
14224                if (pkg == null || !pkg.hasComponentClassName(className)) {
14225                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14226                        throw new IllegalArgumentException("Component class " + className
14227                                + " does not exist in " + packageName);
14228                    } else {
14229                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14230                                + className + " does not exist in " + packageName);
14231                    }
14232                }
14233                switch (newState) {
14234                case COMPONENT_ENABLED_STATE_ENABLED:
14235                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14236                        return;
14237                    }
14238                    break;
14239                case COMPONENT_ENABLED_STATE_DISABLED:
14240                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14241                        return;
14242                    }
14243                    break;
14244                case COMPONENT_ENABLED_STATE_DEFAULT:
14245                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14246                        return;
14247                    }
14248                    break;
14249                default:
14250                    Slog.e(TAG, "Invalid new component state: " + newState);
14251                    return;
14252                }
14253            }
14254            scheduleWritePackageRestrictionsLocked(userId);
14255            components = mPendingBroadcasts.get(userId, packageName);
14256            final boolean newPackage = components == null;
14257            if (newPackage) {
14258                components = new ArrayList<String>();
14259            }
14260            if (!components.contains(componentName)) {
14261                components.add(componentName);
14262            }
14263            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14264                sendNow = true;
14265                // Purge entry from pending broadcast list if another one exists already
14266                // since we are sending one right away.
14267                mPendingBroadcasts.remove(userId, packageName);
14268            } else {
14269                if (newPackage) {
14270                    mPendingBroadcasts.put(userId, packageName, components);
14271                }
14272                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14273                    // Schedule a message
14274                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14275                }
14276            }
14277        }
14278
14279        long callingId = Binder.clearCallingIdentity();
14280        try {
14281            if (sendNow) {
14282                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14283                sendPackageChangedBroadcast(packageName,
14284                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14285            }
14286        } finally {
14287            Binder.restoreCallingIdentity(callingId);
14288        }
14289    }
14290
14291    private void sendPackageChangedBroadcast(String packageName,
14292            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14293        if (DEBUG_INSTALL)
14294            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14295                    + componentNames);
14296        Bundle extras = new Bundle(4);
14297        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14298        String nameList[] = new String[componentNames.size()];
14299        componentNames.toArray(nameList);
14300        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14301        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14302        extras.putInt(Intent.EXTRA_UID, packageUid);
14303        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14304                new int[] {UserHandle.getUserId(packageUid)});
14305    }
14306
14307    @Override
14308    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14309        if (!sUserManager.exists(userId)) return;
14310        final int uid = Binder.getCallingUid();
14311        final int permission = mContext.checkCallingOrSelfPermission(
14312                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14313        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14314        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14315        // writer
14316        synchronized (mPackages) {
14317            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14318                    allowedByPermission, uid, userId)) {
14319                scheduleWritePackageRestrictionsLocked(userId);
14320            }
14321        }
14322    }
14323
14324    @Override
14325    public String getInstallerPackageName(String packageName) {
14326        // reader
14327        synchronized (mPackages) {
14328            return mSettings.getInstallerPackageNameLPr(packageName);
14329        }
14330    }
14331
14332    @Override
14333    public int getApplicationEnabledSetting(String packageName, int userId) {
14334        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14335        int uid = Binder.getCallingUid();
14336        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14337        // reader
14338        synchronized (mPackages) {
14339            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14340        }
14341    }
14342
14343    @Override
14344    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14345        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14346        int uid = Binder.getCallingUid();
14347        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14348        // reader
14349        synchronized (mPackages) {
14350            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14351        }
14352    }
14353
14354    @Override
14355    public void enterSafeMode() {
14356        enforceSystemOrRoot("Only the system can request entering safe mode");
14357
14358        if (!mSystemReady) {
14359            mSafeMode = true;
14360        }
14361    }
14362
14363    @Override
14364    public void systemReady() {
14365        mSystemReady = true;
14366
14367        // Read the compatibilty setting when the system is ready.
14368        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14369                mContext.getContentResolver(),
14370                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14371        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14372        if (DEBUG_SETTINGS) {
14373            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14374        }
14375
14376        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14377
14378        synchronized (mPackages) {
14379            // Verify that all of the preferred activity components actually
14380            // exist.  It is possible for applications to be updated and at
14381            // that point remove a previously declared activity component that
14382            // had been set as a preferred activity.  We try to clean this up
14383            // the next time we encounter that preferred activity, but it is
14384            // possible for the user flow to never be able to return to that
14385            // situation so here we do a sanity check to make sure we haven't
14386            // left any junk around.
14387            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14388            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14389                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14390                removed.clear();
14391                for (PreferredActivity pa : pir.filterSet()) {
14392                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14393                        removed.add(pa);
14394                    }
14395                }
14396                if (removed.size() > 0) {
14397                    for (int r=0; r<removed.size(); r++) {
14398                        PreferredActivity pa = removed.get(r);
14399                        Slog.w(TAG, "Removing dangling preferred activity: "
14400                                + pa.mPref.mComponent);
14401                        pir.removeFilter(pa);
14402                    }
14403                    mSettings.writePackageRestrictionsLPr(
14404                            mSettings.mPreferredActivities.keyAt(i));
14405                }
14406            }
14407
14408            for (int userId : UserManagerService.getInstance().getUserIds()) {
14409                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14410                    grantPermissionsUserIds = ArrayUtils.appendInt(
14411                            grantPermissionsUserIds, userId);
14412                }
14413            }
14414        }
14415        sUserManager.systemReady();
14416
14417        // If we upgraded grant all default permissions before kicking off.
14418        for (int userId : grantPermissionsUserIds) {
14419            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14420        }
14421
14422        // Kick off any messages waiting for system ready
14423        if (mPostSystemReadyMessages != null) {
14424            for (Message msg : mPostSystemReadyMessages) {
14425                msg.sendToTarget();
14426            }
14427            mPostSystemReadyMessages = null;
14428        }
14429
14430        // Watch for external volumes that come and go over time
14431        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14432        storage.registerListener(mStorageListener);
14433
14434        mInstallerService.systemReady();
14435        mPackageDexOptimizer.systemReady();
14436    }
14437
14438    @Override
14439    public boolean isSafeMode() {
14440        return mSafeMode;
14441    }
14442
14443    @Override
14444    public boolean hasSystemUidErrors() {
14445        return mHasSystemUidErrors;
14446    }
14447
14448    static String arrayToString(int[] array) {
14449        StringBuffer buf = new StringBuffer(128);
14450        buf.append('[');
14451        if (array != null) {
14452            for (int i=0; i<array.length; i++) {
14453                if (i > 0) buf.append(", ");
14454                buf.append(array[i]);
14455            }
14456        }
14457        buf.append(']');
14458        return buf.toString();
14459    }
14460
14461    static class DumpState {
14462        public static final int DUMP_LIBS = 1 << 0;
14463        public static final int DUMP_FEATURES = 1 << 1;
14464        public static final int DUMP_RESOLVERS = 1 << 2;
14465        public static final int DUMP_PERMISSIONS = 1 << 3;
14466        public static final int DUMP_PACKAGES = 1 << 4;
14467        public static final int DUMP_SHARED_USERS = 1 << 5;
14468        public static final int DUMP_MESSAGES = 1 << 6;
14469        public static final int DUMP_PROVIDERS = 1 << 7;
14470        public static final int DUMP_VERIFIERS = 1 << 8;
14471        public static final int DUMP_PREFERRED = 1 << 9;
14472        public static final int DUMP_PREFERRED_XML = 1 << 10;
14473        public static final int DUMP_KEYSETS = 1 << 11;
14474        public static final int DUMP_VERSION = 1 << 12;
14475        public static final int DUMP_INSTALLS = 1 << 13;
14476        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14477        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14478
14479        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14480
14481        private int mTypes;
14482
14483        private int mOptions;
14484
14485        private boolean mTitlePrinted;
14486
14487        private SharedUserSetting mSharedUser;
14488
14489        public boolean isDumping(int type) {
14490            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14491                return true;
14492            }
14493
14494            return (mTypes & type) != 0;
14495        }
14496
14497        public void setDump(int type) {
14498            mTypes |= type;
14499        }
14500
14501        public boolean isOptionEnabled(int option) {
14502            return (mOptions & option) != 0;
14503        }
14504
14505        public void setOptionEnabled(int option) {
14506            mOptions |= option;
14507        }
14508
14509        public boolean onTitlePrinted() {
14510            final boolean printed = mTitlePrinted;
14511            mTitlePrinted = true;
14512            return printed;
14513        }
14514
14515        public boolean getTitlePrinted() {
14516            return mTitlePrinted;
14517        }
14518
14519        public void setTitlePrinted(boolean enabled) {
14520            mTitlePrinted = enabled;
14521        }
14522
14523        public SharedUserSetting getSharedUser() {
14524            return mSharedUser;
14525        }
14526
14527        public void setSharedUser(SharedUserSetting user) {
14528            mSharedUser = user;
14529        }
14530    }
14531
14532    @Override
14533    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14534        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14535                != PackageManager.PERMISSION_GRANTED) {
14536            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14537                    + Binder.getCallingPid()
14538                    + ", uid=" + Binder.getCallingUid()
14539                    + " without permission "
14540                    + android.Manifest.permission.DUMP);
14541            return;
14542        }
14543
14544        DumpState dumpState = new DumpState();
14545        boolean fullPreferred = false;
14546        boolean checkin = false;
14547
14548        String packageName = null;
14549        ArraySet<String> permissionNames = null;
14550
14551        int opti = 0;
14552        while (opti < args.length) {
14553            String opt = args[opti];
14554            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14555                break;
14556            }
14557            opti++;
14558
14559            if ("-a".equals(opt)) {
14560                // Right now we only know how to print all.
14561            } else if ("-h".equals(opt)) {
14562                pw.println("Package manager dump options:");
14563                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14564                pw.println("    --checkin: dump for a checkin");
14565                pw.println("    -f: print details of intent filters");
14566                pw.println("    -h: print this help");
14567                pw.println("  cmd may be one of:");
14568                pw.println("    l[ibraries]: list known shared libraries");
14569                pw.println("    f[ibraries]: list device features");
14570                pw.println("    k[eysets]: print known keysets");
14571                pw.println("    r[esolvers]: dump intent resolvers");
14572                pw.println("    perm[issions]: dump permissions");
14573                pw.println("    permission [name ...]: dump declaration and use of given permission");
14574                pw.println("    pref[erred]: print preferred package settings");
14575                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14576                pw.println("    prov[iders]: dump content providers");
14577                pw.println("    p[ackages]: dump installed packages");
14578                pw.println("    s[hared-users]: dump shared user IDs");
14579                pw.println("    m[essages]: print collected runtime messages");
14580                pw.println("    v[erifiers]: print package verifier info");
14581                pw.println("    version: print database version info");
14582                pw.println("    write: write current settings now");
14583                pw.println("    <package.name>: info about given package");
14584                pw.println("    installs: details about install sessions");
14585                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14586                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14587                return;
14588            } else if ("--checkin".equals(opt)) {
14589                checkin = true;
14590            } else if ("-f".equals(opt)) {
14591                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14592            } else {
14593                pw.println("Unknown argument: " + opt + "; use -h for help");
14594            }
14595        }
14596
14597        // Is the caller requesting to dump a particular piece of data?
14598        if (opti < args.length) {
14599            String cmd = args[opti];
14600            opti++;
14601            // Is this a package name?
14602            if ("android".equals(cmd) || cmd.contains(".")) {
14603                packageName = cmd;
14604                // When dumping a single package, we always dump all of its
14605                // filter information since the amount of data will be reasonable.
14606                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14607            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14608                dumpState.setDump(DumpState.DUMP_LIBS);
14609            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14610                dumpState.setDump(DumpState.DUMP_FEATURES);
14611            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14612                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14613            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14614                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14615            } else if ("permission".equals(cmd)) {
14616                if (opti >= args.length) {
14617                    pw.println("Error: permission requires permission name");
14618                    return;
14619                }
14620                permissionNames = new ArraySet<>();
14621                while (opti < args.length) {
14622                    permissionNames.add(args[opti]);
14623                    opti++;
14624                }
14625                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14626                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14627            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14628                dumpState.setDump(DumpState.DUMP_PREFERRED);
14629            } else if ("preferred-xml".equals(cmd)) {
14630                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14631                if (opti < args.length && "--full".equals(args[opti])) {
14632                    fullPreferred = true;
14633                    opti++;
14634                }
14635            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14636                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14637            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14638                dumpState.setDump(DumpState.DUMP_PACKAGES);
14639            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14640                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14641            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14642                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14643            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14644                dumpState.setDump(DumpState.DUMP_MESSAGES);
14645            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14646                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14647            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14648                    || "intent-filter-verifiers".equals(cmd)) {
14649                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14650            } else if ("version".equals(cmd)) {
14651                dumpState.setDump(DumpState.DUMP_VERSION);
14652            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14653                dumpState.setDump(DumpState.DUMP_KEYSETS);
14654            } else if ("installs".equals(cmd)) {
14655                dumpState.setDump(DumpState.DUMP_INSTALLS);
14656            } else if ("write".equals(cmd)) {
14657                synchronized (mPackages) {
14658                    mSettings.writeLPr();
14659                    pw.println("Settings written.");
14660                    return;
14661                }
14662            }
14663        }
14664
14665        if (checkin) {
14666            pw.println("vers,1");
14667        }
14668
14669        // reader
14670        synchronized (mPackages) {
14671            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
14672                if (!checkin) {
14673                    if (dumpState.onTitlePrinted())
14674                        pw.println();
14675                    pw.println("Database versions:");
14676                    pw.print("  SDK Version:");
14677                    pw.print(" internal=");
14678                    pw.print(mSettings.mInternalSdkPlatform);
14679                    pw.print(" external=");
14680                    pw.println(mSettings.mExternalSdkPlatform);
14681                    pw.print("  DB Version:");
14682                    pw.print(" internal=");
14683                    pw.print(mSettings.mInternalDatabaseVersion);
14684                    pw.print(" external=");
14685                    pw.println(mSettings.mExternalDatabaseVersion);
14686                }
14687            }
14688
14689            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
14690                if (!checkin) {
14691                    if (dumpState.onTitlePrinted())
14692                        pw.println();
14693                    pw.println("Verifiers:");
14694                    pw.print("  Required: ");
14695                    pw.print(mRequiredVerifierPackage);
14696                    pw.print(" (uid=");
14697                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
14698                    pw.println(")");
14699                } else if (mRequiredVerifierPackage != null) {
14700                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
14701                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
14702                }
14703            }
14704
14705            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
14706                    packageName == null) {
14707                if (mIntentFilterVerifierComponent != null) {
14708                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
14709                    if (!checkin) {
14710                        if (dumpState.onTitlePrinted())
14711                            pw.println();
14712                        pw.println("Intent Filter Verifier:");
14713                        pw.print("  Using: ");
14714                        pw.print(verifierPackageName);
14715                        pw.print(" (uid=");
14716                        pw.print(getPackageUid(verifierPackageName, 0));
14717                        pw.println(")");
14718                    } else if (verifierPackageName != null) {
14719                        pw.print("ifv,"); pw.print(verifierPackageName);
14720                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
14721                    }
14722                } else {
14723                    pw.println();
14724                    pw.println("No Intent Filter Verifier available!");
14725                }
14726            }
14727
14728            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
14729                boolean printedHeader = false;
14730                final Iterator<String> it = mSharedLibraries.keySet().iterator();
14731                while (it.hasNext()) {
14732                    String name = it.next();
14733                    SharedLibraryEntry ent = mSharedLibraries.get(name);
14734                    if (!checkin) {
14735                        if (!printedHeader) {
14736                            if (dumpState.onTitlePrinted())
14737                                pw.println();
14738                            pw.println("Libraries:");
14739                            printedHeader = true;
14740                        }
14741                        pw.print("  ");
14742                    } else {
14743                        pw.print("lib,");
14744                    }
14745                    pw.print(name);
14746                    if (!checkin) {
14747                        pw.print(" -> ");
14748                    }
14749                    if (ent.path != null) {
14750                        if (!checkin) {
14751                            pw.print("(jar) ");
14752                            pw.print(ent.path);
14753                        } else {
14754                            pw.print(",jar,");
14755                            pw.print(ent.path);
14756                        }
14757                    } else {
14758                        if (!checkin) {
14759                            pw.print("(apk) ");
14760                            pw.print(ent.apk);
14761                        } else {
14762                            pw.print(",apk,");
14763                            pw.print(ent.apk);
14764                        }
14765                    }
14766                    pw.println();
14767                }
14768            }
14769
14770            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
14771                if (dumpState.onTitlePrinted())
14772                    pw.println();
14773                if (!checkin) {
14774                    pw.println("Features:");
14775                }
14776                Iterator<String> it = mAvailableFeatures.keySet().iterator();
14777                while (it.hasNext()) {
14778                    String name = it.next();
14779                    if (!checkin) {
14780                        pw.print("  ");
14781                    } else {
14782                        pw.print("feat,");
14783                    }
14784                    pw.println(name);
14785                }
14786            }
14787
14788            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
14789                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
14790                        : "Activity Resolver Table:", "  ", packageName,
14791                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14792                    dumpState.setTitlePrinted(true);
14793                }
14794                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
14795                        : "Receiver Resolver Table:", "  ", packageName,
14796                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14797                    dumpState.setTitlePrinted(true);
14798                }
14799                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
14800                        : "Service Resolver Table:", "  ", packageName,
14801                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14802                    dumpState.setTitlePrinted(true);
14803                }
14804                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
14805                        : "Provider Resolver Table:", "  ", packageName,
14806                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
14807                    dumpState.setTitlePrinted(true);
14808                }
14809            }
14810
14811            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
14812                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14813                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14814                    int user = mSettings.mPreferredActivities.keyAt(i);
14815                    if (pir.dump(pw,
14816                            dumpState.getTitlePrinted()
14817                                ? "\nPreferred Activities User " + user + ":"
14818                                : "Preferred Activities User " + user + ":", "  ",
14819                            packageName, true, false)) {
14820                        dumpState.setTitlePrinted(true);
14821                    }
14822                }
14823            }
14824
14825            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
14826                pw.flush();
14827                FileOutputStream fout = new FileOutputStream(fd);
14828                BufferedOutputStream str = new BufferedOutputStream(fout);
14829                XmlSerializer serializer = new FastXmlSerializer();
14830                try {
14831                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
14832                    serializer.startDocument(null, true);
14833                    serializer.setFeature(
14834                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
14835                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
14836                    serializer.endDocument();
14837                    serializer.flush();
14838                } catch (IllegalArgumentException e) {
14839                    pw.println("Failed writing: " + e);
14840                } catch (IllegalStateException e) {
14841                    pw.println("Failed writing: " + e);
14842                } catch (IOException e) {
14843                    pw.println("Failed writing: " + e);
14844                }
14845            }
14846
14847            if (!checkin
14848                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
14849                    && packageName == null) {
14850                pw.println();
14851                int count = mSettings.mPackages.size();
14852                if (count == 0) {
14853                    pw.println("No applications!");
14854                    pw.println();
14855                } else {
14856                    final String prefix = "  ";
14857                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
14858                    if (allPackageSettings.size() == 0) {
14859                        pw.println("No domain preferred apps!");
14860                        pw.println();
14861                    } else {
14862                        pw.println("App verification status:");
14863                        pw.println();
14864                        count = 0;
14865                        for (PackageSetting ps : allPackageSettings) {
14866                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
14867                            if (ivi == null || ivi.getPackageName() == null) continue;
14868                            pw.println(prefix + "Package: " + ivi.getPackageName());
14869                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
14870                            pw.println(prefix + "Status:  " + ivi.getStatusString());
14871                            pw.println();
14872                            count++;
14873                        }
14874                        if (count == 0) {
14875                            pw.println(prefix + "No app verification established.");
14876                            pw.println();
14877                        }
14878                        for (int userId : sUserManager.getUserIds()) {
14879                            pw.println("App linkages for user " + userId + ":");
14880                            pw.println();
14881                            count = 0;
14882                            for (PackageSetting ps : allPackageSettings) {
14883                                final int status = ps.getDomainVerificationStatusForUser(userId);
14884                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
14885                                    continue;
14886                                }
14887                                pw.println(prefix + "Package: " + ps.name);
14888                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
14889                                String statusStr = IntentFilterVerificationInfo.
14890                                        getStatusStringFromValue(status);
14891                                pw.println(prefix + "Status:  " + statusStr);
14892                                pw.println();
14893                                count++;
14894                            }
14895                            if (count == 0) {
14896                                pw.println(prefix + "No configured app linkages.");
14897                                pw.println();
14898                            }
14899                        }
14900                    }
14901                }
14902            }
14903
14904            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
14905                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
14906                if (packageName == null && permissionNames == null) {
14907                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
14908                        if (iperm == 0) {
14909                            if (dumpState.onTitlePrinted())
14910                                pw.println();
14911                            pw.println("AppOp Permissions:");
14912                        }
14913                        pw.print("  AppOp Permission ");
14914                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
14915                        pw.println(":");
14916                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
14917                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
14918                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
14919                        }
14920                    }
14921                }
14922            }
14923
14924            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
14925                boolean printedSomething = false;
14926                for (PackageParser.Provider p : mProviders.mProviders.values()) {
14927                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14928                        continue;
14929                    }
14930                    if (!printedSomething) {
14931                        if (dumpState.onTitlePrinted())
14932                            pw.println();
14933                        pw.println("Registered ContentProviders:");
14934                        printedSomething = true;
14935                    }
14936                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
14937                    pw.print("    "); pw.println(p.toString());
14938                }
14939                printedSomething = false;
14940                for (Map.Entry<String, PackageParser.Provider> entry :
14941                        mProvidersByAuthority.entrySet()) {
14942                    PackageParser.Provider p = entry.getValue();
14943                    if (packageName != null && !packageName.equals(p.info.packageName)) {
14944                        continue;
14945                    }
14946                    if (!printedSomething) {
14947                        if (dumpState.onTitlePrinted())
14948                            pw.println();
14949                        pw.println("ContentProvider Authorities:");
14950                        printedSomething = true;
14951                    }
14952                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
14953                    pw.print("    "); pw.println(p.toString());
14954                    if (p.info != null && p.info.applicationInfo != null) {
14955                        final String appInfo = p.info.applicationInfo.toString();
14956                        pw.print("      applicationInfo="); pw.println(appInfo);
14957                    }
14958                }
14959            }
14960
14961            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
14962                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
14963            }
14964
14965            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
14966                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
14967            }
14968
14969            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
14970                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
14971            }
14972
14973            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
14974                // XXX should handle packageName != null by dumping only install data that
14975                // the given package is involved with.
14976                if (dumpState.onTitlePrinted()) pw.println();
14977                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
14978            }
14979
14980            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
14981                if (dumpState.onTitlePrinted()) pw.println();
14982                mSettings.dumpReadMessagesLPr(pw, dumpState);
14983
14984                pw.println();
14985                pw.println("Package warning messages:");
14986                BufferedReader in = null;
14987                String line = null;
14988                try {
14989                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14990                    while ((line = in.readLine()) != null) {
14991                        if (line.contains("ignored: updated version")) continue;
14992                        pw.println(line);
14993                    }
14994                } catch (IOException ignored) {
14995                } finally {
14996                    IoUtils.closeQuietly(in);
14997                }
14998            }
14999
15000            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15001                BufferedReader in = null;
15002                String line = null;
15003                try {
15004                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15005                    while ((line = in.readLine()) != null) {
15006                        if (line.contains("ignored: updated version")) continue;
15007                        pw.print("msg,");
15008                        pw.println(line);
15009                    }
15010                } catch (IOException ignored) {
15011                } finally {
15012                    IoUtils.closeQuietly(in);
15013                }
15014            }
15015        }
15016    }
15017
15018    private String dumpDomainString(String packageName) {
15019        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15020        List<IntentFilter> filters = getAllIntentFilters(packageName);
15021
15022        ArraySet<String> result = new ArraySet<>();
15023        if (iviList.size() > 0) {
15024            for (IntentFilterVerificationInfo ivi : iviList) {
15025                for (String host : ivi.getDomains()) {
15026                    result.add(host);
15027                }
15028            }
15029        }
15030        if (filters != null && filters.size() > 0) {
15031            for (IntentFilter filter : filters) {
15032                if (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15033                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)) {
15034                    result.addAll(filter.getHostsList());
15035                }
15036            }
15037        }
15038
15039        StringBuilder sb = new StringBuilder(result.size() * 16);
15040        for (String domain : result) {
15041            if (sb.length() > 0) sb.append(" ");
15042            sb.append(domain);
15043        }
15044        return sb.toString();
15045    }
15046
15047    // ------- apps on sdcard specific code -------
15048    static final boolean DEBUG_SD_INSTALL = false;
15049
15050    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15051
15052    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15053
15054    private boolean mMediaMounted = false;
15055
15056    static String getEncryptKey() {
15057        try {
15058            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15059                    SD_ENCRYPTION_KEYSTORE_NAME);
15060            if (sdEncKey == null) {
15061                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15062                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15063                if (sdEncKey == null) {
15064                    Slog.e(TAG, "Failed to create encryption keys");
15065                    return null;
15066                }
15067            }
15068            return sdEncKey;
15069        } catch (NoSuchAlgorithmException nsae) {
15070            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15071            return null;
15072        } catch (IOException ioe) {
15073            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15074            return null;
15075        }
15076    }
15077
15078    /*
15079     * Update media status on PackageManager.
15080     */
15081    @Override
15082    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15083        int callingUid = Binder.getCallingUid();
15084        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15085            throw new SecurityException("Media status can only be updated by the system");
15086        }
15087        // reader; this apparently protects mMediaMounted, but should probably
15088        // be a different lock in that case.
15089        synchronized (mPackages) {
15090            Log.i(TAG, "Updating external media status from "
15091                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15092                    + (mediaStatus ? "mounted" : "unmounted"));
15093            if (DEBUG_SD_INSTALL)
15094                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15095                        + ", mMediaMounted=" + mMediaMounted);
15096            if (mediaStatus == mMediaMounted) {
15097                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15098                        : 0, -1);
15099                mHandler.sendMessage(msg);
15100                return;
15101            }
15102            mMediaMounted = mediaStatus;
15103        }
15104        // Queue up an async operation since the package installation may take a
15105        // little while.
15106        mHandler.post(new Runnable() {
15107            public void run() {
15108                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15109            }
15110        });
15111    }
15112
15113    /**
15114     * Called by MountService when the initial ASECs to scan are available.
15115     * Should block until all the ASEC containers are finished being scanned.
15116     */
15117    public void scanAvailableAsecs() {
15118        updateExternalMediaStatusInner(true, false, false);
15119        if (mShouldRestoreconData) {
15120            SELinuxMMAC.setRestoreconDone();
15121            mShouldRestoreconData = false;
15122        }
15123    }
15124
15125    /*
15126     * Collect information of applications on external media, map them against
15127     * existing containers and update information based on current mount status.
15128     * Please note that we always have to report status if reportStatus has been
15129     * set to true especially when unloading packages.
15130     */
15131    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15132            boolean externalStorage) {
15133        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15134        int[] uidArr = EmptyArray.INT;
15135
15136        final String[] list = PackageHelper.getSecureContainerList();
15137        if (ArrayUtils.isEmpty(list)) {
15138            Log.i(TAG, "No secure containers found");
15139        } else {
15140            // Process list of secure containers and categorize them
15141            // as active or stale based on their package internal state.
15142
15143            // reader
15144            synchronized (mPackages) {
15145                for (String cid : list) {
15146                    // Leave stages untouched for now; installer service owns them
15147                    if (PackageInstallerService.isStageName(cid)) continue;
15148
15149                    if (DEBUG_SD_INSTALL)
15150                        Log.i(TAG, "Processing container " + cid);
15151                    String pkgName = getAsecPackageName(cid);
15152                    if (pkgName == null) {
15153                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15154                        continue;
15155                    }
15156                    if (DEBUG_SD_INSTALL)
15157                        Log.i(TAG, "Looking for pkg : " + pkgName);
15158
15159                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15160                    if (ps == null) {
15161                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15162                        continue;
15163                    }
15164
15165                    /*
15166                     * Skip packages that are not external if we're unmounting
15167                     * external storage.
15168                     */
15169                    if (externalStorage && !isMounted && !isExternal(ps)) {
15170                        continue;
15171                    }
15172
15173                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15174                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15175                    // The package status is changed only if the code path
15176                    // matches between settings and the container id.
15177                    if (ps.codePathString != null
15178                            && ps.codePathString.startsWith(args.getCodePath())) {
15179                        if (DEBUG_SD_INSTALL) {
15180                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15181                                    + " at code path: " + ps.codePathString);
15182                        }
15183
15184                        // We do have a valid package installed on sdcard
15185                        processCids.put(args, ps.codePathString);
15186                        final int uid = ps.appId;
15187                        if (uid != -1) {
15188                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15189                        }
15190                    } else {
15191                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15192                                + ps.codePathString);
15193                    }
15194                }
15195            }
15196
15197            Arrays.sort(uidArr);
15198        }
15199
15200        // Process packages with valid entries.
15201        if (isMounted) {
15202            if (DEBUG_SD_INSTALL)
15203                Log.i(TAG, "Loading packages");
15204            loadMediaPackages(processCids, uidArr);
15205            startCleaningPackages();
15206            mInstallerService.onSecureContainersAvailable();
15207        } else {
15208            if (DEBUG_SD_INSTALL)
15209                Log.i(TAG, "Unloading packages");
15210            unloadMediaPackages(processCids, uidArr, reportStatus);
15211        }
15212    }
15213
15214    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15215            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15216        final int size = infos.size();
15217        final String[] packageNames = new String[size];
15218        final int[] packageUids = new int[size];
15219        for (int i = 0; i < size; i++) {
15220            final ApplicationInfo info = infos.get(i);
15221            packageNames[i] = info.packageName;
15222            packageUids[i] = info.uid;
15223        }
15224        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15225                finishedReceiver);
15226    }
15227
15228    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15229            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15230        sendResourcesChangedBroadcast(mediaStatus, replacing,
15231                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15232    }
15233
15234    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15235            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15236        int size = pkgList.length;
15237        if (size > 0) {
15238            // Send broadcasts here
15239            Bundle extras = new Bundle();
15240            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15241            if (uidArr != null) {
15242                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15243            }
15244            if (replacing) {
15245                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15246            }
15247            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15248                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15249            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15250        }
15251    }
15252
15253   /*
15254     * Look at potentially valid container ids from processCids If package
15255     * information doesn't match the one on record or package scanning fails,
15256     * the cid is added to list of removeCids. We currently don't delete stale
15257     * containers.
15258     */
15259    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15260        ArrayList<String> pkgList = new ArrayList<String>();
15261        Set<AsecInstallArgs> keys = processCids.keySet();
15262
15263        for (AsecInstallArgs args : keys) {
15264            String codePath = processCids.get(args);
15265            if (DEBUG_SD_INSTALL)
15266                Log.i(TAG, "Loading container : " + args.cid);
15267            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15268            try {
15269                // Make sure there are no container errors first.
15270                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15271                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15272                            + " when installing from sdcard");
15273                    continue;
15274                }
15275                // Check code path here.
15276                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15277                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15278                            + " does not match one in settings " + codePath);
15279                    continue;
15280                }
15281                // Parse package
15282                int parseFlags = mDefParseFlags;
15283                if (args.isExternalAsec()) {
15284                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15285                }
15286                if (args.isFwdLocked()) {
15287                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15288                }
15289
15290                synchronized (mInstallLock) {
15291                    PackageParser.Package pkg = null;
15292                    try {
15293                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15294                    } catch (PackageManagerException e) {
15295                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15296                    }
15297                    // Scan the package
15298                    if (pkg != null) {
15299                        /*
15300                         * TODO why is the lock being held? doPostInstall is
15301                         * called in other places without the lock. This needs
15302                         * to be straightened out.
15303                         */
15304                        // writer
15305                        synchronized (mPackages) {
15306                            retCode = PackageManager.INSTALL_SUCCEEDED;
15307                            pkgList.add(pkg.packageName);
15308                            // Post process args
15309                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15310                                    pkg.applicationInfo.uid);
15311                        }
15312                    } else {
15313                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15314                    }
15315                }
15316
15317            } finally {
15318                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15319                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15320                }
15321            }
15322        }
15323        // writer
15324        synchronized (mPackages) {
15325            // If the platform SDK has changed since the last time we booted,
15326            // we need to re-grant app permission to catch any new ones that
15327            // appear. This is really a hack, and means that apps can in some
15328            // cases get permissions that the user didn't initially explicitly
15329            // allow... it would be nice to have some better way to handle
15330            // this situation.
15331            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
15332            if (regrantPermissions)
15333                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
15334                        + mSdkVersion + "; regranting permissions for external storage");
15335            mSettings.mExternalSdkPlatform = mSdkVersion;
15336
15337            // Make sure group IDs have been assigned, and any permission
15338            // changes in other apps are accounted for
15339            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
15340                    | (regrantPermissions
15341                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
15342                            : 0));
15343
15344            mSettings.updateExternalDatabaseVersion();
15345
15346            // can downgrade to reader
15347            // Persist settings
15348            mSettings.writeLPr();
15349        }
15350        // Send a broadcast to let everyone know we are done processing
15351        if (pkgList.size() > 0) {
15352            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15353        }
15354    }
15355
15356   /*
15357     * Utility method to unload a list of specified containers
15358     */
15359    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15360        // Just unmount all valid containers.
15361        for (AsecInstallArgs arg : cidArgs) {
15362            synchronized (mInstallLock) {
15363                arg.doPostDeleteLI(false);
15364           }
15365       }
15366   }
15367
15368    /*
15369     * Unload packages mounted on external media. This involves deleting package
15370     * data from internal structures, sending broadcasts about diabled packages,
15371     * gc'ing to free up references, unmounting all secure containers
15372     * corresponding to packages on external media, and posting a
15373     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15374     * that we always have to post this message if status has been requested no
15375     * matter what.
15376     */
15377    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15378            final boolean reportStatus) {
15379        if (DEBUG_SD_INSTALL)
15380            Log.i(TAG, "unloading media packages");
15381        ArrayList<String> pkgList = new ArrayList<String>();
15382        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15383        final Set<AsecInstallArgs> keys = processCids.keySet();
15384        for (AsecInstallArgs args : keys) {
15385            String pkgName = args.getPackageName();
15386            if (DEBUG_SD_INSTALL)
15387                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15388            // Delete package internally
15389            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15390            synchronized (mInstallLock) {
15391                boolean res = deletePackageLI(pkgName, null, false, null, null,
15392                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15393                if (res) {
15394                    pkgList.add(pkgName);
15395                } else {
15396                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15397                    failedList.add(args);
15398                }
15399            }
15400        }
15401
15402        // reader
15403        synchronized (mPackages) {
15404            // We didn't update the settings after removing each package;
15405            // write them now for all packages.
15406            mSettings.writeLPr();
15407        }
15408
15409        // We have to absolutely send UPDATED_MEDIA_STATUS only
15410        // after confirming that all the receivers processed the ordered
15411        // broadcast when packages get disabled, force a gc to clean things up.
15412        // and unload all the containers.
15413        if (pkgList.size() > 0) {
15414            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15415                    new IIntentReceiver.Stub() {
15416                public void performReceive(Intent intent, int resultCode, String data,
15417                        Bundle extras, boolean ordered, boolean sticky,
15418                        int sendingUser) throws RemoteException {
15419                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15420                            reportStatus ? 1 : 0, 1, keys);
15421                    mHandler.sendMessage(msg);
15422                }
15423            });
15424        } else {
15425            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15426                    keys);
15427            mHandler.sendMessage(msg);
15428        }
15429    }
15430
15431    private void loadPrivatePackages(VolumeInfo vol) {
15432        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15433        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15434        synchronized (mInstallLock) {
15435        synchronized (mPackages) {
15436            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15437            for (PackageSetting ps : packages) {
15438                final PackageParser.Package pkg;
15439                try {
15440                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15441                    loaded.add(pkg.applicationInfo);
15442                } catch (PackageManagerException e) {
15443                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15444                }
15445            }
15446
15447            // TODO: regrant any permissions that changed based since original install
15448
15449            mSettings.writeLPr();
15450        }
15451        }
15452
15453        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15454        sendResourcesChangedBroadcast(true, false, loaded, null);
15455    }
15456
15457    private void unloadPrivatePackages(VolumeInfo vol) {
15458        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15459        synchronized (mInstallLock) {
15460        synchronized (mPackages) {
15461            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15462            for (PackageSetting ps : packages) {
15463                if (ps.pkg == null) continue;
15464
15465                final ApplicationInfo info = ps.pkg.applicationInfo;
15466                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15467                if (deletePackageLI(ps.name, null, false, null, null,
15468                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15469                    unloaded.add(info);
15470                } else {
15471                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15472                }
15473            }
15474
15475            mSettings.writeLPr();
15476        }
15477        }
15478
15479        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15480        sendResourcesChangedBroadcast(false, false, unloaded, null);
15481    }
15482
15483    /**
15484     * Examine all users present on given mounted volume, and destroy data
15485     * belonging to users that are no longer valid, or whose user ID has been
15486     * recycled.
15487     */
15488    private void reconcileUsers(String volumeUuid) {
15489        final File[] files = Environment.getDataUserDirectory(volumeUuid).listFiles();
15490        if (ArrayUtils.isEmpty(files)) {
15491            Slog.d(TAG, "No users found on " + volumeUuid);
15492            return;
15493        }
15494
15495        for (File file : files) {
15496            if (!file.isDirectory()) continue;
15497
15498            final int userId;
15499            final UserInfo info;
15500            try {
15501                userId = Integer.parseInt(file.getName());
15502                info = sUserManager.getUserInfo(userId);
15503            } catch (NumberFormatException e) {
15504                Slog.w(TAG, "Invalid user directory " + file);
15505                continue;
15506            }
15507
15508            boolean destroyUser = false;
15509            if (info == null) {
15510                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15511                        + " because no matching user was found");
15512                destroyUser = true;
15513            } else {
15514                try {
15515                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15516                } catch (IOException e) {
15517                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15518                            + " because we failed to enforce serial number: " + e);
15519                    destroyUser = true;
15520                }
15521            }
15522
15523            if (destroyUser) {
15524                synchronized (mInstallLock) {
15525                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15526                }
15527            }
15528        }
15529
15530        final UserManager um = mContext.getSystemService(UserManager.class);
15531        for (UserInfo user : um.getUsers()) {
15532            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15533            if (userDir.exists()) continue;
15534
15535            try {
15536                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15537                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15538            } catch (IOException e) {
15539                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15540            }
15541        }
15542    }
15543
15544    /**
15545     * Examine all apps present on given mounted volume, and destroy apps that
15546     * aren't expected, either due to uninstallation or reinstallation on
15547     * another volume.
15548     */
15549    private void reconcileApps(String volumeUuid) {
15550        final File[] files = Environment.getDataAppDirectory(volumeUuid).listFiles();
15551        if (ArrayUtils.isEmpty(files)) {
15552            Slog.d(TAG, "No apps found on " + volumeUuid);
15553            return;
15554        }
15555
15556        for (File file : files) {
15557            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15558                    && !PackageInstallerService.isStageName(file.getName());
15559            if (!isPackage) {
15560                // Ignore entries which are not packages
15561                continue;
15562            }
15563
15564            boolean destroyApp = false;
15565            String packageName = null;
15566            try {
15567                final PackageLite pkg = PackageParser.parsePackageLite(file,
15568                        PackageParser.PARSE_MUST_BE_APK);
15569                packageName = pkg.packageName;
15570
15571                synchronized (mPackages) {
15572                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15573                    if (ps == null) {
15574                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15575                                + volumeUuid + " because we found no install record");
15576                        destroyApp = true;
15577                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15578                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15579                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15580                        destroyApp = true;
15581                    }
15582                }
15583
15584            } catch (PackageParserException e) {
15585                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15586                destroyApp = true;
15587            }
15588
15589            if (destroyApp) {
15590                synchronized (mInstallLock) {
15591                    if (packageName != null) {
15592                        removeDataDirsLI(volumeUuid, packageName);
15593                    }
15594                    if (file.isDirectory()) {
15595                        mInstaller.rmPackageDir(file.getAbsolutePath());
15596                    } else {
15597                        file.delete();
15598                    }
15599                }
15600            }
15601        }
15602    }
15603
15604    private void unfreezePackage(String packageName) {
15605        synchronized (mPackages) {
15606            final PackageSetting ps = mSettings.mPackages.get(packageName);
15607            if (ps != null) {
15608                ps.frozen = false;
15609            }
15610        }
15611    }
15612
15613    @Override
15614    public int movePackage(final String packageName, final String volumeUuid) {
15615        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15616
15617        final int moveId = mNextMoveId.getAndIncrement();
15618        try {
15619            movePackageInternal(packageName, volumeUuid, moveId);
15620        } catch (PackageManagerException e) {
15621            Slog.w(TAG, "Failed to move " + packageName, e);
15622            mMoveCallbacks.notifyStatusChanged(moveId,
15623                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15624        }
15625        return moveId;
15626    }
15627
15628    private void movePackageInternal(final String packageName, final String volumeUuid,
15629            final int moveId) throws PackageManagerException {
15630        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15631        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15632        final PackageManager pm = mContext.getPackageManager();
15633
15634        final boolean currentAsec;
15635        final String currentVolumeUuid;
15636        final File codeFile;
15637        final String installerPackageName;
15638        final String packageAbiOverride;
15639        final int appId;
15640        final String seinfo;
15641        final String label;
15642
15643        // reader
15644        synchronized (mPackages) {
15645            final PackageParser.Package pkg = mPackages.get(packageName);
15646            final PackageSetting ps = mSettings.mPackages.get(packageName);
15647            if (pkg == null || ps == null) {
15648                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
15649            }
15650
15651            if (pkg.applicationInfo.isSystemApp()) {
15652                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
15653                        "Cannot move system application");
15654            }
15655
15656            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
15657                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15658                        "Package already moved to " + volumeUuid);
15659            }
15660
15661            final File probe = new File(pkg.codePath);
15662            final File probeOat = new File(probe, "oat");
15663            if (!probe.isDirectory() || !probeOat.isDirectory()) {
15664                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15665                        "Move only supported for modern cluster style installs");
15666            }
15667
15668            if (ps.frozen) {
15669                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
15670                        "Failed to move already frozen package");
15671            }
15672            ps.frozen = true;
15673
15674            currentAsec = pkg.applicationInfo.isForwardLocked()
15675                    || pkg.applicationInfo.isExternalAsec();
15676            currentVolumeUuid = ps.volumeUuid;
15677            codeFile = new File(pkg.codePath);
15678            installerPackageName = ps.installerPackageName;
15679            packageAbiOverride = ps.cpuAbiOverrideString;
15680            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15681            seinfo = pkg.applicationInfo.seinfo;
15682            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
15683        }
15684
15685        // Now that we're guarded by frozen state, kill app during move
15686        killApplication(packageName, appId, "move pkg");
15687
15688        final Bundle extras = new Bundle();
15689        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
15690        extras.putString(Intent.EXTRA_TITLE, label);
15691        mMoveCallbacks.notifyCreated(moveId, extras);
15692
15693        int installFlags;
15694        final boolean moveCompleteApp;
15695        final File measurePath;
15696
15697        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
15698            installFlags = INSTALL_INTERNAL;
15699            moveCompleteApp = !currentAsec;
15700            measurePath = Environment.getDataAppDirectory(volumeUuid);
15701        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
15702            installFlags = INSTALL_EXTERNAL;
15703            moveCompleteApp = false;
15704            measurePath = storage.getPrimaryPhysicalVolume().getPath();
15705        } else {
15706            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
15707            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
15708                    || !volume.isMountedWritable()) {
15709                unfreezePackage(packageName);
15710                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15711                        "Move location not mounted private volume");
15712            }
15713
15714            Preconditions.checkState(!currentAsec);
15715
15716            installFlags = INSTALL_INTERNAL;
15717            moveCompleteApp = true;
15718            measurePath = Environment.getDataAppDirectory(volumeUuid);
15719        }
15720
15721        final PackageStats stats = new PackageStats(null, -1);
15722        synchronized (mInstaller) {
15723            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
15724                unfreezePackage(packageName);
15725                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15726                        "Failed to measure package size");
15727            }
15728        }
15729
15730        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
15731                + stats.dataSize);
15732
15733        final long startFreeBytes = measurePath.getFreeSpace();
15734        final long sizeBytes;
15735        if (moveCompleteApp) {
15736            sizeBytes = stats.codeSize + stats.dataSize;
15737        } else {
15738            sizeBytes = stats.codeSize;
15739        }
15740
15741        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
15742            unfreezePackage(packageName);
15743            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
15744                    "Not enough free space to move");
15745        }
15746
15747        mMoveCallbacks.notifyStatusChanged(moveId, 10);
15748
15749        final CountDownLatch installedLatch = new CountDownLatch(1);
15750        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
15751            @Override
15752            public void onUserActionRequired(Intent intent) throws RemoteException {
15753                throw new IllegalStateException();
15754            }
15755
15756            @Override
15757            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
15758                    Bundle extras) throws RemoteException {
15759                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
15760                        + PackageManager.installStatusToString(returnCode, msg));
15761
15762                installedLatch.countDown();
15763
15764                // Regardless of success or failure of the move operation,
15765                // always unfreeze the package
15766                unfreezePackage(packageName);
15767
15768                final int status = PackageManager.installStatusToPublicStatus(returnCode);
15769                switch (status) {
15770                    case PackageInstaller.STATUS_SUCCESS:
15771                        mMoveCallbacks.notifyStatusChanged(moveId,
15772                                PackageManager.MOVE_SUCCEEDED);
15773                        break;
15774                    case PackageInstaller.STATUS_FAILURE_STORAGE:
15775                        mMoveCallbacks.notifyStatusChanged(moveId,
15776                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
15777                        break;
15778                    default:
15779                        mMoveCallbacks.notifyStatusChanged(moveId,
15780                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15781                        break;
15782                }
15783            }
15784        };
15785
15786        final MoveInfo move;
15787        if (moveCompleteApp) {
15788            // Kick off a thread to report progress estimates
15789            new Thread() {
15790                @Override
15791                public void run() {
15792                    while (true) {
15793                        try {
15794                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
15795                                break;
15796                            }
15797                        } catch (InterruptedException ignored) {
15798                        }
15799
15800                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
15801                        final int progress = 10 + (int) MathUtils.constrain(
15802                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
15803                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
15804                    }
15805                }
15806            }.start();
15807
15808            final String dataAppName = codeFile.getName();
15809            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
15810                    dataAppName, appId, seinfo);
15811        } else {
15812            move = null;
15813        }
15814
15815        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
15816
15817        final Message msg = mHandler.obtainMessage(INIT_COPY);
15818        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
15819        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
15820                installerPackageName, volumeUuid, null, user, packageAbiOverride);
15821        mHandler.sendMessage(msg);
15822    }
15823
15824    @Override
15825    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
15826        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15827
15828        final int realMoveId = mNextMoveId.getAndIncrement();
15829        final Bundle extras = new Bundle();
15830        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
15831        mMoveCallbacks.notifyCreated(realMoveId, extras);
15832
15833        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
15834            @Override
15835            public void onCreated(int moveId, Bundle extras) {
15836                // Ignored
15837            }
15838
15839            @Override
15840            public void onStatusChanged(int moveId, int status, long estMillis) {
15841                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
15842            }
15843        };
15844
15845        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15846        storage.setPrimaryStorageUuid(volumeUuid, callback);
15847        return realMoveId;
15848    }
15849
15850    @Override
15851    public int getMoveStatus(int moveId) {
15852        mContext.enforceCallingOrSelfPermission(
15853                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15854        return mMoveCallbacks.mLastStatus.get(moveId);
15855    }
15856
15857    @Override
15858    public void registerMoveCallback(IPackageMoveObserver callback) {
15859        mContext.enforceCallingOrSelfPermission(
15860                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15861        mMoveCallbacks.register(callback);
15862    }
15863
15864    @Override
15865    public void unregisterMoveCallback(IPackageMoveObserver callback) {
15866        mContext.enforceCallingOrSelfPermission(
15867                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
15868        mMoveCallbacks.unregister(callback);
15869    }
15870
15871    @Override
15872    public boolean setInstallLocation(int loc) {
15873        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
15874                null);
15875        if (getInstallLocation() == loc) {
15876            return true;
15877        }
15878        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
15879                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
15880            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
15881                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
15882            return true;
15883        }
15884        return false;
15885   }
15886
15887    @Override
15888    public int getInstallLocation() {
15889        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
15890                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
15891                PackageHelper.APP_INSTALL_AUTO);
15892    }
15893
15894    /** Called by UserManagerService */
15895    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
15896        mDirtyUsers.remove(userHandle);
15897        mSettings.removeUserLPw(userHandle);
15898        mPendingBroadcasts.remove(userHandle);
15899        if (mInstaller != null) {
15900            // Technically, we shouldn't be doing this with the package lock
15901            // held.  However, this is very rare, and there is already so much
15902            // other disk I/O going on, that we'll let it slide for now.
15903            final StorageManager storage = mContext.getSystemService(StorageManager.class);
15904            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
15905                final String volumeUuid = vol.getFsUuid();
15906                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
15907                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
15908            }
15909        }
15910        mUserNeedsBadging.delete(userHandle);
15911        removeUnusedPackagesLILPw(userManager, userHandle);
15912    }
15913
15914    /**
15915     * We're removing userHandle and would like to remove any downloaded packages
15916     * that are no longer in use by any other user.
15917     * @param userHandle the user being removed
15918     */
15919    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
15920        final boolean DEBUG_CLEAN_APKS = false;
15921        int [] users = userManager.getUserIdsLPr();
15922        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
15923        while (psit.hasNext()) {
15924            PackageSetting ps = psit.next();
15925            if (ps.pkg == null) {
15926                continue;
15927            }
15928            final String packageName = ps.pkg.packageName;
15929            // Skip over if system app
15930            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15931                continue;
15932            }
15933            if (DEBUG_CLEAN_APKS) {
15934                Slog.i(TAG, "Checking package " + packageName);
15935            }
15936            boolean keep = false;
15937            for (int i = 0; i < users.length; i++) {
15938                if (users[i] != userHandle && ps.getInstalled(users[i])) {
15939                    keep = true;
15940                    if (DEBUG_CLEAN_APKS) {
15941                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
15942                                + users[i]);
15943                    }
15944                    break;
15945                }
15946            }
15947            if (!keep) {
15948                if (DEBUG_CLEAN_APKS) {
15949                    Slog.i(TAG, "  Removing package " + packageName);
15950                }
15951                mHandler.post(new Runnable() {
15952                    public void run() {
15953                        deletePackageX(packageName, userHandle, 0);
15954                    } //end run
15955                });
15956            }
15957        }
15958    }
15959
15960    /** Called by UserManagerService */
15961    void createNewUserLILPw(int userHandle) {
15962        if (mInstaller != null) {
15963            mInstaller.createUserConfig(userHandle);
15964            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
15965            applyFactoryDefaultBrowserLPw(userHandle);
15966            primeDomainVerificationsLPw(userHandle);
15967        }
15968    }
15969
15970    void newUserCreated(final int userHandle) {
15971        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
15972    }
15973
15974    @Override
15975    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
15976        mContext.enforceCallingOrSelfPermission(
15977                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15978                "Only package verification agents can read the verifier device identity");
15979
15980        synchronized (mPackages) {
15981            return mSettings.getVerifierDeviceIdentityLPw();
15982        }
15983    }
15984
15985    @Override
15986    public void setPermissionEnforced(String permission, boolean enforced) {
15987        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
15988        if (READ_EXTERNAL_STORAGE.equals(permission)) {
15989            synchronized (mPackages) {
15990                if (mSettings.mReadExternalStorageEnforced == null
15991                        || mSettings.mReadExternalStorageEnforced != enforced) {
15992                    mSettings.mReadExternalStorageEnforced = enforced;
15993                    mSettings.writeLPr();
15994                }
15995            }
15996            // kill any non-foreground processes so we restart them and
15997            // grant/revoke the GID.
15998            final IActivityManager am = ActivityManagerNative.getDefault();
15999            if (am != null) {
16000                final long token = Binder.clearCallingIdentity();
16001                try {
16002                    am.killProcessesBelowForeground("setPermissionEnforcement");
16003                } catch (RemoteException e) {
16004                } finally {
16005                    Binder.restoreCallingIdentity(token);
16006                }
16007            }
16008        } else {
16009            throw new IllegalArgumentException("No selective enforcement for " + permission);
16010        }
16011    }
16012
16013    @Override
16014    @Deprecated
16015    public boolean isPermissionEnforced(String permission) {
16016        return true;
16017    }
16018
16019    @Override
16020    public boolean isStorageLow() {
16021        final long token = Binder.clearCallingIdentity();
16022        try {
16023            final DeviceStorageMonitorInternal
16024                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16025            if (dsm != null) {
16026                return dsm.isMemoryLow();
16027            } else {
16028                return false;
16029            }
16030        } finally {
16031            Binder.restoreCallingIdentity(token);
16032        }
16033    }
16034
16035    @Override
16036    public IPackageInstaller getPackageInstaller() {
16037        return mInstallerService;
16038    }
16039
16040    private boolean userNeedsBadging(int userId) {
16041        int index = mUserNeedsBadging.indexOfKey(userId);
16042        if (index < 0) {
16043            final UserInfo userInfo;
16044            final long token = Binder.clearCallingIdentity();
16045            try {
16046                userInfo = sUserManager.getUserInfo(userId);
16047            } finally {
16048                Binder.restoreCallingIdentity(token);
16049            }
16050            final boolean b;
16051            if (userInfo != null && userInfo.isManagedProfile()) {
16052                b = true;
16053            } else {
16054                b = false;
16055            }
16056            mUserNeedsBadging.put(userId, b);
16057            return b;
16058        }
16059        return mUserNeedsBadging.valueAt(index);
16060    }
16061
16062    @Override
16063    public KeySet getKeySetByAlias(String packageName, String alias) {
16064        if (packageName == null || alias == null) {
16065            return null;
16066        }
16067        synchronized(mPackages) {
16068            final PackageParser.Package pkg = mPackages.get(packageName);
16069            if (pkg == null) {
16070                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16071                throw new IllegalArgumentException("Unknown package: " + packageName);
16072            }
16073            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16074            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16075        }
16076    }
16077
16078    @Override
16079    public KeySet getSigningKeySet(String packageName) {
16080        if (packageName == null) {
16081            return null;
16082        }
16083        synchronized(mPackages) {
16084            final PackageParser.Package pkg = mPackages.get(packageName);
16085            if (pkg == null) {
16086                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16087                throw new IllegalArgumentException("Unknown package: " + packageName);
16088            }
16089            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16090                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16091                throw new SecurityException("May not access signing KeySet of other apps.");
16092            }
16093            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16094            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16095        }
16096    }
16097
16098    @Override
16099    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16100        if (packageName == null || ks == null) {
16101            return false;
16102        }
16103        synchronized(mPackages) {
16104            final PackageParser.Package pkg = mPackages.get(packageName);
16105            if (pkg == null) {
16106                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16107                throw new IllegalArgumentException("Unknown package: " + packageName);
16108            }
16109            IBinder ksh = ks.getToken();
16110            if (ksh instanceof KeySetHandle) {
16111                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16112                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16113            }
16114            return false;
16115        }
16116    }
16117
16118    @Override
16119    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16120        if (packageName == null || ks == null) {
16121            return false;
16122        }
16123        synchronized(mPackages) {
16124            final PackageParser.Package pkg = mPackages.get(packageName);
16125            if (pkg == null) {
16126                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16127                throw new IllegalArgumentException("Unknown package: " + packageName);
16128            }
16129            IBinder ksh = ks.getToken();
16130            if (ksh instanceof KeySetHandle) {
16131                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16132                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16133            }
16134            return false;
16135        }
16136    }
16137
16138    public void getUsageStatsIfNoPackageUsageInfo() {
16139        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16140            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16141            if (usm == null) {
16142                throw new IllegalStateException("UsageStatsManager must be initialized");
16143            }
16144            long now = System.currentTimeMillis();
16145            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16146            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16147                String packageName = entry.getKey();
16148                PackageParser.Package pkg = mPackages.get(packageName);
16149                if (pkg == null) {
16150                    continue;
16151                }
16152                UsageStats usage = entry.getValue();
16153                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16154                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16155            }
16156        }
16157    }
16158
16159    /**
16160     * Check and throw if the given before/after packages would be considered a
16161     * downgrade.
16162     */
16163    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16164            throws PackageManagerException {
16165        if (after.versionCode < before.mVersionCode) {
16166            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16167                    "Update version code " + after.versionCode + " is older than current "
16168                    + before.mVersionCode);
16169        } else if (after.versionCode == before.mVersionCode) {
16170            if (after.baseRevisionCode < before.baseRevisionCode) {
16171                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16172                        "Update base revision code " + after.baseRevisionCode
16173                        + " is older than current " + before.baseRevisionCode);
16174            }
16175
16176            if (!ArrayUtils.isEmpty(after.splitNames)) {
16177                for (int i = 0; i < after.splitNames.length; i++) {
16178                    final String splitName = after.splitNames[i];
16179                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16180                    if (j != -1) {
16181                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16182                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16183                                    "Update split " + splitName + " revision code "
16184                                    + after.splitRevisionCodes[i] + " is older than current "
16185                                    + before.splitRevisionCodes[j]);
16186                        }
16187                    }
16188                }
16189            }
16190        }
16191    }
16192
16193    private static class MoveCallbacks extends Handler {
16194        private static final int MSG_CREATED = 1;
16195        private static final int MSG_STATUS_CHANGED = 2;
16196
16197        private final RemoteCallbackList<IPackageMoveObserver>
16198                mCallbacks = new RemoteCallbackList<>();
16199
16200        private final SparseIntArray mLastStatus = new SparseIntArray();
16201
16202        public MoveCallbacks(Looper looper) {
16203            super(looper);
16204        }
16205
16206        public void register(IPackageMoveObserver callback) {
16207            mCallbacks.register(callback);
16208        }
16209
16210        public void unregister(IPackageMoveObserver callback) {
16211            mCallbacks.unregister(callback);
16212        }
16213
16214        @Override
16215        public void handleMessage(Message msg) {
16216            final SomeArgs args = (SomeArgs) msg.obj;
16217            final int n = mCallbacks.beginBroadcast();
16218            for (int i = 0; i < n; i++) {
16219                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16220                try {
16221                    invokeCallback(callback, msg.what, args);
16222                } catch (RemoteException ignored) {
16223                }
16224            }
16225            mCallbacks.finishBroadcast();
16226            args.recycle();
16227        }
16228
16229        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16230                throws RemoteException {
16231            switch (what) {
16232                case MSG_CREATED: {
16233                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16234                    break;
16235                }
16236                case MSG_STATUS_CHANGED: {
16237                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16238                    break;
16239                }
16240            }
16241        }
16242
16243        private void notifyCreated(int moveId, Bundle extras) {
16244            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16245
16246            final SomeArgs args = SomeArgs.obtain();
16247            args.argi1 = moveId;
16248            args.arg2 = extras;
16249            obtainMessage(MSG_CREATED, args).sendToTarget();
16250        }
16251
16252        private void notifyStatusChanged(int moveId, int status) {
16253            notifyStatusChanged(moveId, status, -1);
16254        }
16255
16256        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16257            Slog.v(TAG, "Move " + moveId + " status " + status);
16258
16259            final SomeArgs args = SomeArgs.obtain();
16260            args.argi1 = moveId;
16261            args.argi2 = status;
16262            args.arg3 = estMillis;
16263            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16264
16265            synchronized (mLastStatus) {
16266                mLastStatus.put(moveId, status);
16267            }
16268        }
16269    }
16270
16271    private final class OnPermissionChangeListeners extends Handler {
16272        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16273
16274        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16275                new RemoteCallbackList<>();
16276
16277        public OnPermissionChangeListeners(Looper looper) {
16278            super(looper);
16279        }
16280
16281        @Override
16282        public void handleMessage(Message msg) {
16283            switch (msg.what) {
16284                case MSG_ON_PERMISSIONS_CHANGED: {
16285                    final int uid = msg.arg1;
16286                    handleOnPermissionsChanged(uid);
16287                } break;
16288            }
16289        }
16290
16291        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16292            mPermissionListeners.register(listener);
16293
16294        }
16295
16296        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16297            mPermissionListeners.unregister(listener);
16298        }
16299
16300        public void onPermissionsChanged(int uid) {
16301            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16302                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16303            }
16304        }
16305
16306        private void handleOnPermissionsChanged(int uid) {
16307            final int count = mPermissionListeners.beginBroadcast();
16308            try {
16309                for (int i = 0; i < count; i++) {
16310                    IOnPermissionsChangeListener callback = mPermissionListeners
16311                            .getBroadcastItem(i);
16312                    try {
16313                        callback.onPermissionsChanged(uid);
16314                    } catch (RemoteException e) {
16315                        Log.e(TAG, "Permission listener is dead", e);
16316                    }
16317                }
16318            } finally {
16319                mPermissionListeners.finishBroadcast();
16320            }
16321        }
16322    }
16323
16324    private class PackageManagerInternalImpl extends PackageManagerInternal {
16325        @Override
16326        public void setLocationPackagesProvider(PackagesProvider provider) {
16327            synchronized (mPackages) {
16328                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16329            }
16330        }
16331
16332        @Override
16333        public void setImePackagesProvider(PackagesProvider provider) {
16334            synchronized (mPackages) {
16335                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16336            }
16337        }
16338
16339        @Override
16340        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16341            synchronized (mPackages) {
16342                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16343            }
16344        }
16345
16346        @Override
16347        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16348            synchronized (mPackages) {
16349                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16350            }
16351        }
16352
16353        @Override
16354        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16355            synchronized (mPackages) {
16356                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16357            }
16358        }
16359
16360        @Override
16361        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16362            synchronized (mPackages) {
16363                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderrLPw(provider);
16364            }
16365        }
16366
16367        @Override
16368        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16369            synchronized (mPackages) {
16370                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16371                        packageName, userId);
16372            }
16373        }
16374
16375        @Override
16376        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16377            synchronized (mPackages) {
16378                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16379                        packageName, userId);
16380            }
16381        }
16382    }
16383
16384    @Override
16385    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16386        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16387        synchronized (mPackages) {
16388            final long identity = Binder.clearCallingIdentity();
16389            try {
16390                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16391                        packageNames, userId);
16392            } finally {
16393                Binder.restoreCallingIdentity(identity);
16394            }
16395        }
16396    }
16397
16398    private static void enforceSystemOrPhoneCaller(String tag) {
16399        int callingUid = Binder.getCallingUid();
16400        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16401            throw new SecurityException(
16402                    "Cannot call " + tag + " from UID " + callingUid);
16403        }
16404    }
16405}
16406