PackageManagerService.java revision 6142f90b9f99c33c4f75c2057fb1db3bc77425cf
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.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
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_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
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.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
63import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
64import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
65import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
66import static android.content.pm.PackageManager.PERMISSION_DENIED;
67import static android.content.pm.PackageManager.PERMISSION_GRANTED;
68import static android.content.pm.PackageParser.isApkFile;
69import static android.os.Process.PACKAGE_INFO_GID;
70import static android.os.Process.SYSTEM_UID;
71import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
72import static android.system.OsConstants.O_CREAT;
73import static android.system.OsConstants.O_RDWR;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
76import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
77import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
78import static com.android.internal.util.ArrayUtils.appendInt;
79import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
80import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
83import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
84import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
88
89import android.Manifest;
90import android.app.ActivityManager;
91import android.app.ActivityManagerNative;
92import android.app.AppGlobals;
93import android.app.IActivityManager;
94import android.app.admin.IDevicePolicyManager;
95import android.app.backup.IBackupManager;
96import android.content.BroadcastReceiver;
97import android.content.ComponentName;
98import android.content.Context;
99import android.content.IIntentReceiver;
100import android.content.Intent;
101import android.content.IntentFilter;
102import android.content.IntentSender;
103import android.content.IntentSender.SendIntentException;
104import android.content.ServiceConnection;
105import android.content.pm.ActivityInfo;
106import android.content.pm.ApplicationInfo;
107import android.content.pm.AppsQueryHelper;
108import android.content.pm.EphemeralResolveInfo;
109import android.content.pm.EphemeralApplicationInfo;
110import android.content.pm.FeatureInfo;
111import android.content.pm.IOnPermissionsChangeListener;
112import android.content.pm.IPackageDataObserver;
113import android.content.pm.IPackageDeleteObserver;
114import android.content.pm.IPackageDeleteObserver2;
115import android.content.pm.IPackageInstallObserver2;
116import android.content.pm.IPackageInstaller;
117import android.content.pm.IPackageManager;
118import android.content.pm.IPackageMoveObserver;
119import android.content.pm.IPackageStatsObserver;
120import android.content.pm.InstrumentationInfo;
121import android.content.pm.IntentFilterVerificationInfo;
122import android.content.pm.KeySet;
123import android.content.pm.ManifestDigest;
124import android.content.pm.PackageCleanItem;
125import android.content.pm.PackageInfo;
126import android.content.pm.PackageInfoLite;
127import android.content.pm.PackageInstaller;
128import android.content.pm.PackageManager;
129import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
130import android.content.pm.PackageManagerInternal;
131import android.content.pm.PackageParser;
132import android.content.pm.PackageParser.ActivityIntentInfo;
133import android.content.pm.PackageParser.PackageLite;
134import android.content.pm.PackageParser.PackageParserException;
135import android.content.pm.PackageStats;
136import android.content.pm.PackageUserState;
137import android.content.pm.ParceledListSlice;
138import android.content.pm.PermissionGroupInfo;
139import android.content.pm.PermissionInfo;
140import android.content.pm.ProviderInfo;
141import android.content.pm.ResolveInfo;
142import android.content.pm.ServiceInfo;
143import android.content.pm.Signature;
144import android.content.pm.UserInfo;
145import android.content.pm.VerificationParams;
146import android.content.pm.VerifierDeviceIdentity;
147import android.content.pm.VerifierInfo;
148import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
149import android.content.res.Resources;
150import android.graphics.Bitmap;
151import android.hardware.display.DisplayManager;
152import android.net.Uri;
153import android.os.Debug;
154import android.os.Binder;
155import android.os.Build;
156import android.os.Bundle;
157import android.os.Environment;
158import android.os.Environment.UserEnvironment;
159import android.os.FileUtils;
160import android.os.Handler;
161import android.os.IBinder;
162import android.os.Looper;
163import android.os.Message;
164import android.os.Parcel;
165import android.os.ParcelFileDescriptor;
166import android.os.Process;
167import android.os.RemoteCallbackList;
168import android.os.RemoteException;
169import android.os.ResultReceiver;
170import android.os.SELinux;
171import android.os.ServiceManager;
172import android.os.SystemClock;
173import android.os.SystemProperties;
174import android.os.Trace;
175import android.os.UserHandle;
176import android.os.UserManager;
177import android.os.storage.IMountService;
178import android.os.storage.MountServiceInternal;
179import android.os.storage.StorageEventListener;
180import android.os.storage.StorageManager;
181import android.os.storage.VolumeInfo;
182import android.os.storage.VolumeRecord;
183import android.security.KeyStore;
184import android.security.SystemKeyStore;
185import android.system.ErrnoException;
186import android.system.Os;
187import android.system.StructStat;
188import android.text.TextUtils;
189import android.text.format.DateUtils;
190import android.util.ArrayMap;
191import android.util.ArraySet;
192import android.util.AtomicFile;
193import android.util.DisplayMetrics;
194import android.util.EventLog;
195import android.util.ExceptionUtils;
196import android.util.Log;
197import android.util.LogPrinter;
198import android.util.MathUtils;
199import android.util.PrintStreamPrinter;
200import android.util.Slog;
201import android.util.SparseArray;
202import android.util.SparseBooleanArray;
203import android.util.SparseIntArray;
204import android.util.Xml;
205import android.view.Display;
206
207import com.android.internal.annotations.GuardedBy;
208import dalvik.system.DexFile;
209import dalvik.system.VMRuntime;
210
211import libcore.io.IoUtils;
212import libcore.util.EmptyArray;
213
214import com.android.internal.R;
215import com.android.internal.annotations.GuardedBy;
216import com.android.internal.app.IMediaContainerService;
217import com.android.internal.app.ResolverActivity;
218import com.android.internal.content.NativeLibraryHelper;
219import com.android.internal.content.PackageHelper;
220import com.android.internal.os.IParcelFileDescriptorFactory;
221import com.android.internal.os.SomeArgs;
222import com.android.internal.os.Zygote;
223import com.android.internal.util.ArrayUtils;
224import com.android.internal.util.FastPrintWriter;
225import com.android.internal.util.FastXmlSerializer;
226import com.android.internal.util.IndentingPrintWriter;
227import com.android.internal.util.Preconditions;
228import com.android.server.EventLogTags;
229import com.android.server.FgThread;
230import com.android.server.IntentResolver;
231import com.android.server.LocalServices;
232import com.android.server.ServiceThread;
233import com.android.server.SystemConfig;
234import com.android.server.Watchdog;
235import com.android.server.pm.PermissionsState.PermissionState;
236import com.android.server.pm.Settings.DatabaseVersion;
237import com.android.server.pm.Settings.VersionInfo;
238import com.android.server.storage.DeviceStorageMonitorInternal;
239
240import org.xmlpull.v1.XmlPullParser;
241import org.xmlpull.v1.XmlPullParserException;
242import org.xmlpull.v1.XmlSerializer;
243
244import java.io.BufferedInputStream;
245import java.io.BufferedOutputStream;
246import java.io.BufferedReader;
247import java.io.ByteArrayInputStream;
248import java.io.ByteArrayOutputStream;
249import java.io.File;
250import java.io.FileDescriptor;
251import java.io.FileNotFoundException;
252import java.io.FileOutputStream;
253import java.io.FileReader;
254import java.io.FilenameFilter;
255import java.io.IOException;
256import java.io.InputStream;
257import java.io.PrintWriter;
258import java.nio.charset.StandardCharsets;
259import java.security.MessageDigest;
260import java.security.NoSuchAlgorithmException;
261import java.security.PublicKey;
262import java.security.cert.CertificateEncodingException;
263import java.security.cert.CertificateException;
264import java.text.SimpleDateFormat;
265import java.util.ArrayList;
266import java.util.Arrays;
267import java.util.Collection;
268import java.util.Collections;
269import java.util.Comparator;
270import java.util.Date;
271import java.util.Iterator;
272import java.util.List;
273import java.util.Map;
274import java.util.Objects;
275import java.util.Set;
276import java.util.concurrent.CountDownLatch;
277import java.util.concurrent.TimeUnit;
278import java.util.concurrent.atomic.AtomicBoolean;
279import java.util.concurrent.atomic.AtomicInteger;
280import java.util.concurrent.atomic.AtomicLong;
281
282/**
283 * Keep track of all those .apks everywhere.
284 *
285 * This is very central to the platform's security; please run the unit
286 * tests whenever making modifications here:
287 *
288runtest -c android.content.pm.PackageManagerTests frameworks-core
289 *
290 * {@hide}
291 */
292public class PackageManagerService extends IPackageManager.Stub {
293    static final String TAG = "PackageManager";
294    static final boolean DEBUG_SETTINGS = false;
295    static final boolean DEBUG_PREFERRED = false;
296    static final boolean DEBUG_UPGRADE = false;
297    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
298    private static final boolean DEBUG_BACKUP = false;
299    private static final boolean DEBUG_INSTALL = false;
300    private static final boolean DEBUG_REMOVE = false;
301    private static final boolean DEBUG_BROADCASTS = false;
302    private static final boolean DEBUG_SHOW_INFO = false;
303    private static final boolean DEBUG_PACKAGE_INFO = false;
304    private static final boolean DEBUG_INTENT_MATCHING = false;
305    private static final boolean DEBUG_PACKAGE_SCANNING = false;
306    private static final boolean DEBUG_VERIFY = false;
307    private static final boolean DEBUG_DEXOPT = false;
308    private static final boolean DEBUG_ABI_SELECTION = false;
309    private static final boolean DEBUG_EPHEMERAL = false;
310
311    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
312
313    private static final int RADIO_UID = Process.PHONE_UID;
314    private static final int LOG_UID = Process.LOG_UID;
315    private static final int NFC_UID = Process.NFC_UID;
316    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
317    private static final int SHELL_UID = Process.SHELL_UID;
318
319    // Cap the size of permission trees that 3rd party apps can define
320    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
321
322    // Suffix used during package installation when copying/moving
323    // package apks to install directory.
324    private static final String INSTALL_PACKAGE_SUFFIX = "-";
325
326    static final int SCAN_NO_DEX = 1<<1;
327    static final int SCAN_FORCE_DEX = 1<<2;
328    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
329    static final int SCAN_NEW_INSTALL = 1<<4;
330    static final int SCAN_NO_PATHS = 1<<5;
331    static final int SCAN_UPDATE_TIME = 1<<6;
332    static final int SCAN_DEFER_DEX = 1<<7;
333    static final int SCAN_BOOTING = 1<<8;
334    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
335    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
336    static final int SCAN_REPLACING = 1<<11;
337    static final int SCAN_REQUIRE_KNOWN = 1<<12;
338    static final int SCAN_MOVE = 1<<13;
339    static final int SCAN_INITIAL = 1<<14;
340
341    static final int REMOVE_CHATTY = 1<<16;
342
343    private static final int[] EMPTY_INT_ARRAY = new int[0];
344
345    /**
346     * Timeout (in milliseconds) after which the watchdog should declare that
347     * our handler thread is wedged.  The usual default for such things is one
348     * minute but we sometimes do very lengthy I/O operations on this thread,
349     * such as installing multi-gigabyte applications, so ours needs to be longer.
350     */
351    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
352
353    /**
354     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
355     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
356     * settings entry if available, otherwise we use the hardcoded default.  If it's been
357     * more than this long since the last fstrim, we force one during the boot sequence.
358     *
359     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
360     * one gets run at the next available charging+idle time.  This final mandatory
361     * no-fstrim check kicks in only of the other scheduling criteria is never met.
362     */
363    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
364
365    /**
366     * Whether verification is enabled by default.
367     */
368    private static final boolean DEFAULT_VERIFY_ENABLE = true;
369
370    /**
371     * The default maximum time to wait for the verification agent to return in
372     * milliseconds.
373     */
374    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
375
376    /**
377     * The default response for package verification timeout.
378     *
379     * This can be either PackageManager.VERIFICATION_ALLOW or
380     * PackageManager.VERIFICATION_REJECT.
381     */
382    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
383
384    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
385
386    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
387            DEFAULT_CONTAINER_PACKAGE,
388            "com.android.defcontainer.DefaultContainerService");
389
390    private static final String KILL_APP_REASON_GIDS_CHANGED =
391            "permission grant or revoke changed gids";
392
393    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
394            "permissions revoked";
395
396    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
397
398    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
399
400    /** Permission grant: not grant the permission. */
401    private static final int GRANT_DENIED = 1;
402
403    /** Permission grant: grant the permission as an install permission. */
404    private static final int GRANT_INSTALL = 2;
405
406    /** Permission grant: grant the permission as a runtime one. */
407    private static final int GRANT_RUNTIME = 3;
408
409    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
410    private static final int GRANT_UPGRADE = 4;
411
412    /** Canonical intent used to identify what counts as a "web browser" app */
413    private static final Intent sBrowserIntent;
414    static {
415        sBrowserIntent = new Intent();
416        sBrowserIntent.setAction(Intent.ACTION_VIEW);
417        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
418        sBrowserIntent.setData(Uri.parse("http:"));
419    }
420
421    final ServiceThread mHandlerThread;
422
423    final PackageHandler mHandler;
424
425    /**
426     * Messages for {@link #mHandler} that need to wait for system ready before
427     * being dispatched.
428     */
429    private ArrayList<Message> mPostSystemReadyMessages;
430
431    final int mSdkVersion = Build.VERSION.SDK_INT;
432
433    final Context mContext;
434    final boolean mFactoryTest;
435    final boolean mOnlyCore;
436    final DisplayMetrics mMetrics;
437    final int mDefParseFlags;
438    final String[] mSeparateProcesses;
439    final boolean mIsUpgrade;
440
441    /** The location for ASEC container files on internal storage. */
442    final String mAsecInternalPath;
443
444    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
445    // LOCK HELD.  Can be called with mInstallLock held.
446    @GuardedBy("mInstallLock")
447    final Installer mInstaller;
448
449    /** Directory where installed third-party apps stored */
450    final File mAppInstallDir;
451    final File mEphemeralInstallDir;
452
453    /**
454     * Directory to which applications installed internally have their
455     * 32 bit native libraries copied.
456     */
457    private File mAppLib32InstallDir;
458
459    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
460    // apps.
461    final File mDrmAppPrivateInstallDir;
462
463    // ----------------------------------------------------------------
464
465    // Lock for state used when installing and doing other long running
466    // operations.  Methods that must be called with this lock held have
467    // the suffix "LI".
468    final Object mInstallLock = new Object();
469
470    // ----------------------------------------------------------------
471
472    // Keys are String (package name), values are Package.  This also serves
473    // as the lock for the global state.  Methods that must be called with
474    // this lock held have the prefix "LP".
475    @GuardedBy("mPackages")
476    final ArrayMap<String, PackageParser.Package> mPackages =
477            new ArrayMap<String, PackageParser.Package>();
478
479    // Tracks available target package names -> overlay package paths.
480    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
481        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
482
483    /**
484     * Tracks new system packages [received in an OTA] that we expect to
485     * find updated user-installed versions. Keys are package name, values
486     * are package location.
487     */
488    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
489
490    /**
491     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
492     */
493    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
494    /**
495     * Whether or not system app permissions should be promoted from install to runtime.
496     */
497    boolean mPromoteSystemApps;
498
499    final Settings mSettings;
500    boolean mRestoredSettings;
501
502    // System configuration read by SystemConfig.
503    final int[] mGlobalGids;
504    final SparseArray<ArraySet<String>> mSystemPermissions;
505    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
506
507    // If mac_permissions.xml was found for seinfo labeling.
508    boolean mFoundPolicyFile;
509
510    // If a recursive restorecon of /data/data/<pkg> is needed.
511    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
512
513    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
514
515    public static final class SharedLibraryEntry {
516        public final String path;
517        public final String apk;
518
519        SharedLibraryEntry(String _path, String _apk) {
520            path = _path;
521            apk = _apk;
522        }
523    }
524
525    // Currently known shared libraries.
526    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
527            new ArrayMap<String, SharedLibraryEntry>();
528
529    // All available activities, for your resolving pleasure.
530    final ActivityIntentResolver mActivities =
531            new ActivityIntentResolver();
532
533    // All available receivers, for your resolving pleasure.
534    final ActivityIntentResolver mReceivers =
535            new ActivityIntentResolver();
536
537    // All available services, for your resolving pleasure.
538    final ServiceIntentResolver mServices = new ServiceIntentResolver();
539
540    // All available providers, for your resolving pleasure.
541    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
542
543    // Mapping from provider base names (first directory in content URI codePath)
544    // to the provider information.
545    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
546            new ArrayMap<String, PackageParser.Provider>();
547
548    // Mapping from instrumentation class names to info about them.
549    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
550            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
551
552    // Mapping from permission names to info about them.
553    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
554            new ArrayMap<String, PackageParser.PermissionGroup>();
555
556    // Packages whose data we have transfered into another package, thus
557    // should no longer exist.
558    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
559
560    // Broadcast actions that are only available to the system.
561    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
562
563    /** List of packages waiting for verification. */
564    final SparseArray<PackageVerificationState> mPendingVerification
565            = new SparseArray<PackageVerificationState>();
566
567    /** Set of packages associated with each app op permission. */
568    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
569
570    final PackageInstallerService mInstallerService;
571
572    private final PackageDexOptimizer mPackageDexOptimizer;
573
574    private AtomicInteger mNextMoveId = new AtomicInteger();
575    private final MoveCallbacks mMoveCallbacks;
576
577    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
578
579    // Cache of users who need badging.
580    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
581
582    /** Token for keys in mPendingVerification. */
583    private int mPendingVerificationToken = 0;
584
585    volatile boolean mSystemReady;
586    volatile boolean mSafeMode;
587    volatile boolean mHasSystemUidErrors;
588
589    ApplicationInfo mAndroidApplication;
590    final ActivityInfo mResolveActivity = new ActivityInfo();
591    final ResolveInfo mResolveInfo = new ResolveInfo();
592    ComponentName mResolveComponentName;
593    PackageParser.Package mPlatformPackage;
594    ComponentName mCustomResolverComponentName;
595
596    boolean mResolverReplaced = false;
597
598    private final ComponentName mIntentFilterVerifierComponent;
599    private int mIntentFilterVerificationToken = 0;
600
601    /** Component that knows whether or not an ephemeral application exists */
602    final ComponentName mEphemeralResolverComponent;
603    /** The service connection to the ephemeral resolver */
604    final EphemeralResolverConnection mEphemeralResolverConnection;
605
606    /** Component used to install ephemeral applications */
607    final ComponentName mEphemeralInstallerComponent;
608    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
609    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
610
611    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
612            = new SparseArray<IntentFilterVerificationState>();
613
614    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
615            new DefaultPermissionGrantPolicy(this);
616
617    // List of packages names to keep cached, even if they are uninstalled for all users
618    private List<String> mKeepUninstalledPackages;
619
620    private static class IFVerificationParams {
621        PackageParser.Package pkg;
622        boolean replacing;
623        int userId;
624        int verifierUid;
625
626        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
627                int _userId, int _verifierUid) {
628            pkg = _pkg;
629            replacing = _replacing;
630            userId = _userId;
631            replacing = _replacing;
632            verifierUid = _verifierUid;
633        }
634    }
635
636    private interface IntentFilterVerifier<T extends IntentFilter> {
637        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
638                                               T filter, String packageName);
639        void startVerifications(int userId);
640        void receiveVerificationResponse(int verificationId);
641    }
642
643    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
644        private Context mContext;
645        private ComponentName mIntentFilterVerifierComponent;
646        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
647
648        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
649            mContext = context;
650            mIntentFilterVerifierComponent = verifierComponent;
651        }
652
653        private String getDefaultScheme() {
654            return IntentFilter.SCHEME_HTTPS;
655        }
656
657        @Override
658        public void startVerifications(int userId) {
659            // Launch verifications requests
660            int count = mCurrentIntentFilterVerifications.size();
661            for (int n=0; n<count; n++) {
662                int verificationId = mCurrentIntentFilterVerifications.get(n);
663                final IntentFilterVerificationState ivs =
664                        mIntentFilterVerificationStates.get(verificationId);
665
666                String packageName = ivs.getPackageName();
667
668                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
669                final int filterCount = filters.size();
670                ArraySet<String> domainsSet = new ArraySet<>();
671                for (int m=0; m<filterCount; m++) {
672                    PackageParser.ActivityIntentInfo filter = filters.get(m);
673                    domainsSet.addAll(filter.getHostsList());
674                }
675                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
676                synchronized (mPackages) {
677                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
678                            packageName, domainsList) != null) {
679                        scheduleWriteSettingsLocked();
680                    }
681                }
682                sendVerificationRequest(userId, verificationId, ivs);
683            }
684            mCurrentIntentFilterVerifications.clear();
685        }
686
687        private void sendVerificationRequest(int userId, int verificationId,
688                IntentFilterVerificationState ivs) {
689
690            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
691            verificationIntent.putExtra(
692                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
693                    verificationId);
694            verificationIntent.putExtra(
695                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
696                    getDefaultScheme());
697            verificationIntent.putExtra(
698                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
699                    ivs.getHostsString());
700            verificationIntent.putExtra(
701                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
702                    ivs.getPackageName());
703            verificationIntent.setComponent(mIntentFilterVerifierComponent);
704            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
705
706            UserHandle user = new UserHandle(userId);
707            mContext.sendBroadcastAsUser(verificationIntent, user);
708            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
709                    "Sending IntentFilter verification broadcast");
710        }
711
712        public void receiveVerificationResponse(int verificationId) {
713            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
714
715            final boolean verified = ivs.isVerified();
716
717            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
718            final int count = filters.size();
719            if (DEBUG_DOMAIN_VERIFICATION) {
720                Slog.i(TAG, "Received verification response " + verificationId
721                        + " for " + count + " filters, verified=" + verified);
722            }
723            for (int n=0; n<count; n++) {
724                PackageParser.ActivityIntentInfo filter = filters.get(n);
725                filter.setVerified(verified);
726
727                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
728                        + " verified with result:" + verified + " and hosts:"
729                        + ivs.getHostsString());
730            }
731
732            mIntentFilterVerificationStates.remove(verificationId);
733
734            final String packageName = ivs.getPackageName();
735            IntentFilterVerificationInfo ivi = null;
736
737            synchronized (mPackages) {
738                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
739            }
740            if (ivi == null) {
741                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
742                        + verificationId + " packageName:" + packageName);
743                return;
744            }
745            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
746                    "Updating IntentFilterVerificationInfo for package " + packageName
747                            +" verificationId:" + verificationId);
748
749            synchronized (mPackages) {
750                if (verified) {
751                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
752                } else {
753                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
754                }
755                scheduleWriteSettingsLocked();
756
757                final int userId = ivs.getUserId();
758                if (userId != UserHandle.USER_ALL) {
759                    final int userStatus =
760                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
761
762                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
763                    boolean needUpdate = false;
764
765                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
766                    // already been set by the User thru the Disambiguation dialog
767                    switch (userStatus) {
768                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
769                            if (verified) {
770                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
771                            } else {
772                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
773                            }
774                            needUpdate = true;
775                            break;
776
777                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
778                            if (verified) {
779                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
780                                needUpdate = true;
781                            }
782                            break;
783
784                        default:
785                            // Nothing to do
786                    }
787
788                    if (needUpdate) {
789                        mSettings.updateIntentFilterVerificationStatusLPw(
790                                packageName, updatedStatus, userId);
791                        scheduleWritePackageRestrictionsLocked(userId);
792                    }
793                }
794            }
795        }
796
797        @Override
798        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
799                    ActivityIntentInfo filter, String packageName) {
800            if (!hasValidDomains(filter)) {
801                return false;
802            }
803            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
804            if (ivs == null) {
805                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
806                        packageName);
807            }
808            if (DEBUG_DOMAIN_VERIFICATION) {
809                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
810            }
811            ivs.addFilter(filter);
812            return true;
813        }
814
815        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
816                int userId, int verificationId, String packageName) {
817            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
818                    verifierUid, userId, packageName);
819            ivs.setPendingState();
820            synchronized (mPackages) {
821                mIntentFilterVerificationStates.append(verificationId, ivs);
822                mCurrentIntentFilterVerifications.add(verificationId);
823            }
824            return ivs;
825        }
826    }
827
828    private static boolean hasValidDomains(ActivityIntentInfo filter) {
829        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
830                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
831                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
832    }
833
834    private IntentFilterVerifier mIntentFilterVerifier;
835
836    // Set of pending broadcasts for aggregating enable/disable of components.
837    static class PendingPackageBroadcasts {
838        // for each user id, a map of <package name -> components within that package>
839        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
840
841        public PendingPackageBroadcasts() {
842            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
843        }
844
845        public ArrayList<String> get(int userId, String packageName) {
846            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
847            return packages.get(packageName);
848        }
849
850        public void put(int userId, String packageName, ArrayList<String> components) {
851            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
852            packages.put(packageName, components);
853        }
854
855        public void remove(int userId, String packageName) {
856            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
857            if (packages != null) {
858                packages.remove(packageName);
859            }
860        }
861
862        public void remove(int userId) {
863            mUidMap.remove(userId);
864        }
865
866        public int userIdCount() {
867            return mUidMap.size();
868        }
869
870        public int userIdAt(int n) {
871            return mUidMap.keyAt(n);
872        }
873
874        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
875            return mUidMap.get(userId);
876        }
877
878        public int size() {
879            // total number of pending broadcast entries across all userIds
880            int num = 0;
881            for (int i = 0; i< mUidMap.size(); i++) {
882                num += mUidMap.valueAt(i).size();
883            }
884            return num;
885        }
886
887        public void clear() {
888            mUidMap.clear();
889        }
890
891        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
892            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
893            if (map == null) {
894                map = new ArrayMap<String, ArrayList<String>>();
895                mUidMap.put(userId, map);
896            }
897            return map;
898        }
899    }
900    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
901
902    // Service Connection to remote media container service to copy
903    // package uri's from external media onto secure containers
904    // or internal storage.
905    private IMediaContainerService mContainerService = null;
906
907    static final int SEND_PENDING_BROADCAST = 1;
908    static final int MCS_BOUND = 3;
909    static final int END_COPY = 4;
910    static final int INIT_COPY = 5;
911    static final int MCS_UNBIND = 6;
912    static final int START_CLEANING_PACKAGE = 7;
913    static final int FIND_INSTALL_LOC = 8;
914    static final int POST_INSTALL = 9;
915    static final int MCS_RECONNECT = 10;
916    static final int MCS_GIVE_UP = 11;
917    static final int UPDATED_MEDIA_STATUS = 12;
918    static final int WRITE_SETTINGS = 13;
919    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
920    static final int PACKAGE_VERIFIED = 15;
921    static final int CHECK_PENDING_VERIFICATION = 16;
922    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
923    static final int INTENT_FILTER_VERIFIED = 18;
924
925    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
926
927    // Delay time in millisecs
928    static final int BROADCAST_DELAY = 10 * 1000;
929
930    static UserManagerService sUserManager;
931
932    // Stores a list of users whose package restrictions file needs to be updated
933    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
934
935    final private DefaultContainerConnection mDefContainerConn =
936            new DefaultContainerConnection();
937    class DefaultContainerConnection implements ServiceConnection {
938        public void onServiceConnected(ComponentName name, IBinder service) {
939            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
940            IMediaContainerService imcs =
941                IMediaContainerService.Stub.asInterface(service);
942            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
943        }
944
945        public void onServiceDisconnected(ComponentName name) {
946            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
947        }
948    }
949
950    // Recordkeeping of restore-after-install operations that are currently in flight
951    // between the Package Manager and the Backup Manager
952    static class PostInstallData {
953        public InstallArgs args;
954        public PackageInstalledInfo res;
955
956        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
957            args = _a;
958            res = _r;
959        }
960    }
961
962    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
963    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
964
965    // XML tags for backup/restore of various bits of state
966    private static final String TAG_PREFERRED_BACKUP = "pa";
967    private static final String TAG_DEFAULT_APPS = "da";
968    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
969
970    final String mRequiredVerifierPackage;
971    final String mRequiredInstallerPackage;
972
973    private final PackageUsage mPackageUsage = new PackageUsage();
974
975    private class PackageUsage {
976        private static final int WRITE_INTERVAL
977            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
978
979        private final Object mFileLock = new Object();
980        private final AtomicLong mLastWritten = new AtomicLong(0);
981        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
982
983        private boolean mIsHistoricalPackageUsageAvailable = true;
984
985        boolean isHistoricalPackageUsageAvailable() {
986            return mIsHistoricalPackageUsageAvailable;
987        }
988
989        void write(boolean force) {
990            if (force) {
991                writeInternal();
992                return;
993            }
994            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
995                && !DEBUG_DEXOPT) {
996                return;
997            }
998            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
999                new Thread("PackageUsage_DiskWriter") {
1000                    @Override
1001                    public void run() {
1002                        try {
1003                            writeInternal();
1004                        } finally {
1005                            mBackgroundWriteRunning.set(false);
1006                        }
1007                    }
1008                }.start();
1009            }
1010        }
1011
1012        private void writeInternal() {
1013            synchronized (mPackages) {
1014                synchronized (mFileLock) {
1015                    AtomicFile file = getFile();
1016                    FileOutputStream f = null;
1017                    try {
1018                        f = file.startWrite();
1019                        BufferedOutputStream out = new BufferedOutputStream(f);
1020                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1021                        StringBuilder sb = new StringBuilder();
1022                        for (PackageParser.Package pkg : mPackages.values()) {
1023                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1024                                continue;
1025                            }
1026                            sb.setLength(0);
1027                            sb.append(pkg.packageName);
1028                            sb.append(' ');
1029                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1030                            sb.append('\n');
1031                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1032                        }
1033                        out.flush();
1034                        file.finishWrite(f);
1035                    } catch (IOException e) {
1036                        if (f != null) {
1037                            file.failWrite(f);
1038                        }
1039                        Log.e(TAG, "Failed to write package usage times", e);
1040                    }
1041                }
1042            }
1043            mLastWritten.set(SystemClock.elapsedRealtime());
1044        }
1045
1046        void readLP() {
1047            synchronized (mFileLock) {
1048                AtomicFile file = getFile();
1049                BufferedInputStream in = null;
1050                try {
1051                    in = new BufferedInputStream(file.openRead());
1052                    StringBuffer sb = new StringBuffer();
1053                    while (true) {
1054                        String packageName = readToken(in, sb, ' ');
1055                        if (packageName == null) {
1056                            break;
1057                        }
1058                        String timeInMillisString = readToken(in, sb, '\n');
1059                        if (timeInMillisString == null) {
1060                            throw new IOException("Failed to find last usage time for package "
1061                                                  + packageName);
1062                        }
1063                        PackageParser.Package pkg = mPackages.get(packageName);
1064                        if (pkg == null) {
1065                            continue;
1066                        }
1067                        long timeInMillis;
1068                        try {
1069                            timeInMillis = Long.parseLong(timeInMillisString);
1070                        } catch (NumberFormatException e) {
1071                            throw new IOException("Failed to parse " + timeInMillisString
1072                                                  + " as a long.", e);
1073                        }
1074                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1075                    }
1076                } catch (FileNotFoundException expected) {
1077                    mIsHistoricalPackageUsageAvailable = false;
1078                } catch (IOException e) {
1079                    Log.w(TAG, "Failed to read package usage times", e);
1080                } finally {
1081                    IoUtils.closeQuietly(in);
1082                }
1083            }
1084            mLastWritten.set(SystemClock.elapsedRealtime());
1085        }
1086
1087        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1088                throws IOException {
1089            sb.setLength(0);
1090            while (true) {
1091                int ch = in.read();
1092                if (ch == -1) {
1093                    if (sb.length() == 0) {
1094                        return null;
1095                    }
1096                    throw new IOException("Unexpected EOF");
1097                }
1098                if (ch == endOfToken) {
1099                    return sb.toString();
1100                }
1101                sb.append((char)ch);
1102            }
1103        }
1104
1105        private AtomicFile getFile() {
1106            File dataDir = Environment.getDataDirectory();
1107            File systemDir = new File(dataDir, "system");
1108            File fname = new File(systemDir, "package-usage.list");
1109            return new AtomicFile(fname);
1110        }
1111    }
1112
1113    class PackageHandler extends Handler {
1114        private boolean mBound = false;
1115        final ArrayList<HandlerParams> mPendingInstalls =
1116            new ArrayList<HandlerParams>();
1117
1118        private boolean connectToService() {
1119            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1120                    " DefaultContainerService");
1121            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1124                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1125                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126                mBound = true;
1127                return true;
1128            }
1129            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1130            return false;
1131        }
1132
1133        private void disconnectService() {
1134            mContainerService = null;
1135            mBound = false;
1136            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1137            mContext.unbindService(mDefContainerConn);
1138            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1139        }
1140
1141        PackageHandler(Looper looper) {
1142            super(looper);
1143        }
1144
1145        public void handleMessage(Message msg) {
1146            try {
1147                doHandleMessage(msg);
1148            } finally {
1149                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1150            }
1151        }
1152
1153        void doHandleMessage(Message msg) {
1154            switch (msg.what) {
1155                case INIT_COPY: {
1156                    HandlerParams params = (HandlerParams) msg.obj;
1157                    int idx = mPendingInstalls.size();
1158                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1159                    // If a bind was already initiated we dont really
1160                    // need to do anything. The pending install
1161                    // will be processed later on.
1162                    if (!mBound) {
1163                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1164                                System.identityHashCode(mHandler));
1165                        // If this is the only one pending we might
1166                        // have to bind to the service again.
1167                        if (!connectToService()) {
1168                            Slog.e(TAG, "Failed to bind to media container service");
1169                            params.serviceError();
1170                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1171                                    System.identityHashCode(mHandler));
1172                            if (params.traceMethod != null) {
1173                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1174                                        params.traceCookie);
1175                            }
1176                            return;
1177                        } else {
1178                            // Once we bind to the service, the first
1179                            // pending request will be processed.
1180                            mPendingInstalls.add(idx, params);
1181                        }
1182                    } else {
1183                        mPendingInstalls.add(idx, params);
1184                        // Already bound to the service. Just make
1185                        // sure we trigger off processing the first request.
1186                        if (idx == 0) {
1187                            mHandler.sendEmptyMessage(MCS_BOUND);
1188                        }
1189                    }
1190                    break;
1191                }
1192                case MCS_BOUND: {
1193                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1194                    if (msg.obj != null) {
1195                        mContainerService = (IMediaContainerService) msg.obj;
1196                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1197                                System.identityHashCode(mHandler));
1198                    }
1199                    if (mContainerService == null) {
1200                        if (!mBound) {
1201                            // Something seriously wrong since we are not bound and we are not
1202                            // waiting for connection. Bail out.
1203                            Slog.e(TAG, "Cannot bind to media container service");
1204                            for (HandlerParams params : mPendingInstalls) {
1205                                // Indicate service bind error
1206                                params.serviceError();
1207                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1208                                        System.identityHashCode(params));
1209                                if (params.traceMethod != null) {
1210                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1211                                            params.traceMethod, params.traceCookie);
1212                                }
1213                                return;
1214                            }
1215                            mPendingInstalls.clear();
1216                        } else {
1217                            Slog.w(TAG, "Waiting to connect to media container service");
1218                        }
1219                    } else if (mPendingInstalls.size() > 0) {
1220                        HandlerParams params = mPendingInstalls.get(0);
1221                        if (params != null) {
1222                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1223                                    System.identityHashCode(params));
1224                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1225                            if (params.startCopy()) {
1226                                // We are done...  look for more work or to
1227                                // go idle.
1228                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1229                                        "Checking for more work or unbind...");
1230                                // Delete pending install
1231                                if (mPendingInstalls.size() > 0) {
1232                                    mPendingInstalls.remove(0);
1233                                }
1234                                if (mPendingInstalls.size() == 0) {
1235                                    if (mBound) {
1236                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1237                                                "Posting delayed MCS_UNBIND");
1238                                        removeMessages(MCS_UNBIND);
1239                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1240                                        // Unbind after a little delay, to avoid
1241                                        // continual thrashing.
1242                                        sendMessageDelayed(ubmsg, 10000);
1243                                    }
1244                                } else {
1245                                    // There are more pending requests in queue.
1246                                    // Just post MCS_BOUND message to trigger processing
1247                                    // of next pending install.
1248                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1249                                            "Posting MCS_BOUND for next work");
1250                                    mHandler.sendEmptyMessage(MCS_BOUND);
1251                                }
1252                            }
1253                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1254                        }
1255                    } else {
1256                        // Should never happen ideally.
1257                        Slog.w(TAG, "Empty queue");
1258                    }
1259                    break;
1260                }
1261                case MCS_RECONNECT: {
1262                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1263                    if (mPendingInstalls.size() > 0) {
1264                        if (mBound) {
1265                            disconnectService();
1266                        }
1267                        if (!connectToService()) {
1268                            Slog.e(TAG, "Failed to bind to media container service");
1269                            for (HandlerParams params : mPendingInstalls) {
1270                                // Indicate service bind error
1271                                params.serviceError();
1272                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1273                                        System.identityHashCode(params));
1274                            }
1275                            mPendingInstalls.clear();
1276                        }
1277                    }
1278                    break;
1279                }
1280                case MCS_UNBIND: {
1281                    // If there is no actual work left, then time to unbind.
1282                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1283
1284                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1285                        if (mBound) {
1286                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1287
1288                            disconnectService();
1289                        }
1290                    } else if (mPendingInstalls.size() > 0) {
1291                        // There are more pending requests in queue.
1292                        // Just post MCS_BOUND message to trigger processing
1293                        // of next pending install.
1294                        mHandler.sendEmptyMessage(MCS_BOUND);
1295                    }
1296
1297                    break;
1298                }
1299                case MCS_GIVE_UP: {
1300                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1301                    HandlerParams params = mPendingInstalls.remove(0);
1302                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1303                            System.identityHashCode(params));
1304                    break;
1305                }
1306                case SEND_PENDING_BROADCAST: {
1307                    String packages[];
1308                    ArrayList<String> components[];
1309                    int size = 0;
1310                    int uids[];
1311                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1312                    synchronized (mPackages) {
1313                        if (mPendingBroadcasts == null) {
1314                            return;
1315                        }
1316                        size = mPendingBroadcasts.size();
1317                        if (size <= 0) {
1318                            // Nothing to be done. Just return
1319                            return;
1320                        }
1321                        packages = new String[size];
1322                        components = new ArrayList[size];
1323                        uids = new int[size];
1324                        int i = 0;  // filling out the above arrays
1325
1326                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1327                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1328                            Iterator<Map.Entry<String, ArrayList<String>>> it
1329                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1330                                            .entrySet().iterator();
1331                            while (it.hasNext() && i < size) {
1332                                Map.Entry<String, ArrayList<String>> ent = it.next();
1333                                packages[i] = ent.getKey();
1334                                components[i] = ent.getValue();
1335                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1336                                uids[i] = (ps != null)
1337                                        ? UserHandle.getUid(packageUserId, ps.appId)
1338                                        : -1;
1339                                i++;
1340                            }
1341                        }
1342                        size = i;
1343                        mPendingBroadcasts.clear();
1344                    }
1345                    // Send broadcasts
1346                    for (int i = 0; i < size; i++) {
1347                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1348                    }
1349                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1350                    break;
1351                }
1352                case START_CLEANING_PACKAGE: {
1353                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1354                    final String packageName = (String)msg.obj;
1355                    final int userId = msg.arg1;
1356                    final boolean andCode = msg.arg2 != 0;
1357                    synchronized (mPackages) {
1358                        if (userId == UserHandle.USER_ALL) {
1359                            int[] users = sUserManager.getUserIds();
1360                            for (int user : users) {
1361                                mSettings.addPackageToCleanLPw(
1362                                        new PackageCleanItem(user, packageName, andCode));
1363                            }
1364                        } else {
1365                            mSettings.addPackageToCleanLPw(
1366                                    new PackageCleanItem(userId, packageName, andCode));
1367                        }
1368                    }
1369                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1370                    startCleaningPackages();
1371                } break;
1372                case POST_INSTALL: {
1373                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1374
1375                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1376                    mRunningInstalls.delete(msg.arg1);
1377                    boolean deleteOld = false;
1378
1379                    if (data != null) {
1380                        InstallArgs args = data.args;
1381                        PackageInstalledInfo res = data.res;
1382
1383                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1384                            final String packageName = res.pkg.applicationInfo.packageName;
1385                            res.removedInfo.sendBroadcast(false, true, false);
1386                            Bundle extras = new Bundle(1);
1387                            extras.putInt(Intent.EXTRA_UID, res.uid);
1388
1389                            // Now that we successfully installed the package, grant runtime
1390                            // permissions if requested before broadcasting the install.
1391                            if ((args.installFlags
1392                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1393                                    && res.pkg.applicationInfo.targetSdkVersion
1394                                            >= Build.VERSION_CODES.M) {
1395                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1396                                        args.installGrantPermissions);
1397                            }
1398
1399                            synchronized (mPackages) {
1400                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1401                            }
1402
1403                            // Determine the set of users who are adding this
1404                            // package for the first time vs. those who are seeing
1405                            // an update.
1406                            int[] firstUsers;
1407                            int[] updateUsers = new int[0];
1408                            if (res.origUsers == null || res.origUsers.length == 0) {
1409                                firstUsers = res.newUsers;
1410                            } else {
1411                                firstUsers = new int[0];
1412                                for (int i=0; i<res.newUsers.length; i++) {
1413                                    int user = res.newUsers[i];
1414                                    boolean isNew = true;
1415                                    for (int j=0; j<res.origUsers.length; j++) {
1416                                        if (res.origUsers[j] == user) {
1417                                            isNew = false;
1418                                            break;
1419                                        }
1420                                    }
1421                                    if (isNew) {
1422                                        int[] newFirst = new int[firstUsers.length+1];
1423                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1424                                                firstUsers.length);
1425                                        newFirst[firstUsers.length] = user;
1426                                        firstUsers = newFirst;
1427                                    } else {
1428                                        int[] newUpdate = new int[updateUsers.length+1];
1429                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1430                                                updateUsers.length);
1431                                        newUpdate[updateUsers.length] = user;
1432                                        updateUsers = newUpdate;
1433                                    }
1434                                }
1435                            }
1436                            // don't broadcast for ephemeral installs/updates
1437                            final boolean isEphemeral = isEphemeral(res.pkg);
1438                            if (!isEphemeral) {
1439                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1440                                        extras, 0 /*flags*/, null /*targetPackage*/,
1441                                        null /*finishedReceiver*/, firstUsers);
1442                            }
1443                            final boolean update = res.removedInfo.removedPackage != null;
1444                            if (update) {
1445                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1446                            }
1447                            if (!isEphemeral) {
1448                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1449                                        extras, 0 /*flags*/, null /*targetPackage*/,
1450                                        null /*finishedReceiver*/, updateUsers);
1451                            }
1452                            if (update) {
1453                                if (!isEphemeral) {
1454                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1455                                            packageName, extras, 0 /*flags*/,
1456                                            null /*targetPackage*/, null /*finishedReceiver*/,
1457                                            updateUsers);
1458                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1459                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1460                                            packageName /*targetPackage*/,
1461                                            null /*finishedReceiver*/, updateUsers);
1462                                }
1463
1464                                // treat asec-hosted packages like removable media on upgrade
1465                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1466                                    if (DEBUG_INSTALL) {
1467                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1468                                                + " is ASEC-hosted -> AVAILABLE");
1469                                    }
1470                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1471                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1472                                    pkgList.add(packageName);
1473                                    sendResourcesChangedBroadcast(true, true,
1474                                            pkgList,uidArray, null);
1475                                }
1476                            }
1477                            if (res.removedInfo.args != null) {
1478                                // Remove the replaced package's older resources safely now
1479                                deleteOld = true;
1480                            }
1481
1482                            // If this app is a browser and it's newly-installed for some
1483                            // users, clear any default-browser state in those users
1484                            if (firstUsers.length > 0) {
1485                                // the app's nature doesn't depend on the user, so we can just
1486                                // check its browser nature in any user and generalize.
1487                                if (packageIsBrowser(packageName, firstUsers[0])) {
1488                                    synchronized (mPackages) {
1489                                        for (int userId : firstUsers) {
1490                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1491                                        }
1492                                    }
1493                                }
1494                            }
1495                            // Log current value of "unknown sources" setting
1496                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1497                                getUnknownSourcesSettings());
1498                        }
1499                        // Force a gc to clear up things
1500                        Runtime.getRuntime().gc();
1501                        // We delete after a gc for applications  on sdcard.
1502                        if (deleteOld) {
1503                            synchronized (mInstallLock) {
1504                                res.removedInfo.args.doPostDeleteLI(true);
1505                            }
1506                        }
1507                        if (args.observer != null) {
1508                            try {
1509                                Bundle extras = extrasForInstallResult(res);
1510                                args.observer.onPackageInstalled(res.name, res.returnCode,
1511                                        res.returnMsg, extras);
1512                            } catch (RemoteException e) {
1513                                Slog.i(TAG, "Observer no longer exists.");
1514                            }
1515                        }
1516                        if (args.traceMethod != null) {
1517                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1518                                    args.traceCookie);
1519                        }
1520                        return;
1521                    } else {
1522                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1523                    }
1524
1525                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1526                } break;
1527                case UPDATED_MEDIA_STATUS: {
1528                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1529                    boolean reportStatus = msg.arg1 == 1;
1530                    boolean doGc = msg.arg2 == 1;
1531                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1532                    if (doGc) {
1533                        // Force a gc to clear up stale containers.
1534                        Runtime.getRuntime().gc();
1535                    }
1536                    if (msg.obj != null) {
1537                        @SuppressWarnings("unchecked")
1538                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1539                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1540                        // Unload containers
1541                        unloadAllContainers(args);
1542                    }
1543                    if (reportStatus) {
1544                        try {
1545                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1546                            PackageHelper.getMountService().finishMediaUpdate();
1547                        } catch (RemoteException e) {
1548                            Log.e(TAG, "MountService not running?");
1549                        }
1550                    }
1551                } break;
1552                case WRITE_SETTINGS: {
1553                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1554                    synchronized (mPackages) {
1555                        removeMessages(WRITE_SETTINGS);
1556                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1557                        mSettings.writeLPr();
1558                        mDirtyUsers.clear();
1559                    }
1560                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1561                } break;
1562                case WRITE_PACKAGE_RESTRICTIONS: {
1563                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1564                    synchronized (mPackages) {
1565                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1566                        for (int userId : mDirtyUsers) {
1567                            mSettings.writePackageRestrictionsLPr(userId);
1568                        }
1569                        mDirtyUsers.clear();
1570                    }
1571                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1572                } break;
1573                case CHECK_PENDING_VERIFICATION: {
1574                    final int verificationId = msg.arg1;
1575                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1576
1577                    if ((state != null) && !state.timeoutExtended()) {
1578                        final InstallArgs args = state.getInstallArgs();
1579                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1580
1581                        Slog.i(TAG, "Verification timed out for " + originUri);
1582                        mPendingVerification.remove(verificationId);
1583
1584                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1585
1586                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1587                            Slog.i(TAG, "Continuing with installation of " + originUri);
1588                            state.setVerifierResponse(Binder.getCallingUid(),
1589                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1590                            broadcastPackageVerified(verificationId, originUri,
1591                                    PackageManager.VERIFICATION_ALLOW,
1592                                    state.getInstallArgs().getUser());
1593                            try {
1594                                ret = args.copyApk(mContainerService, true);
1595                            } catch (RemoteException e) {
1596                                Slog.e(TAG, "Could not contact the ContainerService");
1597                            }
1598                        } else {
1599                            broadcastPackageVerified(verificationId, originUri,
1600                                    PackageManager.VERIFICATION_REJECT,
1601                                    state.getInstallArgs().getUser());
1602                        }
1603
1604                        Trace.asyncTraceEnd(
1605                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1606
1607                        processPendingInstall(args, ret);
1608                        mHandler.sendEmptyMessage(MCS_UNBIND);
1609                    }
1610                    break;
1611                }
1612                case PACKAGE_VERIFIED: {
1613                    final int verificationId = msg.arg1;
1614
1615                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1616                    if (state == null) {
1617                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1618                        break;
1619                    }
1620
1621                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1622
1623                    state.setVerifierResponse(response.callerUid, response.code);
1624
1625                    if (state.isVerificationComplete()) {
1626                        mPendingVerification.remove(verificationId);
1627
1628                        final InstallArgs args = state.getInstallArgs();
1629                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1630
1631                        int ret;
1632                        if (state.isInstallAllowed()) {
1633                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1634                            broadcastPackageVerified(verificationId, originUri,
1635                                    response.code, state.getInstallArgs().getUser());
1636                            try {
1637                                ret = args.copyApk(mContainerService, true);
1638                            } catch (RemoteException e) {
1639                                Slog.e(TAG, "Could not contact the ContainerService");
1640                            }
1641                        } else {
1642                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1643                        }
1644
1645                        Trace.asyncTraceEnd(
1646                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1647
1648                        processPendingInstall(args, ret);
1649                        mHandler.sendEmptyMessage(MCS_UNBIND);
1650                    }
1651
1652                    break;
1653                }
1654                case START_INTENT_FILTER_VERIFICATIONS: {
1655                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1656                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1657                            params.replacing, params.pkg);
1658                    break;
1659                }
1660                case INTENT_FILTER_VERIFIED: {
1661                    final int verificationId = msg.arg1;
1662
1663                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1664                            verificationId);
1665                    if (state == null) {
1666                        Slog.w(TAG, "Invalid IntentFilter verification token "
1667                                + verificationId + " received");
1668                        break;
1669                    }
1670
1671                    final int userId = state.getUserId();
1672
1673                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1674                            "Processing IntentFilter verification with token:"
1675                            + verificationId + " and userId:" + userId);
1676
1677                    final IntentFilterVerificationResponse response =
1678                            (IntentFilterVerificationResponse) msg.obj;
1679
1680                    state.setVerifierResponse(response.callerUid, response.code);
1681
1682                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1683                            "IntentFilter verification with token:" + verificationId
1684                            + " and userId:" + userId
1685                            + " is settings verifier response with response code:"
1686                            + response.code);
1687
1688                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1689                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1690                                + response.getFailedDomainsString());
1691                    }
1692
1693                    if (state.isVerificationComplete()) {
1694                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1695                    } else {
1696                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1697                                "IntentFilter verification with token:" + verificationId
1698                                + " was not said to be complete");
1699                    }
1700
1701                    break;
1702                }
1703            }
1704        }
1705    }
1706
1707    private StorageEventListener mStorageListener = new StorageEventListener() {
1708        @Override
1709        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1710            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1711                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1712                    final String volumeUuid = vol.getFsUuid();
1713
1714                    // Clean up any users or apps that were removed or recreated
1715                    // while this volume was missing
1716                    reconcileUsers(volumeUuid);
1717                    reconcileApps(volumeUuid);
1718
1719                    // Clean up any install sessions that expired or were
1720                    // cancelled while this volume was missing
1721                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1722
1723                    loadPrivatePackages(vol);
1724
1725                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1726                    unloadPrivatePackages(vol);
1727                }
1728            }
1729
1730            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1731                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1732                    updateExternalMediaStatus(true, false);
1733                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1734                    updateExternalMediaStatus(false, false);
1735                }
1736            }
1737        }
1738
1739        @Override
1740        public void onVolumeForgotten(String fsUuid) {
1741            if (TextUtils.isEmpty(fsUuid)) {
1742                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1743                return;
1744            }
1745
1746            // Remove any apps installed on the forgotten volume
1747            synchronized (mPackages) {
1748                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1749                for (PackageSetting ps : packages) {
1750                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1751                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1752                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1753                }
1754
1755                mSettings.onVolumeForgotten(fsUuid);
1756                mSettings.writeLPr();
1757            }
1758        }
1759    };
1760
1761    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1762            String[] grantedPermissions) {
1763        if (userId >= UserHandle.USER_SYSTEM) {
1764            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1765        } else if (userId == UserHandle.USER_ALL) {
1766            final int[] userIds;
1767            synchronized (mPackages) {
1768                userIds = UserManagerService.getInstance().getUserIds();
1769            }
1770            for (int someUserId : userIds) {
1771                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1772            }
1773        }
1774
1775        // We could have touched GID membership, so flush out packages.list
1776        synchronized (mPackages) {
1777            mSettings.writePackageListLPr();
1778        }
1779    }
1780
1781    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1782            String[] grantedPermissions) {
1783        SettingBase sb = (SettingBase) pkg.mExtras;
1784        if (sb == null) {
1785            return;
1786        }
1787
1788        PermissionsState permissionsState = sb.getPermissionsState();
1789
1790        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1791                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1792
1793        synchronized (mPackages) {
1794            for (String permission : pkg.requestedPermissions) {
1795                BasePermission bp = mSettings.mPermissions.get(permission);
1796                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1797                        && (grantedPermissions == null
1798                               || ArrayUtils.contains(grantedPermissions, permission))) {
1799                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1800                    // Installer cannot change immutable permissions.
1801                    if ((flags & immutableFlags) == 0) {
1802                        grantRuntimePermission(pkg.packageName, permission, userId);
1803                    }
1804                }
1805            }
1806        }
1807    }
1808
1809    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1810        Bundle extras = null;
1811        switch (res.returnCode) {
1812            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1813                extras = new Bundle();
1814                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1815                        res.origPermission);
1816                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1817                        res.origPackage);
1818                break;
1819            }
1820            case PackageManager.INSTALL_SUCCEEDED: {
1821                extras = new Bundle();
1822                extras.putBoolean(Intent.EXTRA_REPLACING,
1823                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1824                break;
1825            }
1826        }
1827        return extras;
1828    }
1829
1830    void scheduleWriteSettingsLocked() {
1831        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1832            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1833        }
1834    }
1835
1836    void scheduleWritePackageRestrictionsLocked(int userId) {
1837        if (!sUserManager.exists(userId)) return;
1838        mDirtyUsers.add(userId);
1839        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1840            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1841        }
1842    }
1843
1844    public static PackageManagerService main(Context context, Installer installer,
1845            boolean factoryTest, boolean onlyCore) {
1846        PackageManagerService m = new PackageManagerService(context, installer,
1847                factoryTest, onlyCore);
1848        m.enableSystemUserPackages();
1849        ServiceManager.addService("package", m);
1850        return m;
1851    }
1852
1853    private void enableSystemUserPackages() {
1854        if (!UserManager.isSplitSystemUser()) {
1855            return;
1856        }
1857        // For system user, enable apps based on the following conditions:
1858        // - app is whitelisted or belong to one of these groups:
1859        //   -- system app which has no launcher icons
1860        //   -- system app which has INTERACT_ACROSS_USERS permission
1861        //   -- system IME app
1862        // - app is not in the blacklist
1863        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1864        Set<String> enableApps = new ArraySet<>();
1865        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1866                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1867                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1868        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1869        enableApps.addAll(wlApps);
1870        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1871                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1872        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1873        enableApps.removeAll(blApps);
1874        Log.i(TAG, "Applications installed for system user: " + enableApps);
1875        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1876                UserHandle.SYSTEM);
1877        final int allAppsSize = allAps.size();
1878        synchronized (mPackages) {
1879            for (int i = 0; i < allAppsSize; i++) {
1880                String pName = allAps.get(i);
1881                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1882                // Should not happen, but we shouldn't be failing if it does
1883                if (pkgSetting == null) {
1884                    continue;
1885                }
1886                boolean install = enableApps.contains(pName);
1887                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1888                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1889                            + " for system user");
1890                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1891                }
1892            }
1893        }
1894    }
1895
1896    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1897        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1898                Context.DISPLAY_SERVICE);
1899        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1900    }
1901
1902    public PackageManagerService(Context context, Installer installer,
1903            boolean factoryTest, boolean onlyCore) {
1904        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1905                SystemClock.uptimeMillis());
1906
1907        if (mSdkVersion <= 0) {
1908            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1909        }
1910
1911        mContext = context;
1912        mFactoryTest = factoryTest;
1913        mOnlyCore = onlyCore;
1914        mMetrics = new DisplayMetrics();
1915        mSettings = new Settings(mPackages);
1916        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1917                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1918        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1919                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1920        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1921                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1922        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1923                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1924        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1925                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1926        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1927                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1928
1929        String separateProcesses = SystemProperties.get("debug.separate_processes");
1930        if (separateProcesses != null && separateProcesses.length() > 0) {
1931            if ("*".equals(separateProcesses)) {
1932                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1933                mSeparateProcesses = null;
1934                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1935            } else {
1936                mDefParseFlags = 0;
1937                mSeparateProcesses = separateProcesses.split(",");
1938                Slog.w(TAG, "Running with debug.separate_processes: "
1939                        + separateProcesses);
1940            }
1941        } else {
1942            mDefParseFlags = 0;
1943            mSeparateProcesses = null;
1944        }
1945
1946        mInstaller = installer;
1947        mPackageDexOptimizer = new PackageDexOptimizer(this);
1948        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1949
1950        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1951                FgThread.get().getLooper());
1952
1953        getDefaultDisplayMetrics(context, mMetrics);
1954
1955        SystemConfig systemConfig = SystemConfig.getInstance();
1956        mGlobalGids = systemConfig.getGlobalGids();
1957        mSystemPermissions = systemConfig.getSystemPermissions();
1958        mAvailableFeatures = systemConfig.getAvailableFeatures();
1959
1960        synchronized (mInstallLock) {
1961        // writer
1962        synchronized (mPackages) {
1963            mHandlerThread = new ServiceThread(TAG,
1964                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1965            mHandlerThread.start();
1966            mHandler = new PackageHandler(mHandlerThread.getLooper());
1967            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1968
1969            File dataDir = Environment.getDataDirectory();
1970            mAppInstallDir = new File(dataDir, "app");
1971            mAppLib32InstallDir = new File(dataDir, "app-lib");
1972            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1973            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1974            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1975
1976            sUserManager = new UserManagerService(context, this, mPackages);
1977
1978            // Propagate permission configuration in to package manager.
1979            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1980                    = systemConfig.getPermissions();
1981            for (int i=0; i<permConfig.size(); i++) {
1982                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1983                BasePermission bp = mSettings.mPermissions.get(perm.name);
1984                if (bp == null) {
1985                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1986                    mSettings.mPermissions.put(perm.name, bp);
1987                }
1988                if (perm.gids != null) {
1989                    bp.setGids(perm.gids, perm.perUser);
1990                }
1991            }
1992
1993            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1994            for (int i=0; i<libConfig.size(); i++) {
1995                mSharedLibraries.put(libConfig.keyAt(i),
1996                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1997            }
1998
1999            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2000
2001            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2002
2003            String customResolverActivity = Resources.getSystem().getString(
2004                    R.string.config_customResolverActivity);
2005            if (TextUtils.isEmpty(customResolverActivity)) {
2006                customResolverActivity = null;
2007            } else {
2008                mCustomResolverComponentName = ComponentName.unflattenFromString(
2009                        customResolverActivity);
2010            }
2011
2012            long startTime = SystemClock.uptimeMillis();
2013
2014            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2015                    startTime);
2016
2017            // Set flag to monitor and not change apk file paths when
2018            // scanning install directories.
2019            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2020
2021            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2022            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2023
2024            if (bootClassPath == null) {
2025                Slog.w(TAG, "No BOOTCLASSPATH found!");
2026            }
2027
2028            if (systemServerClassPath == null) {
2029                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2030            }
2031
2032            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2033            final String[] dexCodeInstructionSets =
2034                    getDexCodeInstructionSets(
2035                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2036
2037            /**
2038             * Ensure all external libraries have had dexopt run on them.
2039             */
2040            if (mSharedLibraries.size() > 0) {
2041                // NOTE: For now, we're compiling these system "shared libraries"
2042                // (and framework jars) into all available architectures. It's possible
2043                // to compile them only when we come across an app that uses them (there's
2044                // already logic for that in scanPackageLI) but that adds some complexity.
2045                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2046                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2047                        final String lib = libEntry.path;
2048                        if (lib == null) {
2049                            continue;
2050                        }
2051
2052                        try {
2053                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2054                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2055                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2056                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2057                            }
2058                        } catch (FileNotFoundException e) {
2059                            Slog.w(TAG, "Library not found: " + lib);
2060                        } catch (IOException e) {
2061                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2062                                    + e.getMessage());
2063                        }
2064                    }
2065                }
2066            }
2067
2068            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2069
2070            final VersionInfo ver = mSettings.getInternalVersion();
2071            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2072            // when upgrading from pre-M, promote system app permissions from install to runtime
2073            mPromoteSystemApps =
2074                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2075
2076            // save off the names of pre-existing system packages prior to scanning; we don't
2077            // want to automatically grant runtime permissions for new system apps
2078            if (mPromoteSystemApps) {
2079                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2080                while (pkgSettingIter.hasNext()) {
2081                    PackageSetting ps = pkgSettingIter.next();
2082                    if (isSystemApp(ps)) {
2083                        mExistingSystemPackages.add(ps.name);
2084                    }
2085                }
2086            }
2087
2088            // Collect vendor overlay packages.
2089            // (Do this before scanning any apps.)
2090            // For security and version matching reason, only consider
2091            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2092            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2093            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2094                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2095
2096            // Find base frameworks (resource packages without code).
2097            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2098                    | PackageParser.PARSE_IS_SYSTEM_DIR
2099                    | PackageParser.PARSE_IS_PRIVILEGED,
2100                    scanFlags | SCAN_NO_DEX, 0);
2101
2102            // Collected privileged system packages.
2103            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2104            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2105                    | PackageParser.PARSE_IS_SYSTEM_DIR
2106                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2107
2108            // Collect ordinary system packages.
2109            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2110            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2111                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2112
2113            // Collect all vendor packages.
2114            File vendorAppDir = new File("/vendor/app");
2115            try {
2116                vendorAppDir = vendorAppDir.getCanonicalFile();
2117            } catch (IOException e) {
2118                // failed to look up canonical path, continue with original one
2119            }
2120            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2121                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2122
2123            // Collect all OEM packages.
2124            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2125            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2126                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2127
2128            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2129            mInstaller.moveFiles();
2130
2131            // Prune any system packages that no longer exist.
2132            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2133            if (!mOnlyCore) {
2134                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2135                while (psit.hasNext()) {
2136                    PackageSetting ps = psit.next();
2137
2138                    /*
2139                     * If this is not a system app, it can't be a
2140                     * disable system app.
2141                     */
2142                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2143                        continue;
2144                    }
2145
2146                    /*
2147                     * If the package is scanned, it's not erased.
2148                     */
2149                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2150                    if (scannedPkg != null) {
2151                        /*
2152                         * If the system app is both scanned and in the
2153                         * disabled packages list, then it must have been
2154                         * added via OTA. Remove it from the currently
2155                         * scanned package so the previously user-installed
2156                         * application can be scanned.
2157                         */
2158                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2159                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2160                                    + ps.name + "; removing system app.  Last known codePath="
2161                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2162                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2163                                    + scannedPkg.mVersionCode);
2164                            removePackageLI(ps, true);
2165                            mExpectingBetter.put(ps.name, ps.codePath);
2166                        }
2167
2168                        continue;
2169                    }
2170
2171                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2172                        psit.remove();
2173                        logCriticalInfo(Log.WARN, "System package " + ps.name
2174                                + " no longer exists; wiping its data");
2175                        removeDataDirsLI(null, ps.name);
2176                    } else {
2177                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2178                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2179                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2180                        }
2181                    }
2182                }
2183            }
2184
2185            //look for any incomplete package installations
2186            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2187            //clean up list
2188            for(int i = 0; i < deletePkgsList.size(); i++) {
2189                //clean up here
2190                cleanupInstallFailedPackage(deletePkgsList.get(i));
2191            }
2192            //delete tmp files
2193            deleteTempPackageFiles();
2194
2195            // Remove any shared userIDs that have no associated packages
2196            mSettings.pruneSharedUsersLPw();
2197
2198            if (!mOnlyCore) {
2199                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2200                        SystemClock.uptimeMillis());
2201                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2202
2203                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2204                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2205
2206                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2207                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2208
2209                /**
2210                 * Remove disable package settings for any updated system
2211                 * apps that were removed via an OTA. If they're not a
2212                 * previously-updated app, remove them completely.
2213                 * Otherwise, just revoke their system-level permissions.
2214                 */
2215                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2216                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2217                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2218
2219                    String msg;
2220                    if (deletedPkg == null) {
2221                        msg = "Updated system package " + deletedAppName
2222                                + " no longer exists; wiping its data";
2223                        removeDataDirsLI(null, deletedAppName);
2224                    } else {
2225                        msg = "Updated system app + " + deletedAppName
2226                                + " no longer present; removing system privileges for "
2227                                + deletedAppName;
2228
2229                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2230
2231                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2232                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2233                    }
2234                    logCriticalInfo(Log.WARN, msg);
2235                }
2236
2237                /**
2238                 * Make sure all system apps that we expected to appear on
2239                 * the userdata partition actually showed up. If they never
2240                 * appeared, crawl back and revive the system version.
2241                 */
2242                for (int i = 0; i < mExpectingBetter.size(); i++) {
2243                    final String packageName = mExpectingBetter.keyAt(i);
2244                    if (!mPackages.containsKey(packageName)) {
2245                        final File scanFile = mExpectingBetter.valueAt(i);
2246
2247                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2248                                + " but never showed up; reverting to system");
2249
2250                        final int reparseFlags;
2251                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2252                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2253                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2254                                    | PackageParser.PARSE_IS_PRIVILEGED;
2255                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2256                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2257                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2258                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2259                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2260                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2261                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2262                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2263                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2264                        } else {
2265                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2266                            continue;
2267                        }
2268
2269                        mSettings.enableSystemPackageLPw(packageName);
2270
2271                        try {
2272                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2273                        } catch (PackageManagerException e) {
2274                            Slog.e(TAG, "Failed to parse original system package: "
2275                                    + e.getMessage());
2276                        }
2277                    }
2278                }
2279            }
2280            mExpectingBetter.clear();
2281
2282            // Now that we know all of the shared libraries, update all clients to have
2283            // the correct library paths.
2284            updateAllSharedLibrariesLPw();
2285
2286            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2287                // NOTE: We ignore potential failures here during a system scan (like
2288                // the rest of the commands above) because there's precious little we
2289                // can do about it. A settings error is reported, though.
2290                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2291                        false /* boot complete */);
2292            }
2293
2294            // Now that we know all the packages we are keeping,
2295            // read and update their last usage times.
2296            mPackageUsage.readLP();
2297
2298            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2299                    SystemClock.uptimeMillis());
2300            Slog.i(TAG, "Time to scan packages: "
2301                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2302                    + " seconds");
2303
2304            // If the platform SDK has changed since the last time we booted,
2305            // we need to re-grant app permission to catch any new ones that
2306            // appear.  This is really a hack, and means that apps can in some
2307            // cases get permissions that the user didn't initially explicitly
2308            // allow...  it would be nice to have some better way to handle
2309            // this situation.
2310            int updateFlags = UPDATE_PERMISSIONS_ALL;
2311            if (ver.sdkVersion != mSdkVersion) {
2312                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2313                        + mSdkVersion + "; regranting permissions for internal storage");
2314                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2315            }
2316            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2317            ver.sdkVersion = mSdkVersion;
2318
2319            // If this is the first boot or an update from pre-M, and it is a normal
2320            // boot, then we need to initialize the default preferred apps across
2321            // all defined users.
2322            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2323                for (UserInfo user : sUserManager.getUsers(true)) {
2324                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2325                    applyFactoryDefaultBrowserLPw(user.id);
2326                    primeDomainVerificationsLPw(user.id);
2327                }
2328            }
2329
2330            // If this is first boot after an OTA, and a normal boot, then
2331            // we need to clear code cache directories.
2332            if (mIsUpgrade && !onlyCore) {
2333                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2334                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2335                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2336                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2337                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2338                    }
2339                }
2340                ver.fingerprint = Build.FINGERPRINT;
2341            }
2342
2343            checkDefaultBrowser();
2344
2345            // clear only after permissions and other defaults have been updated
2346            mExistingSystemPackages.clear();
2347            mPromoteSystemApps = false;
2348
2349            // All the changes are done during package scanning.
2350            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2351
2352            // can downgrade to reader
2353            mSettings.writeLPr();
2354
2355            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2356                    SystemClock.uptimeMillis());
2357
2358            mRequiredVerifierPackage = getRequiredVerifierLPr();
2359            mRequiredInstallerPackage = getRequiredInstallerLPr();
2360
2361            mInstallerService = new PackageInstallerService(context, this);
2362
2363            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2364            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2365                    mIntentFilterVerifierComponent);
2366
2367            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2368            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2369            // both the installer and resolver must be present to enable ephemeral
2370            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2371                if (DEBUG_EPHEMERAL) {
2372                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2373                            + " installer:" + ephemeralInstallerComponent);
2374                }
2375                mEphemeralResolverComponent = ephemeralResolverComponent;
2376                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2377                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2378                mEphemeralResolverConnection =
2379                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2380            } else {
2381                if (DEBUG_EPHEMERAL) {
2382                    final String missingComponent =
2383                            (ephemeralResolverComponent == null)
2384                            ? (ephemeralInstallerComponent == null)
2385                                    ? "resolver and installer"
2386                                    : "resolver"
2387                            : "installer";
2388                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2389                }
2390                mEphemeralResolverComponent = null;
2391                mEphemeralInstallerComponent = null;
2392                mEphemeralResolverConnection = null;
2393            }
2394
2395            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2396        } // synchronized (mPackages)
2397        } // synchronized (mInstallLock)
2398
2399        // Now after opening every single application zip, make sure they
2400        // are all flushed.  Not really needed, but keeps things nice and
2401        // tidy.
2402        Runtime.getRuntime().gc();
2403
2404        // The initial scanning above does many calls into installd while
2405        // holding the mPackages lock, but we're mostly interested in yelling
2406        // once we have a booted system.
2407        mInstaller.setWarnIfHeld(mPackages);
2408
2409        // Expose private service for system components to use.
2410        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2411    }
2412
2413    @Override
2414    public boolean isFirstBoot() {
2415        return !mRestoredSettings;
2416    }
2417
2418    @Override
2419    public boolean isOnlyCoreApps() {
2420        return mOnlyCore;
2421    }
2422
2423    @Override
2424    public boolean isUpgrade() {
2425        return mIsUpgrade;
2426    }
2427
2428    private String getRequiredVerifierLPr() {
2429        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2430        // We only care about verifier that's installed under system user.
2431        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2432                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2433
2434        String requiredVerifier = null;
2435
2436        final int N = receivers.size();
2437        for (int i = 0; i < N; i++) {
2438            final ResolveInfo info = receivers.get(i);
2439
2440            if (info.activityInfo == null) {
2441                continue;
2442            }
2443
2444            final String packageName = info.activityInfo.packageName;
2445
2446            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2447                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2448                continue;
2449            }
2450
2451            if (requiredVerifier != null) {
2452                throw new RuntimeException("There can be only one required verifier");
2453            }
2454
2455            requiredVerifier = packageName;
2456        }
2457
2458        return requiredVerifier;
2459    }
2460
2461    private String getRequiredInstallerLPr() {
2462        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2463        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2464        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2465
2466        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2467                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2468
2469        String requiredInstaller = null;
2470
2471        final int N = installers.size();
2472        for (int i = 0; i < N; i++) {
2473            final ResolveInfo info = installers.get(i);
2474            final String packageName = info.activityInfo.packageName;
2475
2476            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2477                continue;
2478            }
2479
2480            if (requiredInstaller != null) {
2481                throw new RuntimeException("There must be one required installer");
2482            }
2483
2484            requiredInstaller = packageName;
2485        }
2486
2487        if (requiredInstaller == null) {
2488            throw new RuntimeException("There must be one required installer");
2489        }
2490
2491        return requiredInstaller;
2492    }
2493
2494    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2495        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2496        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2497                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2498
2499        ComponentName verifierComponentName = null;
2500
2501        int priority = -1000;
2502        final int N = receivers.size();
2503        for (int i = 0; i < N; i++) {
2504            final ResolveInfo info = receivers.get(i);
2505
2506            if (info.activityInfo == null) {
2507                continue;
2508            }
2509
2510            final String packageName = info.activityInfo.packageName;
2511
2512            final PackageSetting ps = mSettings.mPackages.get(packageName);
2513            if (ps == null) {
2514                continue;
2515            }
2516
2517            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2518                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2519                continue;
2520            }
2521
2522            // Select the IntentFilterVerifier with the highest priority
2523            if (priority < info.priority) {
2524                priority = info.priority;
2525                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2526                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2527                        + verifierComponentName + " with priority: " + info.priority);
2528            }
2529        }
2530
2531        return verifierComponentName;
2532    }
2533
2534    private ComponentName getEphemeralResolverLPr() {
2535        final String[] packageArray =
2536                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2537        if (packageArray.length == 0) {
2538            if (DEBUG_EPHEMERAL) {
2539                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2540            }
2541            return null;
2542        }
2543
2544        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2545        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2546                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2547
2548        final int N = resolvers.size();
2549        if (N == 0) {
2550            if (DEBUG_EPHEMERAL) {
2551                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2552            }
2553            return null;
2554        }
2555
2556        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2557        for (int i = 0; i < N; i++) {
2558            final ResolveInfo info = resolvers.get(i);
2559
2560            if (info.serviceInfo == null) {
2561                continue;
2562            }
2563
2564            final String packageName = info.serviceInfo.packageName;
2565            if (!possiblePackages.contains(packageName)) {
2566                if (DEBUG_EPHEMERAL) {
2567                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2568                            + " pkg: " + packageName + ", info:" + info);
2569                }
2570                continue;
2571            }
2572
2573            if (DEBUG_EPHEMERAL) {
2574                Slog.v(TAG, "Ephemeral resolver found;"
2575                        + " pkg: " + packageName + ", info:" + info);
2576            }
2577            return new ComponentName(packageName, info.serviceInfo.name);
2578        }
2579        if (DEBUG_EPHEMERAL) {
2580            Slog.v(TAG, "Ephemeral resolver NOT found");
2581        }
2582        return null;
2583    }
2584
2585    private ComponentName getEphemeralInstallerLPr() {
2586        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2587        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2588        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2589        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2590                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2591
2592        ComponentName ephemeralInstaller = null;
2593
2594        final int N = installers.size();
2595        for (int i = 0; i < N; i++) {
2596            final ResolveInfo info = installers.get(i);
2597            final String packageName = info.activityInfo.packageName;
2598
2599            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2600                if (DEBUG_EPHEMERAL) {
2601                    Slog.d(TAG, "Ephemeral installer is not system app;"
2602                            + " pkg: " + packageName + ", info:" + info);
2603                }
2604                continue;
2605            }
2606
2607            if (ephemeralInstaller != null) {
2608                throw new RuntimeException("There must only be one ephemeral installer");
2609            }
2610
2611            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2612        }
2613
2614        return ephemeralInstaller;
2615    }
2616
2617    private void primeDomainVerificationsLPw(int userId) {
2618        if (DEBUG_DOMAIN_VERIFICATION) {
2619            Slog.d(TAG, "Priming domain verifications in user " + userId);
2620        }
2621
2622        SystemConfig systemConfig = SystemConfig.getInstance();
2623        ArraySet<String> packages = systemConfig.getLinkedApps();
2624        ArraySet<String> domains = new ArraySet<String>();
2625
2626        for (String packageName : packages) {
2627            PackageParser.Package pkg = mPackages.get(packageName);
2628            if (pkg != null) {
2629                if (!pkg.isSystemApp()) {
2630                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2631                    continue;
2632                }
2633
2634                domains.clear();
2635                for (PackageParser.Activity a : pkg.activities) {
2636                    for (ActivityIntentInfo filter : a.intents) {
2637                        if (hasValidDomains(filter)) {
2638                            domains.addAll(filter.getHostsList());
2639                        }
2640                    }
2641                }
2642
2643                if (domains.size() > 0) {
2644                    if (DEBUG_DOMAIN_VERIFICATION) {
2645                        Slog.v(TAG, "      + " + packageName);
2646                    }
2647                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2648                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2649                    // and then 'always' in the per-user state actually used for intent resolution.
2650                    final IntentFilterVerificationInfo ivi;
2651                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2652                            new ArrayList<String>(domains));
2653                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2654                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2655                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2656                } else {
2657                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2658                            + "' does not handle web links");
2659                }
2660            } else {
2661                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2662            }
2663        }
2664
2665        scheduleWritePackageRestrictionsLocked(userId);
2666        scheduleWriteSettingsLocked();
2667    }
2668
2669    private void applyFactoryDefaultBrowserLPw(int userId) {
2670        // The default browser app's package name is stored in a string resource,
2671        // with a product-specific overlay used for vendor customization.
2672        String browserPkg = mContext.getResources().getString(
2673                com.android.internal.R.string.default_browser);
2674        if (!TextUtils.isEmpty(browserPkg)) {
2675            // non-empty string => required to be a known package
2676            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2677            if (ps == null) {
2678                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2679                browserPkg = null;
2680            } else {
2681                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2682            }
2683        }
2684
2685        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2686        // default.  If there's more than one, just leave everything alone.
2687        if (browserPkg == null) {
2688            calculateDefaultBrowserLPw(userId);
2689        }
2690    }
2691
2692    private void calculateDefaultBrowserLPw(int userId) {
2693        List<String> allBrowsers = resolveAllBrowserApps(userId);
2694        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2695        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2696    }
2697
2698    private List<String> resolveAllBrowserApps(int userId) {
2699        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2700        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2701                PackageManager.MATCH_ALL, userId);
2702
2703        final int count = list.size();
2704        List<String> result = new ArrayList<String>(count);
2705        for (int i=0; i<count; i++) {
2706            ResolveInfo info = list.get(i);
2707            if (info.activityInfo == null
2708                    || !info.handleAllWebDataURI
2709                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2710                    || result.contains(info.activityInfo.packageName)) {
2711                continue;
2712            }
2713            result.add(info.activityInfo.packageName);
2714        }
2715
2716        return result;
2717    }
2718
2719    private boolean packageIsBrowser(String packageName, int userId) {
2720        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2721                PackageManager.MATCH_ALL, userId);
2722        final int N = list.size();
2723        for (int i = 0; i < N; i++) {
2724            ResolveInfo info = list.get(i);
2725            if (packageName.equals(info.activityInfo.packageName)) {
2726                return true;
2727            }
2728        }
2729        return false;
2730    }
2731
2732    private void checkDefaultBrowser() {
2733        final int myUserId = UserHandle.myUserId();
2734        final String packageName = getDefaultBrowserPackageName(myUserId);
2735        if (packageName != null) {
2736            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2737            if (info == null) {
2738                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2739                synchronized (mPackages) {
2740                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2741                }
2742            }
2743        }
2744    }
2745
2746    @Override
2747    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2748            throws RemoteException {
2749        try {
2750            return super.onTransact(code, data, reply, flags);
2751        } catch (RuntimeException e) {
2752            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2753                Slog.wtf(TAG, "Package Manager Crash", e);
2754            }
2755            throw e;
2756        }
2757    }
2758
2759    void cleanupInstallFailedPackage(PackageSetting ps) {
2760        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2761
2762        removeDataDirsLI(ps.volumeUuid, ps.name);
2763        if (ps.codePath != null) {
2764            if (ps.codePath.isDirectory()) {
2765                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2766            } else {
2767                ps.codePath.delete();
2768            }
2769        }
2770        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2771            if (ps.resourcePath.isDirectory()) {
2772                FileUtils.deleteContents(ps.resourcePath);
2773            }
2774            ps.resourcePath.delete();
2775        }
2776        mSettings.removePackageLPw(ps.name);
2777    }
2778
2779    static int[] appendInts(int[] cur, int[] add) {
2780        if (add == null) return cur;
2781        if (cur == null) return add;
2782        final int N = add.length;
2783        for (int i=0; i<N; i++) {
2784            cur = appendInt(cur, add[i]);
2785        }
2786        return cur;
2787    }
2788
2789    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2790        if (!sUserManager.exists(userId)) return null;
2791        final PackageSetting ps = (PackageSetting) p.mExtras;
2792        if (ps == null) {
2793            return null;
2794        }
2795
2796        final PermissionsState permissionsState = ps.getPermissionsState();
2797
2798        final int[] gids = permissionsState.computeGids(userId);
2799        final Set<String> permissions = permissionsState.getPermissions(userId);
2800        final PackageUserState state = ps.readUserState(userId);
2801
2802        return PackageParser.generatePackageInfo(p, gids, flags,
2803                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2804    }
2805
2806    @Override
2807    public void checkPackageStartable(String packageName, int userId) {
2808        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2809
2810        synchronized (mPackages) {
2811            final PackageSetting ps = mSettings.mPackages.get(packageName);
2812            if (ps == null) {
2813                throw new SecurityException("Package " + packageName + " was not found!");
2814            }
2815
2816            if (ps.frozen) {
2817                throw new SecurityException("Package " + packageName + " is currently frozen!");
2818            }
2819
2820            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2821                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2822                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2823            }
2824        }
2825    }
2826
2827    @Override
2828    public boolean isPackageAvailable(String packageName, int userId) {
2829        if (!sUserManager.exists(userId)) return false;
2830        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2831        synchronized (mPackages) {
2832            PackageParser.Package p = mPackages.get(packageName);
2833            if (p != null) {
2834                final PackageSetting ps = (PackageSetting) p.mExtras;
2835                if (ps != null) {
2836                    final PackageUserState state = ps.readUserState(userId);
2837                    if (state != null) {
2838                        return PackageParser.isAvailable(state);
2839                    }
2840                }
2841            }
2842        }
2843        return false;
2844    }
2845
2846    @Override
2847    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2848        if (!sUserManager.exists(userId)) return null;
2849        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2850        // reader
2851        synchronized (mPackages) {
2852            PackageParser.Package p = mPackages.get(packageName);
2853            if (DEBUG_PACKAGE_INFO)
2854                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2855            if (p != null) {
2856                return generatePackageInfo(p, flags, userId);
2857            }
2858            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2859                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2860            }
2861        }
2862        return null;
2863    }
2864
2865    @Override
2866    public String[] currentToCanonicalPackageNames(String[] names) {
2867        String[] out = new String[names.length];
2868        // reader
2869        synchronized (mPackages) {
2870            for (int i=names.length-1; i>=0; i--) {
2871                PackageSetting ps = mSettings.mPackages.get(names[i]);
2872                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2873            }
2874        }
2875        return out;
2876    }
2877
2878    @Override
2879    public String[] canonicalToCurrentPackageNames(String[] names) {
2880        String[] out = new String[names.length];
2881        // reader
2882        synchronized (mPackages) {
2883            for (int i=names.length-1; i>=0; i--) {
2884                String cur = mSettings.mRenamedPackages.get(names[i]);
2885                out[i] = cur != null ? cur : names[i];
2886            }
2887        }
2888        return out;
2889    }
2890
2891    @Override
2892    public int getPackageUid(String packageName, int userId) {
2893        return getPackageUidEtc(packageName, 0, userId);
2894    }
2895
2896    @Override
2897    public int getPackageUidEtc(String packageName, int flags, int userId) {
2898        if (!sUserManager.exists(userId)) return -1;
2899        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2900
2901        // reader
2902        synchronized (mPackages) {
2903            final PackageParser.Package p = mPackages.get(packageName);
2904            if (p != null) {
2905                return UserHandle.getUid(userId, p.applicationInfo.uid);
2906            }
2907            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2908                final PackageSetting ps = mSettings.mPackages.get(packageName);
2909                if (ps != null) {
2910                    return UserHandle.getUid(userId, ps.appId);
2911                }
2912            }
2913        }
2914
2915        return -1;
2916    }
2917
2918    @Override
2919    public int[] getPackageGids(String packageName, int userId) {
2920        return getPackageGidsEtc(packageName, 0, userId);
2921    }
2922
2923    @Override
2924    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2925        if (!sUserManager.exists(userId)) {
2926            return null;
2927        }
2928
2929        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2930                "getPackageGids");
2931
2932        // reader
2933        synchronized (mPackages) {
2934            final PackageParser.Package p = mPackages.get(packageName);
2935            if (p != null) {
2936                PackageSetting ps = (PackageSetting) p.mExtras;
2937                return ps.getPermissionsState().computeGids(userId);
2938            }
2939            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2940                final PackageSetting ps = mSettings.mPackages.get(packageName);
2941                if (ps != null) {
2942                    return ps.getPermissionsState().computeGids(userId);
2943                }
2944            }
2945        }
2946
2947        return null;
2948    }
2949
2950    static PermissionInfo generatePermissionInfo(
2951            BasePermission bp, int flags) {
2952        if (bp.perm != null) {
2953            return PackageParser.generatePermissionInfo(bp.perm, flags);
2954        }
2955        PermissionInfo pi = new PermissionInfo();
2956        pi.name = bp.name;
2957        pi.packageName = bp.sourcePackage;
2958        pi.nonLocalizedLabel = bp.name;
2959        pi.protectionLevel = bp.protectionLevel;
2960        return pi;
2961    }
2962
2963    @Override
2964    public PermissionInfo getPermissionInfo(String name, int flags) {
2965        // reader
2966        synchronized (mPackages) {
2967            final BasePermission p = mSettings.mPermissions.get(name);
2968            if (p != null) {
2969                return generatePermissionInfo(p, flags);
2970            }
2971            return null;
2972        }
2973    }
2974
2975    @Override
2976    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2977        // reader
2978        synchronized (mPackages) {
2979            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2980            for (BasePermission p : mSettings.mPermissions.values()) {
2981                if (group == null) {
2982                    if (p.perm == null || p.perm.info.group == null) {
2983                        out.add(generatePermissionInfo(p, flags));
2984                    }
2985                } else {
2986                    if (p.perm != null && group.equals(p.perm.info.group)) {
2987                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2988                    }
2989                }
2990            }
2991
2992            if (out.size() > 0) {
2993                return out;
2994            }
2995            return mPermissionGroups.containsKey(group) ? out : null;
2996        }
2997    }
2998
2999    @Override
3000    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3001        // reader
3002        synchronized (mPackages) {
3003            return PackageParser.generatePermissionGroupInfo(
3004                    mPermissionGroups.get(name), flags);
3005        }
3006    }
3007
3008    @Override
3009    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3010        // reader
3011        synchronized (mPackages) {
3012            final int N = mPermissionGroups.size();
3013            ArrayList<PermissionGroupInfo> out
3014                    = new ArrayList<PermissionGroupInfo>(N);
3015            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3016                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3017            }
3018            return out;
3019        }
3020    }
3021
3022    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3023            int userId) {
3024        if (!sUserManager.exists(userId)) return null;
3025        PackageSetting ps = mSettings.mPackages.get(packageName);
3026        if (ps != null) {
3027            if (ps.pkg == null) {
3028                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3029                        flags, userId);
3030                if (pInfo != null) {
3031                    return pInfo.applicationInfo;
3032                }
3033                return null;
3034            }
3035            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3036                    ps.readUserState(userId), userId);
3037        }
3038        return null;
3039    }
3040
3041    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3042            int userId) {
3043        if (!sUserManager.exists(userId)) return null;
3044        PackageSetting ps = mSettings.mPackages.get(packageName);
3045        if (ps != null) {
3046            PackageParser.Package pkg = ps.pkg;
3047            if (pkg == null) {
3048                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3049                    return null;
3050                }
3051                // Only data remains, so we aren't worried about code paths
3052                pkg = new PackageParser.Package(packageName);
3053                pkg.applicationInfo.packageName = packageName;
3054                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3055                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3056                pkg.applicationInfo.uid = ps.appId;
3057                pkg.applicationInfo.initForUser(userId);
3058                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3059                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3060            }
3061            return generatePackageInfo(pkg, flags, userId);
3062        }
3063        return null;
3064    }
3065
3066    @Override
3067    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3068        if (!sUserManager.exists(userId)) return null;
3069        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3070        // writer
3071        synchronized (mPackages) {
3072            PackageParser.Package p = mPackages.get(packageName);
3073            if (DEBUG_PACKAGE_INFO) Log.v(
3074                    TAG, "getApplicationInfo " + packageName
3075                    + ": " + p);
3076            if (p != null) {
3077                PackageSetting ps = mSettings.mPackages.get(packageName);
3078                if (ps == null) return null;
3079                // Note: isEnabledLP() does not apply here - always return info
3080                return PackageParser.generateApplicationInfo(
3081                        p, flags, ps.readUserState(userId), userId);
3082            }
3083            if ("android".equals(packageName)||"system".equals(packageName)) {
3084                return mAndroidApplication;
3085            }
3086            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3087                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3088            }
3089        }
3090        return null;
3091    }
3092
3093    @Override
3094    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3095            final IPackageDataObserver observer) {
3096        mContext.enforceCallingOrSelfPermission(
3097                android.Manifest.permission.CLEAR_APP_CACHE, null);
3098        // Queue up an async operation since clearing cache may take a little while.
3099        mHandler.post(new Runnable() {
3100            public void run() {
3101                mHandler.removeCallbacks(this);
3102                int retCode = -1;
3103                synchronized (mInstallLock) {
3104                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3105                    if (retCode < 0) {
3106                        Slog.w(TAG, "Couldn't clear application caches");
3107                    }
3108                }
3109                if (observer != null) {
3110                    try {
3111                        observer.onRemoveCompleted(null, (retCode >= 0));
3112                    } catch (RemoteException e) {
3113                        Slog.w(TAG, "RemoveException when invoking call back");
3114                    }
3115                }
3116            }
3117        });
3118    }
3119
3120    @Override
3121    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3122            final IntentSender pi) {
3123        mContext.enforceCallingOrSelfPermission(
3124                android.Manifest.permission.CLEAR_APP_CACHE, null);
3125        // Queue up an async operation since clearing cache may take a little while.
3126        mHandler.post(new Runnable() {
3127            public void run() {
3128                mHandler.removeCallbacks(this);
3129                int retCode = -1;
3130                synchronized (mInstallLock) {
3131                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3132                    if (retCode < 0) {
3133                        Slog.w(TAG, "Couldn't clear application caches");
3134                    }
3135                }
3136                if(pi != null) {
3137                    try {
3138                        // Callback via pending intent
3139                        int code = (retCode >= 0) ? 1 : 0;
3140                        pi.sendIntent(null, code, null,
3141                                null, null);
3142                    } catch (SendIntentException e1) {
3143                        Slog.i(TAG, "Failed to send pending intent");
3144                    }
3145                }
3146            }
3147        });
3148    }
3149
3150    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3151        synchronized (mInstallLock) {
3152            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3153                throw new IOException("Failed to free enough space");
3154            }
3155        }
3156    }
3157
3158    /**
3159     * Return if the user key is currently unlocked.
3160     */
3161    private boolean isUserKeyUnlocked(int userId) {
3162        if (StorageManager.isFileBasedEncryptionEnabled()) {
3163            final IMountService mount = IMountService.Stub
3164                    .asInterface(ServiceManager.getService("mount"));
3165            if (mount == null) {
3166                Slog.w(TAG, "Early during boot, assuming locked");
3167                return false;
3168            }
3169            final long token = Binder.clearCallingIdentity();
3170            try {
3171                return mount.isUserKeyUnlocked(userId);
3172            } catch (RemoteException e) {
3173                throw e.rethrowAsRuntimeException();
3174            } finally {
3175                Binder.restoreCallingIdentity(token);
3176            }
3177        } else {
3178            return true;
3179        }
3180    }
3181
3182    /**
3183     * Augment the given flags depending on current user running state. This is
3184     * purposefully done before acquiring {@link #mPackages} lock.
3185     */
3186    private int augmentFlagsForUser(int flags, int userId) {
3187        if (!isUserKeyUnlocked(userId)) {
3188            flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3189        }
3190        return flags;
3191    }
3192
3193    @Override
3194    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3195        if (!sUserManager.exists(userId)) return null;
3196        flags = augmentFlagsForUser(flags, userId);
3197        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3198        synchronized (mPackages) {
3199            PackageParser.Activity a = mActivities.mActivities.get(component);
3200
3201            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3202            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3203                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3204                if (ps == null) return null;
3205                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3206                        userId);
3207            }
3208            if (mResolveComponentName.equals(component)) {
3209                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3210                        new PackageUserState(), userId);
3211            }
3212        }
3213        return null;
3214    }
3215
3216    @Override
3217    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3218            String resolvedType) {
3219        synchronized (mPackages) {
3220            if (component.equals(mResolveComponentName)) {
3221                // The resolver supports EVERYTHING!
3222                return true;
3223            }
3224            PackageParser.Activity a = mActivities.mActivities.get(component);
3225            if (a == null) {
3226                return false;
3227            }
3228            for (int i=0; i<a.intents.size(); i++) {
3229                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3230                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3231                    return true;
3232                }
3233            }
3234            return false;
3235        }
3236    }
3237
3238    @Override
3239    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3240        if (!sUserManager.exists(userId)) return null;
3241        flags = augmentFlagsForUser(flags, userId);
3242        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3243        synchronized (mPackages) {
3244            PackageParser.Activity a = mReceivers.mActivities.get(component);
3245            if (DEBUG_PACKAGE_INFO) Log.v(
3246                TAG, "getReceiverInfo " + component + ": " + a);
3247            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3248                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3249                if (ps == null) return null;
3250                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3251                        userId);
3252            }
3253        }
3254        return null;
3255    }
3256
3257    @Override
3258    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3259        if (!sUserManager.exists(userId)) return null;
3260        flags = augmentFlagsForUser(flags, userId);
3261        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3262        synchronized (mPackages) {
3263            PackageParser.Service s = mServices.mServices.get(component);
3264            if (DEBUG_PACKAGE_INFO) Log.v(
3265                TAG, "getServiceInfo " + component + ": " + s);
3266            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3267                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3268                if (ps == null) return null;
3269                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3270                        userId);
3271            }
3272        }
3273        return null;
3274    }
3275
3276    @Override
3277    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3278        if (!sUserManager.exists(userId)) return null;
3279        flags = augmentFlagsForUser(flags, userId);
3280        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3281        synchronized (mPackages) {
3282            PackageParser.Provider p = mProviders.mProviders.get(component);
3283            if (DEBUG_PACKAGE_INFO) Log.v(
3284                TAG, "getProviderInfo " + component + ": " + p);
3285            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3286                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3287                if (ps == null) return null;
3288                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3289                        userId);
3290            }
3291        }
3292        return null;
3293    }
3294
3295    @Override
3296    public String[] getSystemSharedLibraryNames() {
3297        Set<String> libSet;
3298        synchronized (mPackages) {
3299            libSet = mSharedLibraries.keySet();
3300            int size = libSet.size();
3301            if (size > 0) {
3302                String[] libs = new String[size];
3303                libSet.toArray(libs);
3304                return libs;
3305            }
3306        }
3307        return null;
3308    }
3309
3310    /**
3311     * @hide
3312     */
3313    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3314        synchronized (mPackages) {
3315            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3316            if (lib != null && lib.apk != null) {
3317                return mPackages.get(lib.apk);
3318            }
3319        }
3320        return null;
3321    }
3322
3323    @Override
3324    public FeatureInfo[] getSystemAvailableFeatures() {
3325        Collection<FeatureInfo> featSet;
3326        synchronized (mPackages) {
3327            featSet = mAvailableFeatures.values();
3328            int size = featSet.size();
3329            if (size > 0) {
3330                FeatureInfo[] features = new FeatureInfo[size+1];
3331                featSet.toArray(features);
3332                FeatureInfo fi = new FeatureInfo();
3333                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3334                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3335                features[size] = fi;
3336                return features;
3337            }
3338        }
3339        return null;
3340    }
3341
3342    @Override
3343    public boolean hasSystemFeature(String name) {
3344        synchronized (mPackages) {
3345            return mAvailableFeatures.containsKey(name);
3346        }
3347    }
3348
3349    @Override
3350    public int checkPermission(String permName, String pkgName, int userId) {
3351        if (!sUserManager.exists(userId)) {
3352            return PackageManager.PERMISSION_DENIED;
3353        }
3354
3355        synchronized (mPackages) {
3356            final PackageParser.Package p = mPackages.get(pkgName);
3357            if (p != null && p.mExtras != null) {
3358                final PackageSetting ps = (PackageSetting) p.mExtras;
3359                final PermissionsState permissionsState = ps.getPermissionsState();
3360                if (permissionsState.hasPermission(permName, userId)) {
3361                    return PackageManager.PERMISSION_GRANTED;
3362                }
3363                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3364                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3365                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3366                    return PackageManager.PERMISSION_GRANTED;
3367                }
3368            }
3369        }
3370
3371        return PackageManager.PERMISSION_DENIED;
3372    }
3373
3374    @Override
3375    public int checkUidPermission(String permName, int uid) {
3376        final int userId = UserHandle.getUserId(uid);
3377
3378        if (!sUserManager.exists(userId)) {
3379            return PackageManager.PERMISSION_DENIED;
3380        }
3381
3382        synchronized (mPackages) {
3383            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3384            if (obj != null) {
3385                final SettingBase ps = (SettingBase) obj;
3386                final PermissionsState permissionsState = ps.getPermissionsState();
3387                if (permissionsState.hasPermission(permName, userId)) {
3388                    return PackageManager.PERMISSION_GRANTED;
3389                }
3390                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3391                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3392                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3393                    return PackageManager.PERMISSION_GRANTED;
3394                }
3395            } else {
3396                ArraySet<String> perms = mSystemPermissions.get(uid);
3397                if (perms != null) {
3398                    if (perms.contains(permName)) {
3399                        return PackageManager.PERMISSION_GRANTED;
3400                    }
3401                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3402                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3403                        return PackageManager.PERMISSION_GRANTED;
3404                    }
3405                }
3406            }
3407        }
3408
3409        return PackageManager.PERMISSION_DENIED;
3410    }
3411
3412    @Override
3413    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3414        if (UserHandle.getCallingUserId() != userId) {
3415            mContext.enforceCallingPermission(
3416                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3417                    "isPermissionRevokedByPolicy for user " + userId);
3418        }
3419
3420        if (checkPermission(permission, packageName, userId)
3421                == PackageManager.PERMISSION_GRANTED) {
3422            return false;
3423        }
3424
3425        final long identity = Binder.clearCallingIdentity();
3426        try {
3427            final int flags = getPermissionFlags(permission, packageName, userId);
3428            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3429        } finally {
3430            Binder.restoreCallingIdentity(identity);
3431        }
3432    }
3433
3434    @Override
3435    public String getPermissionControllerPackageName() {
3436        synchronized (mPackages) {
3437            return mRequiredInstallerPackage;
3438        }
3439    }
3440
3441    /**
3442     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3443     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3444     * @param checkShell TODO(yamasani):
3445     * @param message the message to log on security exception
3446     */
3447    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3448            boolean checkShell, String message) {
3449        if (userId < 0) {
3450            throw new IllegalArgumentException("Invalid userId " + userId);
3451        }
3452        if (checkShell) {
3453            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3454        }
3455        if (userId == UserHandle.getUserId(callingUid)) return;
3456        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3457            if (requireFullPermission) {
3458                mContext.enforceCallingOrSelfPermission(
3459                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3460            } else {
3461                try {
3462                    mContext.enforceCallingOrSelfPermission(
3463                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3464                } catch (SecurityException se) {
3465                    mContext.enforceCallingOrSelfPermission(
3466                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3467                }
3468            }
3469        }
3470    }
3471
3472    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3473        if (callingUid == Process.SHELL_UID) {
3474            if (userHandle >= 0
3475                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3476                throw new SecurityException("Shell does not have permission to access user "
3477                        + userHandle);
3478            } else if (userHandle < 0) {
3479                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3480                        + Debug.getCallers(3));
3481            }
3482        }
3483    }
3484
3485    private BasePermission findPermissionTreeLP(String permName) {
3486        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3487            if (permName.startsWith(bp.name) &&
3488                    permName.length() > bp.name.length() &&
3489                    permName.charAt(bp.name.length()) == '.') {
3490                return bp;
3491            }
3492        }
3493        return null;
3494    }
3495
3496    private BasePermission checkPermissionTreeLP(String permName) {
3497        if (permName != null) {
3498            BasePermission bp = findPermissionTreeLP(permName);
3499            if (bp != null) {
3500                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3501                    return bp;
3502                }
3503                throw new SecurityException("Calling uid "
3504                        + Binder.getCallingUid()
3505                        + " is not allowed to add to permission tree "
3506                        + bp.name + " owned by uid " + bp.uid);
3507            }
3508        }
3509        throw new SecurityException("No permission tree found for " + permName);
3510    }
3511
3512    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3513        if (s1 == null) {
3514            return s2 == null;
3515        }
3516        if (s2 == null) {
3517            return false;
3518        }
3519        if (s1.getClass() != s2.getClass()) {
3520            return false;
3521        }
3522        return s1.equals(s2);
3523    }
3524
3525    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3526        if (pi1.icon != pi2.icon) return false;
3527        if (pi1.logo != pi2.logo) return false;
3528        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3529        if (!compareStrings(pi1.name, pi2.name)) return false;
3530        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3531        // We'll take care of setting this one.
3532        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3533        // These are not currently stored in settings.
3534        //if (!compareStrings(pi1.group, pi2.group)) return false;
3535        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3536        //if (pi1.labelRes != pi2.labelRes) return false;
3537        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3538        return true;
3539    }
3540
3541    int permissionInfoFootprint(PermissionInfo info) {
3542        int size = info.name.length();
3543        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3544        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3545        return size;
3546    }
3547
3548    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3549        int size = 0;
3550        for (BasePermission perm : mSettings.mPermissions.values()) {
3551            if (perm.uid == tree.uid) {
3552                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3553            }
3554        }
3555        return size;
3556    }
3557
3558    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3559        // We calculate the max size of permissions defined by this uid and throw
3560        // if that plus the size of 'info' would exceed our stated maximum.
3561        if (tree.uid != Process.SYSTEM_UID) {
3562            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3563            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3564                throw new SecurityException("Permission tree size cap exceeded");
3565            }
3566        }
3567    }
3568
3569    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3570        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3571            throw new SecurityException("Label must be specified in permission");
3572        }
3573        BasePermission tree = checkPermissionTreeLP(info.name);
3574        BasePermission bp = mSettings.mPermissions.get(info.name);
3575        boolean added = bp == null;
3576        boolean changed = true;
3577        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3578        if (added) {
3579            enforcePermissionCapLocked(info, tree);
3580            bp = new BasePermission(info.name, tree.sourcePackage,
3581                    BasePermission.TYPE_DYNAMIC);
3582        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3583            throw new SecurityException(
3584                    "Not allowed to modify non-dynamic permission "
3585                    + info.name);
3586        } else {
3587            if (bp.protectionLevel == fixedLevel
3588                    && bp.perm.owner.equals(tree.perm.owner)
3589                    && bp.uid == tree.uid
3590                    && comparePermissionInfos(bp.perm.info, info)) {
3591                changed = false;
3592            }
3593        }
3594        bp.protectionLevel = fixedLevel;
3595        info = new PermissionInfo(info);
3596        info.protectionLevel = fixedLevel;
3597        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3598        bp.perm.info.packageName = tree.perm.info.packageName;
3599        bp.uid = tree.uid;
3600        if (added) {
3601            mSettings.mPermissions.put(info.name, bp);
3602        }
3603        if (changed) {
3604            if (!async) {
3605                mSettings.writeLPr();
3606            } else {
3607                scheduleWriteSettingsLocked();
3608            }
3609        }
3610        return added;
3611    }
3612
3613    @Override
3614    public boolean addPermission(PermissionInfo info) {
3615        synchronized (mPackages) {
3616            return addPermissionLocked(info, false);
3617        }
3618    }
3619
3620    @Override
3621    public boolean addPermissionAsync(PermissionInfo info) {
3622        synchronized (mPackages) {
3623            return addPermissionLocked(info, true);
3624        }
3625    }
3626
3627    @Override
3628    public void removePermission(String name) {
3629        synchronized (mPackages) {
3630            checkPermissionTreeLP(name);
3631            BasePermission bp = mSettings.mPermissions.get(name);
3632            if (bp != null) {
3633                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3634                    throw new SecurityException(
3635                            "Not allowed to modify non-dynamic permission "
3636                            + name);
3637                }
3638                mSettings.mPermissions.remove(name);
3639                mSettings.writeLPr();
3640            }
3641        }
3642    }
3643
3644    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3645            BasePermission bp) {
3646        int index = pkg.requestedPermissions.indexOf(bp.name);
3647        if (index == -1) {
3648            throw new SecurityException("Package " + pkg.packageName
3649                    + " has not requested permission " + bp.name);
3650        }
3651        if (!bp.isRuntime() && !bp.isDevelopment()) {
3652            throw new SecurityException("Permission " + bp.name
3653                    + " is not a changeable permission type");
3654        }
3655    }
3656
3657    @Override
3658    public void grantRuntimePermission(String packageName, String name, final int userId) {
3659        if (!sUserManager.exists(userId)) {
3660            Log.e(TAG, "No such user:" + userId);
3661            return;
3662        }
3663
3664        mContext.enforceCallingOrSelfPermission(
3665                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3666                "grantRuntimePermission");
3667
3668        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3669                "grantRuntimePermission");
3670
3671        final int uid;
3672        final SettingBase sb;
3673
3674        synchronized (mPackages) {
3675            final PackageParser.Package pkg = mPackages.get(packageName);
3676            if (pkg == null) {
3677                throw new IllegalArgumentException("Unknown package: " + packageName);
3678            }
3679
3680            final BasePermission bp = mSettings.mPermissions.get(name);
3681            if (bp == null) {
3682                throw new IllegalArgumentException("Unknown permission: " + name);
3683            }
3684
3685            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3686
3687            // If a permission review is required for legacy apps we represent
3688            // their permissions as always granted runtime ones since we need
3689            // to keep the review required permission flag per user while an
3690            // install permission's state is shared across all users.
3691            if (Build.PERMISSIONS_REVIEW_REQUIRED
3692                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3693                    && bp.isRuntime()) {
3694                return;
3695            }
3696
3697            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3698            sb = (SettingBase) pkg.mExtras;
3699            if (sb == null) {
3700                throw new IllegalArgumentException("Unknown package: " + packageName);
3701            }
3702
3703            final PermissionsState permissionsState = sb.getPermissionsState();
3704
3705            final int flags = permissionsState.getPermissionFlags(name, userId);
3706            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3707                throw new SecurityException("Cannot grant system fixed permission: "
3708                        + name + " for package: " + packageName);
3709            }
3710
3711            if (bp.isDevelopment()) {
3712                // Development permissions must be handled specially, since they are not
3713                // normal runtime permissions.  For now they apply to all users.
3714                if (permissionsState.grantInstallPermission(bp) !=
3715                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3716                    scheduleWriteSettingsLocked();
3717                }
3718                return;
3719            }
3720
3721            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3722                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3723                return;
3724            }
3725
3726            final int result = permissionsState.grantRuntimePermission(bp, userId);
3727            switch (result) {
3728                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3729                    return;
3730                }
3731
3732                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3733                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3734                    mHandler.post(new Runnable() {
3735                        @Override
3736                        public void run() {
3737                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3738                        }
3739                    });
3740                }
3741                break;
3742            }
3743
3744            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3745
3746            // Not critical if that is lost - app has to request again.
3747            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3748        }
3749
3750        // Only need to do this if user is initialized. Otherwise it's a new user
3751        // and there are no processes running as the user yet and there's no need
3752        // to make an expensive call to remount processes for the changed permissions.
3753        if (READ_EXTERNAL_STORAGE.equals(name)
3754                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3755            final long token = Binder.clearCallingIdentity();
3756            try {
3757                if (sUserManager.isInitialized(userId)) {
3758                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3759                            MountServiceInternal.class);
3760                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3761                }
3762            } finally {
3763                Binder.restoreCallingIdentity(token);
3764            }
3765        }
3766    }
3767
3768    @Override
3769    public void revokeRuntimePermission(String packageName, String name, int userId) {
3770        if (!sUserManager.exists(userId)) {
3771            Log.e(TAG, "No such user:" + userId);
3772            return;
3773        }
3774
3775        mContext.enforceCallingOrSelfPermission(
3776                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3777                "revokeRuntimePermission");
3778
3779        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3780                "revokeRuntimePermission");
3781
3782        final int appId;
3783
3784        synchronized (mPackages) {
3785            final PackageParser.Package pkg = mPackages.get(packageName);
3786            if (pkg == null) {
3787                throw new IllegalArgumentException("Unknown package: " + packageName);
3788            }
3789
3790            final BasePermission bp = mSettings.mPermissions.get(name);
3791            if (bp == null) {
3792                throw new IllegalArgumentException("Unknown permission: " + name);
3793            }
3794
3795            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3796
3797            // If a permission review is required for legacy apps we represent
3798            // their permissions as always granted runtime ones since we need
3799            // to keep the review required permission flag per user while an
3800            // install permission's state is shared across all users.
3801            if (Build.PERMISSIONS_REVIEW_REQUIRED
3802                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3803                    && bp.isRuntime()) {
3804                return;
3805            }
3806
3807            SettingBase sb = (SettingBase) pkg.mExtras;
3808            if (sb == null) {
3809                throw new IllegalArgumentException("Unknown package: " + packageName);
3810            }
3811
3812            final PermissionsState permissionsState = sb.getPermissionsState();
3813
3814            final int flags = permissionsState.getPermissionFlags(name, userId);
3815            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3816                throw new SecurityException("Cannot revoke system fixed permission: "
3817                        + name + " for package: " + packageName);
3818            }
3819
3820            if (bp.isDevelopment()) {
3821                // Development permissions must be handled specially, since they are not
3822                // normal runtime permissions.  For now they apply to all users.
3823                if (permissionsState.revokeInstallPermission(bp) !=
3824                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3825                    scheduleWriteSettingsLocked();
3826                }
3827                return;
3828            }
3829
3830            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3831                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3832                return;
3833            }
3834
3835            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3836
3837            // Critical, after this call app should never have the permission.
3838            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3839
3840            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3841        }
3842
3843        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3844    }
3845
3846    @Override
3847    public void resetRuntimePermissions() {
3848        mContext.enforceCallingOrSelfPermission(
3849                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3850                "revokeRuntimePermission");
3851
3852        int callingUid = Binder.getCallingUid();
3853        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3854            mContext.enforceCallingOrSelfPermission(
3855                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3856                    "resetRuntimePermissions");
3857        }
3858
3859        synchronized (mPackages) {
3860            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3861            for (int userId : UserManagerService.getInstance().getUserIds()) {
3862                final int packageCount = mPackages.size();
3863                for (int i = 0; i < packageCount; i++) {
3864                    PackageParser.Package pkg = mPackages.valueAt(i);
3865                    if (!(pkg.mExtras instanceof PackageSetting)) {
3866                        continue;
3867                    }
3868                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3869                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3870                }
3871            }
3872        }
3873    }
3874
3875    @Override
3876    public int getPermissionFlags(String name, String packageName, int userId) {
3877        if (!sUserManager.exists(userId)) {
3878            return 0;
3879        }
3880
3881        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3882
3883        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3884                "getPermissionFlags");
3885
3886        synchronized (mPackages) {
3887            final PackageParser.Package pkg = mPackages.get(packageName);
3888            if (pkg == null) {
3889                throw new IllegalArgumentException("Unknown package: " + packageName);
3890            }
3891
3892            final BasePermission bp = mSettings.mPermissions.get(name);
3893            if (bp == null) {
3894                throw new IllegalArgumentException("Unknown permission: " + name);
3895            }
3896
3897            SettingBase sb = (SettingBase) pkg.mExtras;
3898            if (sb == null) {
3899                throw new IllegalArgumentException("Unknown package: " + packageName);
3900            }
3901
3902            PermissionsState permissionsState = sb.getPermissionsState();
3903            return permissionsState.getPermissionFlags(name, userId);
3904        }
3905    }
3906
3907    @Override
3908    public void updatePermissionFlags(String name, String packageName, int flagMask,
3909            int flagValues, int userId) {
3910        if (!sUserManager.exists(userId)) {
3911            return;
3912        }
3913
3914        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3915
3916        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3917                "updatePermissionFlags");
3918
3919        // Only the system can change these flags and nothing else.
3920        if (getCallingUid() != Process.SYSTEM_UID) {
3921            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3922            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3923            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3924            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3925            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3926        }
3927
3928        synchronized (mPackages) {
3929            final PackageParser.Package pkg = mPackages.get(packageName);
3930            if (pkg == null) {
3931                throw new IllegalArgumentException("Unknown package: " + packageName);
3932            }
3933
3934            final BasePermission bp = mSettings.mPermissions.get(name);
3935            if (bp == null) {
3936                throw new IllegalArgumentException("Unknown permission: " + name);
3937            }
3938
3939            SettingBase sb = (SettingBase) pkg.mExtras;
3940            if (sb == null) {
3941                throw new IllegalArgumentException("Unknown package: " + packageName);
3942            }
3943
3944            PermissionsState permissionsState = sb.getPermissionsState();
3945
3946            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3947
3948            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3949                // Install and runtime permissions are stored in different places,
3950                // so figure out what permission changed and persist the change.
3951                if (permissionsState.getInstallPermissionState(name) != null) {
3952                    scheduleWriteSettingsLocked();
3953                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3954                        || hadState) {
3955                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3956                }
3957            }
3958        }
3959    }
3960
3961    /**
3962     * Update the permission flags for all packages and runtime permissions of a user in order
3963     * to allow device or profile owner to remove POLICY_FIXED.
3964     */
3965    @Override
3966    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3967        if (!sUserManager.exists(userId)) {
3968            return;
3969        }
3970
3971        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3972
3973        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3974                "updatePermissionFlagsForAllApps");
3975
3976        // Only the system can change system fixed flags.
3977        if (getCallingUid() != Process.SYSTEM_UID) {
3978            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3979            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3980        }
3981
3982        synchronized (mPackages) {
3983            boolean changed = false;
3984            final int packageCount = mPackages.size();
3985            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3986                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3987                SettingBase sb = (SettingBase) pkg.mExtras;
3988                if (sb == null) {
3989                    continue;
3990                }
3991                PermissionsState permissionsState = sb.getPermissionsState();
3992                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3993                        userId, flagMask, flagValues);
3994            }
3995            if (changed) {
3996                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3997            }
3998        }
3999    }
4000
4001    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4002        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4003                != PackageManager.PERMISSION_GRANTED
4004            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4005                != PackageManager.PERMISSION_GRANTED) {
4006            throw new SecurityException(message + " requires "
4007                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4008                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4009        }
4010    }
4011
4012    @Override
4013    public boolean shouldShowRequestPermissionRationale(String permissionName,
4014            String packageName, int userId) {
4015        if (UserHandle.getCallingUserId() != userId) {
4016            mContext.enforceCallingPermission(
4017                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4018                    "canShowRequestPermissionRationale for user " + userId);
4019        }
4020
4021        final int uid = getPackageUid(packageName, userId);
4022        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4023            return false;
4024        }
4025
4026        if (checkPermission(permissionName, packageName, userId)
4027                == PackageManager.PERMISSION_GRANTED) {
4028            return false;
4029        }
4030
4031        final int flags;
4032
4033        final long identity = Binder.clearCallingIdentity();
4034        try {
4035            flags = getPermissionFlags(permissionName,
4036                    packageName, userId);
4037        } finally {
4038            Binder.restoreCallingIdentity(identity);
4039        }
4040
4041        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4042                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4043                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4044
4045        if ((flags & fixedFlags) != 0) {
4046            return false;
4047        }
4048
4049        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4050    }
4051
4052    @Override
4053    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4054        mContext.enforceCallingOrSelfPermission(
4055                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4056                "addOnPermissionsChangeListener");
4057
4058        synchronized (mPackages) {
4059            mOnPermissionChangeListeners.addListenerLocked(listener);
4060        }
4061    }
4062
4063    @Override
4064    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4065        synchronized (mPackages) {
4066            mOnPermissionChangeListeners.removeListenerLocked(listener);
4067        }
4068    }
4069
4070    @Override
4071    public boolean isProtectedBroadcast(String actionName) {
4072        synchronized (mPackages) {
4073            if (mProtectedBroadcasts.contains(actionName)) {
4074                return true;
4075            } else if (actionName != null) {
4076                // TODO: remove these terrible hacks
4077                if (actionName.startsWith("android.net.netmon.lingerExpired")
4078                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4079                    return true;
4080                }
4081            }
4082        }
4083        return false;
4084    }
4085
4086    @Override
4087    public int checkSignatures(String pkg1, String pkg2) {
4088        synchronized (mPackages) {
4089            final PackageParser.Package p1 = mPackages.get(pkg1);
4090            final PackageParser.Package p2 = mPackages.get(pkg2);
4091            if (p1 == null || p1.mExtras == null
4092                    || p2 == null || p2.mExtras == null) {
4093                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4094            }
4095            return compareSignatures(p1.mSignatures, p2.mSignatures);
4096        }
4097    }
4098
4099    @Override
4100    public int checkUidSignatures(int uid1, int uid2) {
4101        // Map to base uids.
4102        uid1 = UserHandle.getAppId(uid1);
4103        uid2 = UserHandle.getAppId(uid2);
4104        // reader
4105        synchronized (mPackages) {
4106            Signature[] s1;
4107            Signature[] s2;
4108            Object obj = mSettings.getUserIdLPr(uid1);
4109            if (obj != null) {
4110                if (obj instanceof SharedUserSetting) {
4111                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4112                } else if (obj instanceof PackageSetting) {
4113                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4114                } else {
4115                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4116                }
4117            } else {
4118                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4119            }
4120            obj = mSettings.getUserIdLPr(uid2);
4121            if (obj != null) {
4122                if (obj instanceof SharedUserSetting) {
4123                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4124                } else if (obj instanceof PackageSetting) {
4125                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4126                } else {
4127                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4128                }
4129            } else {
4130                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4131            }
4132            return compareSignatures(s1, s2);
4133        }
4134    }
4135
4136    private void killUid(int appId, int userId, String reason) {
4137        final long identity = Binder.clearCallingIdentity();
4138        try {
4139            IActivityManager am = ActivityManagerNative.getDefault();
4140            if (am != null) {
4141                try {
4142                    am.killUid(appId, userId, reason);
4143                } catch (RemoteException e) {
4144                    /* ignore - same process */
4145                }
4146            }
4147        } finally {
4148            Binder.restoreCallingIdentity(identity);
4149        }
4150    }
4151
4152    /**
4153     * Compares two sets of signatures. Returns:
4154     * <br />
4155     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4156     * <br />
4157     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4158     * <br />
4159     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4160     * <br />
4161     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4162     * <br />
4163     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4164     */
4165    static int compareSignatures(Signature[] s1, Signature[] s2) {
4166        if (s1 == null) {
4167            return s2 == null
4168                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4169                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4170        }
4171
4172        if (s2 == null) {
4173            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4174        }
4175
4176        if (s1.length != s2.length) {
4177            return PackageManager.SIGNATURE_NO_MATCH;
4178        }
4179
4180        // Since both signature sets are of size 1, we can compare without HashSets.
4181        if (s1.length == 1) {
4182            return s1[0].equals(s2[0]) ?
4183                    PackageManager.SIGNATURE_MATCH :
4184                    PackageManager.SIGNATURE_NO_MATCH;
4185        }
4186
4187        ArraySet<Signature> set1 = new ArraySet<Signature>();
4188        for (Signature sig : s1) {
4189            set1.add(sig);
4190        }
4191        ArraySet<Signature> set2 = new ArraySet<Signature>();
4192        for (Signature sig : s2) {
4193            set2.add(sig);
4194        }
4195        // Make sure s2 contains all signatures in s1.
4196        if (set1.equals(set2)) {
4197            return PackageManager.SIGNATURE_MATCH;
4198        }
4199        return PackageManager.SIGNATURE_NO_MATCH;
4200    }
4201
4202    /**
4203     * If the database version for this type of package (internal storage or
4204     * external storage) is less than the version where package signatures
4205     * were updated, return true.
4206     */
4207    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4208        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4209        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4210    }
4211
4212    /**
4213     * Used for backward compatibility to make sure any packages with
4214     * certificate chains get upgraded to the new style. {@code existingSigs}
4215     * will be in the old format (since they were stored on disk from before the
4216     * system upgrade) and {@code scannedSigs} will be in the newer format.
4217     */
4218    private int compareSignaturesCompat(PackageSignatures existingSigs,
4219            PackageParser.Package scannedPkg) {
4220        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4221            return PackageManager.SIGNATURE_NO_MATCH;
4222        }
4223
4224        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4225        for (Signature sig : existingSigs.mSignatures) {
4226            existingSet.add(sig);
4227        }
4228        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4229        for (Signature sig : scannedPkg.mSignatures) {
4230            try {
4231                Signature[] chainSignatures = sig.getChainSignatures();
4232                for (Signature chainSig : chainSignatures) {
4233                    scannedCompatSet.add(chainSig);
4234                }
4235            } catch (CertificateEncodingException e) {
4236                scannedCompatSet.add(sig);
4237            }
4238        }
4239        /*
4240         * Make sure the expanded scanned set contains all signatures in the
4241         * existing one.
4242         */
4243        if (scannedCompatSet.equals(existingSet)) {
4244            // Migrate the old signatures to the new scheme.
4245            existingSigs.assignSignatures(scannedPkg.mSignatures);
4246            // The new KeySets will be re-added later in the scanning process.
4247            synchronized (mPackages) {
4248                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4249            }
4250            return PackageManager.SIGNATURE_MATCH;
4251        }
4252        return PackageManager.SIGNATURE_NO_MATCH;
4253    }
4254
4255    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4256        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4257        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4258    }
4259
4260    private int compareSignaturesRecover(PackageSignatures existingSigs,
4261            PackageParser.Package scannedPkg) {
4262        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4263            return PackageManager.SIGNATURE_NO_MATCH;
4264        }
4265
4266        String msg = null;
4267        try {
4268            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4269                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4270                        + scannedPkg.packageName);
4271                return PackageManager.SIGNATURE_MATCH;
4272            }
4273        } catch (CertificateException e) {
4274            msg = e.getMessage();
4275        }
4276
4277        logCriticalInfo(Log.INFO,
4278                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4279        return PackageManager.SIGNATURE_NO_MATCH;
4280    }
4281
4282    @Override
4283    public String[] getPackagesForUid(int uid) {
4284        uid = UserHandle.getAppId(uid);
4285        // reader
4286        synchronized (mPackages) {
4287            Object obj = mSettings.getUserIdLPr(uid);
4288            if (obj instanceof SharedUserSetting) {
4289                final SharedUserSetting sus = (SharedUserSetting) obj;
4290                final int N = sus.packages.size();
4291                final String[] res = new String[N];
4292                final Iterator<PackageSetting> it = sus.packages.iterator();
4293                int i = 0;
4294                while (it.hasNext()) {
4295                    res[i++] = it.next().name;
4296                }
4297                return res;
4298            } else if (obj instanceof PackageSetting) {
4299                final PackageSetting ps = (PackageSetting) obj;
4300                return new String[] { ps.name };
4301            }
4302        }
4303        return null;
4304    }
4305
4306    @Override
4307    public String getNameForUid(int uid) {
4308        // reader
4309        synchronized (mPackages) {
4310            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4311            if (obj instanceof SharedUserSetting) {
4312                final SharedUserSetting sus = (SharedUserSetting) obj;
4313                return sus.name + ":" + sus.userId;
4314            } else if (obj instanceof PackageSetting) {
4315                final PackageSetting ps = (PackageSetting) obj;
4316                return ps.name;
4317            }
4318        }
4319        return null;
4320    }
4321
4322    @Override
4323    public int getUidForSharedUser(String sharedUserName) {
4324        if(sharedUserName == null) {
4325            return -1;
4326        }
4327        // reader
4328        synchronized (mPackages) {
4329            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4330            if (suid == null) {
4331                return -1;
4332            }
4333            return suid.userId;
4334        }
4335    }
4336
4337    @Override
4338    public int getFlagsForUid(int uid) {
4339        synchronized (mPackages) {
4340            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4341            if (obj instanceof SharedUserSetting) {
4342                final SharedUserSetting sus = (SharedUserSetting) obj;
4343                return sus.pkgFlags;
4344            } else if (obj instanceof PackageSetting) {
4345                final PackageSetting ps = (PackageSetting) obj;
4346                return ps.pkgFlags;
4347            }
4348        }
4349        return 0;
4350    }
4351
4352    @Override
4353    public int getPrivateFlagsForUid(int uid) {
4354        synchronized (mPackages) {
4355            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4356            if (obj instanceof SharedUserSetting) {
4357                final SharedUserSetting sus = (SharedUserSetting) obj;
4358                return sus.pkgPrivateFlags;
4359            } else if (obj instanceof PackageSetting) {
4360                final PackageSetting ps = (PackageSetting) obj;
4361                return ps.pkgPrivateFlags;
4362            }
4363        }
4364        return 0;
4365    }
4366
4367    @Override
4368    public boolean isUidPrivileged(int uid) {
4369        uid = UserHandle.getAppId(uid);
4370        // reader
4371        synchronized (mPackages) {
4372            Object obj = mSettings.getUserIdLPr(uid);
4373            if (obj instanceof SharedUserSetting) {
4374                final SharedUserSetting sus = (SharedUserSetting) obj;
4375                final Iterator<PackageSetting> it = sus.packages.iterator();
4376                while (it.hasNext()) {
4377                    if (it.next().isPrivileged()) {
4378                        return true;
4379                    }
4380                }
4381            } else if (obj instanceof PackageSetting) {
4382                final PackageSetting ps = (PackageSetting) obj;
4383                return ps.isPrivileged();
4384            }
4385        }
4386        return false;
4387    }
4388
4389    @Override
4390    public String[] getAppOpPermissionPackages(String permissionName) {
4391        synchronized (mPackages) {
4392            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4393            if (pkgs == null) {
4394                return null;
4395            }
4396            return pkgs.toArray(new String[pkgs.size()]);
4397        }
4398    }
4399
4400    @Override
4401    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4402            int flags, int userId) {
4403        if (!sUserManager.exists(userId)) return null;
4404        flags = augmentFlagsForUser(flags, userId);
4405        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4406        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4407        final ResolveInfo bestChoice =
4408                chooseBestActivity(intent, resolvedType, flags, query, userId);
4409
4410        if (isEphemeralAllowed(intent, query, userId)) {
4411            final EphemeralResolveInfo ai =
4412                    getEphemeralResolveInfo(intent, resolvedType, userId);
4413            if (ai != null) {
4414                if (DEBUG_EPHEMERAL) {
4415                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4416                }
4417                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4418                bestChoice.ephemeralResolveInfo = ai;
4419            }
4420        }
4421        return bestChoice;
4422    }
4423
4424    @Override
4425    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4426            IntentFilter filter, int match, ComponentName activity) {
4427        final int userId = UserHandle.getCallingUserId();
4428        if (DEBUG_PREFERRED) {
4429            Log.v(TAG, "setLastChosenActivity intent=" + intent
4430                + " resolvedType=" + resolvedType
4431                + " flags=" + flags
4432                + " filter=" + filter
4433                + " match=" + match
4434                + " activity=" + activity);
4435            filter.dump(new PrintStreamPrinter(System.out), "    ");
4436        }
4437        intent.setComponent(null);
4438        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4439        // Find any earlier preferred or last chosen entries and nuke them
4440        findPreferredActivity(intent, resolvedType,
4441                flags, query, 0, false, true, false, userId);
4442        // Add the new activity as the last chosen for this filter
4443        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4444                "Setting last chosen");
4445    }
4446
4447    @Override
4448    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4449        final int userId = UserHandle.getCallingUserId();
4450        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4451        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4452        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4453                false, false, false, userId);
4454    }
4455
4456
4457    private boolean isEphemeralAllowed(
4458            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4459        // Short circuit and return early if possible.
4460        final int callingUser = UserHandle.getCallingUserId();
4461        if (callingUser != UserHandle.USER_SYSTEM) {
4462            return false;
4463        }
4464        if (mEphemeralResolverConnection == null) {
4465            return false;
4466        }
4467        if (intent.getComponent() != null) {
4468            return false;
4469        }
4470        if (intent.getPackage() != null) {
4471            return false;
4472        }
4473        final boolean isWebUri = hasWebURI(intent);
4474        if (!isWebUri) {
4475            return false;
4476        }
4477        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4478        synchronized (mPackages) {
4479            final int count = resolvedActivites.size();
4480            for (int n = 0; n < count; n++) {
4481                ResolveInfo info = resolvedActivites.get(n);
4482                String packageName = info.activityInfo.packageName;
4483                PackageSetting ps = mSettings.mPackages.get(packageName);
4484                if (ps != null) {
4485                    // Try to get the status from User settings first
4486                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4487                    int status = (int) (packedStatus >> 32);
4488                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4489                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4490                        if (DEBUG_EPHEMERAL) {
4491                            Slog.v(TAG, "DENY ephemeral apps;"
4492                                + " pkg: " + packageName + ", status: " + status);
4493                        }
4494                        return false;
4495                    }
4496                }
4497            }
4498        }
4499        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4500        return true;
4501    }
4502
4503    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4504            int userId) {
4505        MessageDigest digest = null;
4506        try {
4507            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4508        } catch (NoSuchAlgorithmException e) {
4509            // If we can't create a digest, ignore ephemeral apps.
4510            return null;
4511        }
4512
4513        final byte[] hostBytes = intent.getData().getHost().getBytes();
4514        final byte[] digestBytes = digest.digest(hostBytes);
4515        int shaPrefix =
4516                digestBytes[0] << 24
4517                | digestBytes[1] << 16
4518                | digestBytes[2] << 8
4519                | digestBytes[3] << 0;
4520        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4521                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4522        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4523            // No hash prefix match; there are no ephemeral apps for this domain.
4524            return null;
4525        }
4526        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4527            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4528            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4529                continue;
4530            }
4531            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4532            // No filters; this should never happen.
4533            if (filters.isEmpty()) {
4534                continue;
4535            }
4536            // We have a domain match; resolve the filters to see if anything matches.
4537            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4538            for (int j = filters.size() - 1; j >= 0; --j) {
4539                final EphemeralResolveIntentInfo intentInfo =
4540                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4541                ephemeralResolver.addFilter(intentInfo);
4542            }
4543            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4544                    intent, resolvedType, false /*defaultOnly*/, userId);
4545            if (!matchedResolveInfoList.isEmpty()) {
4546                return matchedResolveInfoList.get(0);
4547            }
4548        }
4549        // Hash or filter mis-match; no ephemeral apps for this domain.
4550        return null;
4551    }
4552
4553    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4554            int flags, List<ResolveInfo> query, int userId) {
4555        if (query != null) {
4556            final int N = query.size();
4557            if (N == 1) {
4558                return query.get(0);
4559            } else if (N > 1) {
4560                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4561                // If there is more than one activity with the same priority,
4562                // then let the user decide between them.
4563                ResolveInfo r0 = query.get(0);
4564                ResolveInfo r1 = query.get(1);
4565                if (DEBUG_INTENT_MATCHING || debug) {
4566                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4567                            + r1.activityInfo.name + "=" + r1.priority);
4568                }
4569                // If the first activity has a higher priority, or a different
4570                // default, then it is always desirable to pick it.
4571                if (r0.priority != r1.priority
4572                        || r0.preferredOrder != r1.preferredOrder
4573                        || r0.isDefault != r1.isDefault) {
4574                    return query.get(0);
4575                }
4576                // If we have saved a preference for a preferred activity for
4577                // this Intent, use that.
4578                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4579                        flags, query, r0.priority, true, false, debug, userId);
4580                if (ri != null) {
4581                    return ri;
4582                }
4583                ri = new ResolveInfo(mResolveInfo);
4584                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4585                ri.activityInfo.applicationInfo = new ApplicationInfo(
4586                        ri.activityInfo.applicationInfo);
4587                if (userId != 0) {
4588                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4589                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4590                }
4591                // Make sure that the resolver is displayable in car mode
4592                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4593                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4594                return ri;
4595            }
4596        }
4597        return null;
4598    }
4599
4600    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4601            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4602        final int N = query.size();
4603        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4604                .get(userId);
4605        // Get the list of persistent preferred activities that handle the intent
4606        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4607        List<PersistentPreferredActivity> pprefs = ppir != null
4608                ? ppir.queryIntent(intent, resolvedType,
4609                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4610                : null;
4611        if (pprefs != null && pprefs.size() > 0) {
4612            final int M = pprefs.size();
4613            for (int i=0; i<M; i++) {
4614                final PersistentPreferredActivity ppa = pprefs.get(i);
4615                if (DEBUG_PREFERRED || debug) {
4616                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4617                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4618                            + "\n  component=" + ppa.mComponent);
4619                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4620                }
4621                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4622                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4623                if (DEBUG_PREFERRED || debug) {
4624                    Slog.v(TAG, "Found persistent preferred activity:");
4625                    if (ai != null) {
4626                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4627                    } else {
4628                        Slog.v(TAG, "  null");
4629                    }
4630                }
4631                if (ai == null) {
4632                    // This previously registered persistent preferred activity
4633                    // component is no longer known. Ignore it and do NOT remove it.
4634                    continue;
4635                }
4636                for (int j=0; j<N; j++) {
4637                    final ResolveInfo ri = query.get(j);
4638                    if (!ri.activityInfo.applicationInfo.packageName
4639                            .equals(ai.applicationInfo.packageName)) {
4640                        continue;
4641                    }
4642                    if (!ri.activityInfo.name.equals(ai.name)) {
4643                        continue;
4644                    }
4645                    //  Found a persistent preference that can handle the intent.
4646                    if (DEBUG_PREFERRED || debug) {
4647                        Slog.v(TAG, "Returning persistent preferred activity: " +
4648                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4649                    }
4650                    return ri;
4651                }
4652            }
4653        }
4654        return null;
4655    }
4656
4657    // TODO: handle preferred activities missing while user has amnesia
4658    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4659            List<ResolveInfo> query, int priority, boolean always,
4660            boolean removeMatches, boolean debug, int userId) {
4661        if (!sUserManager.exists(userId)) return null;
4662        flags = augmentFlagsForUser(flags, userId);
4663        // writer
4664        synchronized (mPackages) {
4665            if (intent.getSelector() != null) {
4666                intent = intent.getSelector();
4667            }
4668            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4669
4670            // Try to find a matching persistent preferred activity.
4671            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4672                    debug, userId);
4673
4674            // If a persistent preferred activity matched, use it.
4675            if (pri != null) {
4676                return pri;
4677            }
4678
4679            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4680            // Get the list of preferred activities that handle the intent
4681            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4682            List<PreferredActivity> prefs = pir != null
4683                    ? pir.queryIntent(intent, resolvedType,
4684                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4685                    : null;
4686            if (prefs != null && prefs.size() > 0) {
4687                boolean changed = false;
4688                try {
4689                    // First figure out how good the original match set is.
4690                    // We will only allow preferred activities that came
4691                    // from the same match quality.
4692                    int match = 0;
4693
4694                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4695
4696                    final int N = query.size();
4697                    for (int j=0; j<N; j++) {
4698                        final ResolveInfo ri = query.get(j);
4699                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4700                                + ": 0x" + Integer.toHexString(match));
4701                        if (ri.match > match) {
4702                            match = ri.match;
4703                        }
4704                    }
4705
4706                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4707                            + Integer.toHexString(match));
4708
4709                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4710                    final int M = prefs.size();
4711                    for (int i=0; i<M; i++) {
4712                        final PreferredActivity pa = prefs.get(i);
4713                        if (DEBUG_PREFERRED || debug) {
4714                            Slog.v(TAG, "Checking PreferredActivity ds="
4715                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4716                                    + "\n  component=" + pa.mPref.mComponent);
4717                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4718                        }
4719                        if (pa.mPref.mMatch != match) {
4720                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4721                                    + Integer.toHexString(pa.mPref.mMatch));
4722                            continue;
4723                        }
4724                        // If it's not an "always" type preferred activity and that's what we're
4725                        // looking for, skip it.
4726                        if (always && !pa.mPref.mAlways) {
4727                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4728                            continue;
4729                        }
4730                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4731                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4732                        if (DEBUG_PREFERRED || debug) {
4733                            Slog.v(TAG, "Found preferred activity:");
4734                            if (ai != null) {
4735                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4736                            } else {
4737                                Slog.v(TAG, "  null");
4738                            }
4739                        }
4740                        if (ai == null) {
4741                            // This previously registered preferred activity
4742                            // component is no longer known.  Most likely an update
4743                            // to the app was installed and in the new version this
4744                            // component no longer exists.  Clean it up by removing
4745                            // it from the preferred activities list, and skip it.
4746                            Slog.w(TAG, "Removing dangling preferred activity: "
4747                                    + pa.mPref.mComponent);
4748                            pir.removeFilter(pa);
4749                            changed = true;
4750                            continue;
4751                        }
4752                        for (int j=0; j<N; j++) {
4753                            final ResolveInfo ri = query.get(j);
4754                            if (!ri.activityInfo.applicationInfo.packageName
4755                                    .equals(ai.applicationInfo.packageName)) {
4756                                continue;
4757                            }
4758                            if (!ri.activityInfo.name.equals(ai.name)) {
4759                                continue;
4760                            }
4761
4762                            if (removeMatches) {
4763                                pir.removeFilter(pa);
4764                                changed = true;
4765                                if (DEBUG_PREFERRED) {
4766                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4767                                }
4768                                break;
4769                            }
4770
4771                            // Okay we found a previously set preferred or last chosen app.
4772                            // If the result set is different from when this
4773                            // was created, we need to clear it and re-ask the
4774                            // user their preference, if we're looking for an "always" type entry.
4775                            if (always && !pa.mPref.sameSet(query)) {
4776                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4777                                        + intent + " type " + resolvedType);
4778                                if (DEBUG_PREFERRED) {
4779                                    Slog.v(TAG, "Removing preferred activity since set changed "
4780                                            + pa.mPref.mComponent);
4781                                }
4782                                pir.removeFilter(pa);
4783                                // Re-add the filter as a "last chosen" entry (!always)
4784                                PreferredActivity lastChosen = new PreferredActivity(
4785                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4786                                pir.addFilter(lastChosen);
4787                                changed = true;
4788                                return null;
4789                            }
4790
4791                            // Yay! Either the set matched or we're looking for the last chosen
4792                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4793                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4794                            return ri;
4795                        }
4796                    }
4797                } finally {
4798                    if (changed) {
4799                        if (DEBUG_PREFERRED) {
4800                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4801                        }
4802                        scheduleWritePackageRestrictionsLocked(userId);
4803                    }
4804                }
4805            }
4806        }
4807        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4808        return null;
4809    }
4810
4811    /*
4812     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4813     */
4814    @Override
4815    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4816            int targetUserId) {
4817        mContext.enforceCallingOrSelfPermission(
4818                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4819        List<CrossProfileIntentFilter> matches =
4820                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4821        if (matches != null) {
4822            int size = matches.size();
4823            for (int i = 0; i < size; i++) {
4824                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4825            }
4826        }
4827        if (hasWebURI(intent)) {
4828            // cross-profile app linking works only towards the parent.
4829            final UserInfo parent = getProfileParent(sourceUserId);
4830            synchronized(mPackages) {
4831                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4832                        intent, resolvedType, 0, sourceUserId, parent.id);
4833                return xpDomainInfo != null;
4834            }
4835        }
4836        return false;
4837    }
4838
4839    private UserInfo getProfileParent(int userId) {
4840        final long identity = Binder.clearCallingIdentity();
4841        try {
4842            return sUserManager.getProfileParent(userId);
4843        } finally {
4844            Binder.restoreCallingIdentity(identity);
4845        }
4846    }
4847
4848    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4849            String resolvedType, int userId) {
4850        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4851        if (resolver != null) {
4852            return resolver.queryIntent(intent, resolvedType, false, userId);
4853        }
4854        return null;
4855    }
4856
4857    @Override
4858    public List<ResolveInfo> queryIntentActivities(Intent intent,
4859            String resolvedType, int flags, int userId) {
4860        if (!sUserManager.exists(userId)) return Collections.emptyList();
4861        flags = augmentFlagsForUser(flags, userId);
4862        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4863        ComponentName comp = intent.getComponent();
4864        if (comp == null) {
4865            if (intent.getSelector() != null) {
4866                intent = intent.getSelector();
4867                comp = intent.getComponent();
4868            }
4869        }
4870
4871        if (comp != null) {
4872            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4873            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4874            if (ai != null) {
4875                final ResolveInfo ri = new ResolveInfo();
4876                ri.activityInfo = ai;
4877                list.add(ri);
4878            }
4879            return list;
4880        }
4881
4882        // reader
4883        synchronized (mPackages) {
4884            final String pkgName = intent.getPackage();
4885            if (pkgName == null) {
4886                List<CrossProfileIntentFilter> matchingFilters =
4887                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4888                // Check for results that need to skip the current profile.
4889                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4890                        resolvedType, flags, userId);
4891                if (xpResolveInfo != null) {
4892                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4893                    result.add(xpResolveInfo);
4894                    return filterIfNotSystemUser(result, userId);
4895                }
4896
4897                // Check for results in the current profile.
4898                List<ResolveInfo> result = mActivities.queryIntent(
4899                        intent, resolvedType, flags, userId);
4900                result = filterIfNotSystemUser(result, userId);
4901
4902                // Check for cross profile results.
4903                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4904                xpResolveInfo = queryCrossProfileIntents(
4905                        matchingFilters, intent, resolvedType, flags, userId,
4906                        hasNonNegativePriorityResult);
4907                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4908                    boolean isVisibleToUser = filterIfNotSystemUser(
4909                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4910                    if (isVisibleToUser) {
4911                        result.add(xpResolveInfo);
4912                        Collections.sort(result, mResolvePrioritySorter);
4913                    }
4914                }
4915                if (hasWebURI(intent)) {
4916                    CrossProfileDomainInfo xpDomainInfo = null;
4917                    final UserInfo parent = getProfileParent(userId);
4918                    if (parent != null) {
4919                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4920                                flags, userId, parent.id);
4921                    }
4922                    if (xpDomainInfo != null) {
4923                        if (xpResolveInfo != null) {
4924                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4925                            // in the result.
4926                            result.remove(xpResolveInfo);
4927                        }
4928                        if (result.size() == 0) {
4929                            result.add(xpDomainInfo.resolveInfo);
4930                            return result;
4931                        }
4932                    } else if (result.size() <= 1) {
4933                        return result;
4934                    }
4935                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4936                            xpDomainInfo, userId);
4937                    Collections.sort(result, mResolvePrioritySorter);
4938                }
4939                return result;
4940            }
4941            final PackageParser.Package pkg = mPackages.get(pkgName);
4942            if (pkg != null) {
4943                return filterIfNotSystemUser(
4944                        mActivities.queryIntentForPackage(
4945                                intent, resolvedType, flags, pkg.activities, userId),
4946                        userId);
4947            }
4948            return new ArrayList<ResolveInfo>();
4949        }
4950    }
4951
4952    private static class CrossProfileDomainInfo {
4953        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4954        ResolveInfo resolveInfo;
4955        /* Best domain verification status of the activities found in the other profile */
4956        int bestDomainVerificationStatus;
4957    }
4958
4959    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4960            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4961        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4962                sourceUserId)) {
4963            return null;
4964        }
4965        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4966                resolvedType, flags, parentUserId);
4967
4968        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4969            return null;
4970        }
4971        CrossProfileDomainInfo result = null;
4972        int size = resultTargetUser.size();
4973        for (int i = 0; i < size; i++) {
4974            ResolveInfo riTargetUser = resultTargetUser.get(i);
4975            // Intent filter verification is only for filters that specify a host. So don't return
4976            // those that handle all web uris.
4977            if (riTargetUser.handleAllWebDataURI) {
4978                continue;
4979            }
4980            String packageName = riTargetUser.activityInfo.packageName;
4981            PackageSetting ps = mSettings.mPackages.get(packageName);
4982            if (ps == null) {
4983                continue;
4984            }
4985            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4986            int status = (int)(verificationState >> 32);
4987            if (result == null) {
4988                result = new CrossProfileDomainInfo();
4989                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4990                        sourceUserId, parentUserId);
4991                result.bestDomainVerificationStatus = status;
4992            } else {
4993                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4994                        result.bestDomainVerificationStatus);
4995            }
4996        }
4997        // Don't consider matches with status NEVER across profiles.
4998        if (result != null && result.bestDomainVerificationStatus
4999                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5000            return null;
5001        }
5002        return result;
5003    }
5004
5005    /**
5006     * Verification statuses are ordered from the worse to the best, except for
5007     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5008     */
5009    private int bestDomainVerificationStatus(int status1, int status2) {
5010        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5011            return status2;
5012        }
5013        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5014            return status1;
5015        }
5016        return (int) MathUtils.max(status1, status2);
5017    }
5018
5019    private boolean isUserEnabled(int userId) {
5020        long callingId = Binder.clearCallingIdentity();
5021        try {
5022            UserInfo userInfo = sUserManager.getUserInfo(userId);
5023            return userInfo != null && userInfo.isEnabled();
5024        } finally {
5025            Binder.restoreCallingIdentity(callingId);
5026        }
5027    }
5028
5029    /**
5030     * Filter out activities with systemUserOnly flag set, when current user is not System.
5031     *
5032     * @return filtered list
5033     */
5034    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5035        if (userId == UserHandle.USER_SYSTEM) {
5036            return resolveInfos;
5037        }
5038        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5039            ResolveInfo info = resolveInfos.get(i);
5040            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5041                resolveInfos.remove(i);
5042            }
5043        }
5044        return resolveInfos;
5045    }
5046
5047    /**
5048     * @param resolveInfos list of resolve infos in descending priority order
5049     * @return if the list contains a resolve info with non-negative priority
5050     */
5051    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5052        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5053    }
5054
5055    private static boolean hasWebURI(Intent intent) {
5056        if (intent.getData() == null) {
5057            return false;
5058        }
5059        final String scheme = intent.getScheme();
5060        if (TextUtils.isEmpty(scheme)) {
5061            return false;
5062        }
5063        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5064    }
5065
5066    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5067            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5068            int userId) {
5069        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5070
5071        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5072            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5073                    candidates.size());
5074        }
5075
5076        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5077        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5078        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5079        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5080        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5081        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5082
5083        synchronized (mPackages) {
5084            final int count = candidates.size();
5085            // First, try to use linked apps. Partition the candidates into four lists:
5086            // one for the final results, one for the "do not use ever", one for "undefined status"
5087            // and finally one for "browser app type".
5088            for (int n=0; n<count; n++) {
5089                ResolveInfo info = candidates.get(n);
5090                String packageName = info.activityInfo.packageName;
5091                PackageSetting ps = mSettings.mPackages.get(packageName);
5092                if (ps != null) {
5093                    // Add to the special match all list (Browser use case)
5094                    if (info.handleAllWebDataURI) {
5095                        matchAllList.add(info);
5096                        continue;
5097                    }
5098                    // Try to get the status from User settings first
5099                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5100                    int status = (int)(packedStatus >> 32);
5101                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5102                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5103                        if (DEBUG_DOMAIN_VERIFICATION) {
5104                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5105                                    + " : linkgen=" + linkGeneration);
5106                        }
5107                        // Use link-enabled generation as preferredOrder, i.e.
5108                        // prefer newly-enabled over earlier-enabled.
5109                        info.preferredOrder = linkGeneration;
5110                        alwaysList.add(info);
5111                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5112                        if (DEBUG_DOMAIN_VERIFICATION) {
5113                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5114                        }
5115                        neverList.add(info);
5116                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5117                        if (DEBUG_DOMAIN_VERIFICATION) {
5118                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5119                        }
5120                        alwaysAskList.add(info);
5121                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5122                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5123                        if (DEBUG_DOMAIN_VERIFICATION) {
5124                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5125                        }
5126                        undefinedList.add(info);
5127                    }
5128                }
5129            }
5130
5131            // We'll want to include browser possibilities in a few cases
5132            boolean includeBrowser = false;
5133
5134            // First try to add the "always" resolution(s) for the current user, if any
5135            if (alwaysList.size() > 0) {
5136                result.addAll(alwaysList);
5137            } else {
5138                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5139                result.addAll(undefinedList);
5140                // Maybe add one for the other profile.
5141                if (xpDomainInfo != null && (
5142                        xpDomainInfo.bestDomainVerificationStatus
5143                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5144                    result.add(xpDomainInfo.resolveInfo);
5145                }
5146                includeBrowser = true;
5147            }
5148
5149            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5150            // If there were 'always' entries their preferred order has been set, so we also
5151            // back that off to make the alternatives equivalent
5152            if (alwaysAskList.size() > 0) {
5153                for (ResolveInfo i : result) {
5154                    i.preferredOrder = 0;
5155                }
5156                result.addAll(alwaysAskList);
5157                includeBrowser = true;
5158            }
5159
5160            if (includeBrowser) {
5161                // Also add browsers (all of them or only the default one)
5162                if (DEBUG_DOMAIN_VERIFICATION) {
5163                    Slog.v(TAG, "   ...including browsers in candidate set");
5164                }
5165                if ((matchFlags & MATCH_ALL) != 0) {
5166                    result.addAll(matchAllList);
5167                } else {
5168                    // Browser/generic handling case.  If there's a default browser, go straight
5169                    // to that (but only if there is no other higher-priority match).
5170                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5171                    int maxMatchPrio = 0;
5172                    ResolveInfo defaultBrowserMatch = null;
5173                    final int numCandidates = matchAllList.size();
5174                    for (int n = 0; n < numCandidates; n++) {
5175                        ResolveInfo info = matchAllList.get(n);
5176                        // track the highest overall match priority...
5177                        if (info.priority > maxMatchPrio) {
5178                            maxMatchPrio = info.priority;
5179                        }
5180                        // ...and the highest-priority default browser match
5181                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5182                            if (defaultBrowserMatch == null
5183                                    || (defaultBrowserMatch.priority < info.priority)) {
5184                                if (debug) {
5185                                    Slog.v(TAG, "Considering default browser match " + info);
5186                                }
5187                                defaultBrowserMatch = info;
5188                            }
5189                        }
5190                    }
5191                    if (defaultBrowserMatch != null
5192                            && defaultBrowserMatch.priority >= maxMatchPrio
5193                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5194                    {
5195                        if (debug) {
5196                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5197                        }
5198                        result.add(defaultBrowserMatch);
5199                    } else {
5200                        result.addAll(matchAllList);
5201                    }
5202                }
5203
5204                // If there is nothing selected, add all candidates and remove the ones that the user
5205                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5206                if (result.size() == 0) {
5207                    result.addAll(candidates);
5208                    result.removeAll(neverList);
5209                }
5210            }
5211        }
5212        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5213            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5214                    result.size());
5215            for (ResolveInfo info : result) {
5216                Slog.v(TAG, "  + " + info.activityInfo);
5217            }
5218        }
5219        return result;
5220    }
5221
5222    // Returns a packed value as a long:
5223    //
5224    // high 'int'-sized word: link status: undefined/ask/never/always.
5225    // low 'int'-sized word: relative priority among 'always' results.
5226    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5227        long result = ps.getDomainVerificationStatusForUser(userId);
5228        // if none available, get the master status
5229        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5230            if (ps.getIntentFilterVerificationInfo() != null) {
5231                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5232            }
5233        }
5234        return result;
5235    }
5236
5237    private ResolveInfo querySkipCurrentProfileIntents(
5238            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5239            int flags, int sourceUserId) {
5240        if (matchingFilters != null) {
5241            int size = matchingFilters.size();
5242            for (int i = 0; i < size; i ++) {
5243                CrossProfileIntentFilter filter = matchingFilters.get(i);
5244                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5245                    // Checking if there are activities in the target user that can handle the
5246                    // intent.
5247                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5248                            resolvedType, flags, sourceUserId);
5249                    if (resolveInfo != null) {
5250                        return resolveInfo;
5251                    }
5252                }
5253            }
5254        }
5255        return null;
5256    }
5257
5258    // Return matching ResolveInfo in target user if any.
5259    private ResolveInfo queryCrossProfileIntents(
5260            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5261            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5262        if (matchingFilters != null) {
5263            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5264            // match the same intent. For performance reasons, it is better not to
5265            // run queryIntent twice for the same userId
5266            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5267            int size = matchingFilters.size();
5268            for (int i = 0; i < size; i++) {
5269                CrossProfileIntentFilter filter = matchingFilters.get(i);
5270                int targetUserId = filter.getTargetUserId();
5271                boolean skipCurrentProfile =
5272                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5273                boolean skipCurrentProfileIfNoMatchFound =
5274                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5275                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5276                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5277                    // Checking if there are activities in the target user that can handle the
5278                    // intent.
5279                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5280                            resolvedType, flags, sourceUserId);
5281                    if (resolveInfo != null) return resolveInfo;
5282                    alreadyTriedUserIds.put(targetUserId, true);
5283                }
5284            }
5285        }
5286        return null;
5287    }
5288
5289    /**
5290     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5291     * will forward the intent to the filter's target user.
5292     * Otherwise, returns null.
5293     */
5294    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5295            String resolvedType, int flags, int sourceUserId) {
5296        int targetUserId = filter.getTargetUserId();
5297        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5298                resolvedType, flags, targetUserId);
5299        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5300                && isUserEnabled(targetUserId)) {
5301            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5302        }
5303        return null;
5304    }
5305
5306    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5307            int sourceUserId, int targetUserId) {
5308        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5309        long ident = Binder.clearCallingIdentity();
5310        boolean targetIsProfile;
5311        try {
5312            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5313        } finally {
5314            Binder.restoreCallingIdentity(ident);
5315        }
5316        String className;
5317        if (targetIsProfile) {
5318            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5319        } else {
5320            className = FORWARD_INTENT_TO_PARENT;
5321        }
5322        ComponentName forwardingActivityComponentName = new ComponentName(
5323                mAndroidApplication.packageName, className);
5324        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5325                sourceUserId);
5326        if (!targetIsProfile) {
5327            forwardingActivityInfo.showUserIcon = targetUserId;
5328            forwardingResolveInfo.noResourceId = true;
5329        }
5330        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5331        forwardingResolveInfo.priority = 0;
5332        forwardingResolveInfo.preferredOrder = 0;
5333        forwardingResolveInfo.match = 0;
5334        forwardingResolveInfo.isDefault = true;
5335        forwardingResolveInfo.filter = filter;
5336        forwardingResolveInfo.targetUserId = targetUserId;
5337        return forwardingResolveInfo;
5338    }
5339
5340    @Override
5341    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5342            Intent[] specifics, String[] specificTypes, Intent intent,
5343            String resolvedType, int flags, int userId) {
5344        if (!sUserManager.exists(userId)) return Collections.emptyList();
5345        flags = augmentFlagsForUser(flags, userId);
5346        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5347                false, "query intent activity options");
5348        final String resultsAction = intent.getAction();
5349
5350        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5351                | PackageManager.GET_RESOLVED_FILTER, userId);
5352
5353        if (DEBUG_INTENT_MATCHING) {
5354            Log.v(TAG, "Query " + intent + ": " + results);
5355        }
5356
5357        int specificsPos = 0;
5358        int N;
5359
5360        // todo: note that the algorithm used here is O(N^2).  This
5361        // isn't a problem in our current environment, but if we start running
5362        // into situations where we have more than 5 or 10 matches then this
5363        // should probably be changed to something smarter...
5364
5365        // First we go through and resolve each of the specific items
5366        // that were supplied, taking care of removing any corresponding
5367        // duplicate items in the generic resolve list.
5368        if (specifics != null) {
5369            for (int i=0; i<specifics.length; i++) {
5370                final Intent sintent = specifics[i];
5371                if (sintent == null) {
5372                    continue;
5373                }
5374
5375                if (DEBUG_INTENT_MATCHING) {
5376                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5377                }
5378
5379                String action = sintent.getAction();
5380                if (resultsAction != null && resultsAction.equals(action)) {
5381                    // If this action was explicitly requested, then don't
5382                    // remove things that have it.
5383                    action = null;
5384                }
5385
5386                ResolveInfo ri = null;
5387                ActivityInfo ai = null;
5388
5389                ComponentName comp = sintent.getComponent();
5390                if (comp == null) {
5391                    ri = resolveIntent(
5392                        sintent,
5393                        specificTypes != null ? specificTypes[i] : null,
5394                            flags, userId);
5395                    if (ri == null) {
5396                        continue;
5397                    }
5398                    if (ri == mResolveInfo) {
5399                        // ACK!  Must do something better with this.
5400                    }
5401                    ai = ri.activityInfo;
5402                    comp = new ComponentName(ai.applicationInfo.packageName,
5403                            ai.name);
5404                } else {
5405                    ai = getActivityInfo(comp, flags, userId);
5406                    if (ai == null) {
5407                        continue;
5408                    }
5409                }
5410
5411                // Look for any generic query activities that are duplicates
5412                // of this specific one, and remove them from the results.
5413                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5414                N = results.size();
5415                int j;
5416                for (j=specificsPos; j<N; j++) {
5417                    ResolveInfo sri = results.get(j);
5418                    if ((sri.activityInfo.name.equals(comp.getClassName())
5419                            && sri.activityInfo.applicationInfo.packageName.equals(
5420                                    comp.getPackageName()))
5421                        || (action != null && sri.filter.matchAction(action))) {
5422                        results.remove(j);
5423                        if (DEBUG_INTENT_MATCHING) Log.v(
5424                            TAG, "Removing duplicate item from " + j
5425                            + " due to specific " + specificsPos);
5426                        if (ri == null) {
5427                            ri = sri;
5428                        }
5429                        j--;
5430                        N--;
5431                    }
5432                }
5433
5434                // Add this specific item to its proper place.
5435                if (ri == null) {
5436                    ri = new ResolveInfo();
5437                    ri.activityInfo = ai;
5438                }
5439                results.add(specificsPos, ri);
5440                ri.specificIndex = i;
5441                specificsPos++;
5442            }
5443        }
5444
5445        // Now we go through the remaining generic results and remove any
5446        // duplicate actions that are found here.
5447        N = results.size();
5448        for (int i=specificsPos; i<N-1; i++) {
5449            final ResolveInfo rii = results.get(i);
5450            if (rii.filter == null) {
5451                continue;
5452            }
5453
5454            // Iterate over all of the actions of this result's intent
5455            // filter...  typically this should be just one.
5456            final Iterator<String> it = rii.filter.actionsIterator();
5457            if (it == null) {
5458                continue;
5459            }
5460            while (it.hasNext()) {
5461                final String action = it.next();
5462                if (resultsAction != null && resultsAction.equals(action)) {
5463                    // If this action was explicitly requested, then don't
5464                    // remove things that have it.
5465                    continue;
5466                }
5467                for (int j=i+1; j<N; j++) {
5468                    final ResolveInfo rij = results.get(j);
5469                    if (rij.filter != null && rij.filter.hasAction(action)) {
5470                        results.remove(j);
5471                        if (DEBUG_INTENT_MATCHING) Log.v(
5472                            TAG, "Removing duplicate item from " + j
5473                            + " due to action " + action + " at " + i);
5474                        j--;
5475                        N--;
5476                    }
5477                }
5478            }
5479
5480            // If the caller didn't request filter information, drop it now
5481            // so we don't have to marshall/unmarshall it.
5482            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5483                rii.filter = null;
5484            }
5485        }
5486
5487        // Filter out the caller activity if so requested.
5488        if (caller != null) {
5489            N = results.size();
5490            for (int i=0; i<N; i++) {
5491                ActivityInfo ainfo = results.get(i).activityInfo;
5492                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5493                        && caller.getClassName().equals(ainfo.name)) {
5494                    results.remove(i);
5495                    break;
5496                }
5497            }
5498        }
5499
5500        // If the caller didn't request filter information,
5501        // drop them now so we don't have to
5502        // marshall/unmarshall it.
5503        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5504            N = results.size();
5505            for (int i=0; i<N; i++) {
5506                results.get(i).filter = null;
5507            }
5508        }
5509
5510        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5511        return results;
5512    }
5513
5514    @Override
5515    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5516            int userId) {
5517        if (!sUserManager.exists(userId)) return Collections.emptyList();
5518        flags = augmentFlagsForUser(flags, userId);
5519        ComponentName comp = intent.getComponent();
5520        if (comp == null) {
5521            if (intent.getSelector() != null) {
5522                intent = intent.getSelector();
5523                comp = intent.getComponent();
5524            }
5525        }
5526        if (comp != null) {
5527            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5528            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5529            if (ai != null) {
5530                ResolveInfo ri = new ResolveInfo();
5531                ri.activityInfo = ai;
5532                list.add(ri);
5533            }
5534            return list;
5535        }
5536
5537        // reader
5538        synchronized (mPackages) {
5539            String pkgName = intent.getPackage();
5540            if (pkgName == null) {
5541                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5542            }
5543            final PackageParser.Package pkg = mPackages.get(pkgName);
5544            if (pkg != null) {
5545                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5546                        userId);
5547            }
5548            return null;
5549        }
5550    }
5551
5552    @Override
5553    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5554        if (!sUserManager.exists(userId)) return null;
5555        flags = augmentFlagsForUser(flags, userId);
5556        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5557        if (query != null) {
5558            if (query.size() >= 1) {
5559                // If there is more than one service with the same priority,
5560                // just arbitrarily pick the first one.
5561                return query.get(0);
5562            }
5563        }
5564        return null;
5565    }
5566
5567    @Override
5568    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5569            int userId) {
5570        if (!sUserManager.exists(userId)) return Collections.emptyList();
5571        flags = augmentFlagsForUser(flags, userId);
5572        ComponentName comp = intent.getComponent();
5573        if (comp == null) {
5574            if (intent.getSelector() != null) {
5575                intent = intent.getSelector();
5576                comp = intent.getComponent();
5577            }
5578        }
5579        if (comp != null) {
5580            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5581            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5582            if (si != null) {
5583                final ResolveInfo ri = new ResolveInfo();
5584                ri.serviceInfo = si;
5585                list.add(ri);
5586            }
5587            return list;
5588        }
5589
5590        // reader
5591        synchronized (mPackages) {
5592            String pkgName = intent.getPackage();
5593            if (pkgName == null) {
5594                return mServices.queryIntent(intent, resolvedType, flags, userId);
5595            }
5596            final PackageParser.Package pkg = mPackages.get(pkgName);
5597            if (pkg != null) {
5598                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5599                        userId);
5600            }
5601            return null;
5602        }
5603    }
5604
5605    @Override
5606    public List<ResolveInfo> queryIntentContentProviders(
5607            Intent intent, String resolvedType, int flags, int userId) {
5608        if (!sUserManager.exists(userId)) return Collections.emptyList();
5609        flags = augmentFlagsForUser(flags, userId);
5610        ComponentName comp = intent.getComponent();
5611        if (comp == null) {
5612            if (intent.getSelector() != null) {
5613                intent = intent.getSelector();
5614                comp = intent.getComponent();
5615            }
5616        }
5617        if (comp != null) {
5618            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5619            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5620            if (pi != null) {
5621                final ResolveInfo ri = new ResolveInfo();
5622                ri.providerInfo = pi;
5623                list.add(ri);
5624            }
5625            return list;
5626        }
5627
5628        // reader
5629        synchronized (mPackages) {
5630            String pkgName = intent.getPackage();
5631            if (pkgName == null) {
5632                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5633            }
5634            final PackageParser.Package pkg = mPackages.get(pkgName);
5635            if (pkg != null) {
5636                return mProviders.queryIntentForPackage(
5637                        intent, resolvedType, flags, pkg.providers, userId);
5638            }
5639            return null;
5640        }
5641    }
5642
5643    @Override
5644    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5645        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5646
5647        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5648
5649        // writer
5650        synchronized (mPackages) {
5651            ArrayList<PackageInfo> list;
5652            if (listUninstalled) {
5653                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5654                for (PackageSetting ps : mSettings.mPackages.values()) {
5655                    PackageInfo pi;
5656                    if (ps.pkg != null) {
5657                        pi = generatePackageInfo(ps.pkg, flags, userId);
5658                    } else {
5659                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5660                    }
5661                    if (pi != null) {
5662                        list.add(pi);
5663                    }
5664                }
5665            } else {
5666                list = new ArrayList<PackageInfo>(mPackages.size());
5667                for (PackageParser.Package p : mPackages.values()) {
5668                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5669                    if (pi != null) {
5670                        list.add(pi);
5671                    }
5672                }
5673            }
5674
5675            return new ParceledListSlice<PackageInfo>(list);
5676        }
5677    }
5678
5679    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5680            String[] permissions, boolean[] tmp, int flags, int userId) {
5681        int numMatch = 0;
5682        final PermissionsState permissionsState = ps.getPermissionsState();
5683        for (int i=0; i<permissions.length; i++) {
5684            final String permission = permissions[i];
5685            if (permissionsState.hasPermission(permission, userId)) {
5686                tmp[i] = true;
5687                numMatch++;
5688            } else {
5689                tmp[i] = false;
5690            }
5691        }
5692        if (numMatch == 0) {
5693            return;
5694        }
5695        PackageInfo pi;
5696        if (ps.pkg != null) {
5697            pi = generatePackageInfo(ps.pkg, flags, userId);
5698        } else {
5699            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5700        }
5701        // The above might return null in cases of uninstalled apps or install-state
5702        // skew across users/profiles.
5703        if (pi != null) {
5704            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5705                if (numMatch == permissions.length) {
5706                    pi.requestedPermissions = permissions;
5707                } else {
5708                    pi.requestedPermissions = new String[numMatch];
5709                    numMatch = 0;
5710                    for (int i=0; i<permissions.length; i++) {
5711                        if (tmp[i]) {
5712                            pi.requestedPermissions[numMatch] = permissions[i];
5713                            numMatch++;
5714                        }
5715                    }
5716                }
5717            }
5718            list.add(pi);
5719        }
5720    }
5721
5722    @Override
5723    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5724            String[] permissions, int flags, int userId) {
5725        if (!sUserManager.exists(userId)) return null;
5726        flags = augmentFlagsForUser(flags, userId);
5727        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5728
5729        // writer
5730        synchronized (mPackages) {
5731            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5732            boolean[] tmpBools = new boolean[permissions.length];
5733            if (listUninstalled) {
5734                for (PackageSetting ps : mSettings.mPackages.values()) {
5735                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5736                }
5737            } else {
5738                for (PackageParser.Package pkg : mPackages.values()) {
5739                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5740                    if (ps != null) {
5741                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5742                                userId);
5743                    }
5744                }
5745            }
5746
5747            return new ParceledListSlice<PackageInfo>(list);
5748        }
5749    }
5750
5751    @Override
5752    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5753        if (!sUserManager.exists(userId)) return null;
5754        flags = augmentFlagsForUser(flags, userId);
5755        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5756
5757        // writer
5758        synchronized (mPackages) {
5759            ArrayList<ApplicationInfo> list;
5760            if (listUninstalled) {
5761                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5762                for (PackageSetting ps : mSettings.mPackages.values()) {
5763                    ApplicationInfo ai;
5764                    if (ps.pkg != null) {
5765                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5766                                ps.readUserState(userId), userId);
5767                    } else {
5768                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5769                    }
5770                    if (ai != null) {
5771                        list.add(ai);
5772                    }
5773                }
5774            } else {
5775                list = new ArrayList<ApplicationInfo>(mPackages.size());
5776                for (PackageParser.Package p : mPackages.values()) {
5777                    if (p.mExtras != null) {
5778                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5779                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5780                        if (ai != null) {
5781                            list.add(ai);
5782                        }
5783                    }
5784                }
5785            }
5786
5787            return new ParceledListSlice<ApplicationInfo>(list);
5788        }
5789    }
5790
5791    @Override
5792    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5793        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5794                "getEphemeralApplications");
5795        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5796                "getEphemeralApplications");
5797        synchronized (mPackages) {
5798            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5799                    .getEphemeralApplicationsLPw(userId);
5800            if (ephemeralApps != null) {
5801                return new ParceledListSlice<>(ephemeralApps);
5802            }
5803        }
5804        return null;
5805    }
5806
5807    @Override
5808    public boolean isEphemeralApplication(String packageName, int userId) {
5809        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5810                "isEphemeral");
5811        if (!isCallerSameApp(packageName)) {
5812            return false;
5813        }
5814        synchronized (mPackages) {
5815            PackageParser.Package pkg = mPackages.get(packageName);
5816            if (pkg != null) {
5817                return pkg.applicationInfo.isEphemeralApp();
5818            }
5819        }
5820        return false;
5821    }
5822
5823    @Override
5824    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5825        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5826                "getCookie");
5827        if (!isCallerSameApp(packageName)) {
5828            return null;
5829        }
5830        synchronized (mPackages) {
5831            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5832                    packageName, userId);
5833        }
5834    }
5835
5836    @Override
5837    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5838        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5839                "setCookie");
5840        if (!isCallerSameApp(packageName)) {
5841            return false;
5842        }
5843        synchronized (mPackages) {
5844            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5845                    packageName, cookie, userId);
5846        }
5847    }
5848
5849    @Override
5850    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5851        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5852                "getEphemeralApplicationIcon");
5853        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5854                "getEphemeralApplicationIcon");
5855        synchronized (mPackages) {
5856            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5857                    packageName, userId);
5858        }
5859    }
5860
5861    private boolean isCallerSameApp(String packageName) {
5862        PackageParser.Package pkg = mPackages.get(packageName);
5863        return pkg != null
5864                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5865    }
5866
5867    public List<ApplicationInfo> getPersistentApplications(int flags) {
5868        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5869
5870        // reader
5871        synchronized (mPackages) {
5872            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5873            final int userId = UserHandle.getCallingUserId();
5874            while (i.hasNext()) {
5875                final PackageParser.Package p = i.next();
5876                if (p.applicationInfo != null
5877                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5878                        && (!mSafeMode || isSystemApp(p))) {
5879                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5880                    if (ps != null) {
5881                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5882                                ps.readUserState(userId), userId);
5883                        if (ai != null) {
5884                            finalList.add(ai);
5885                        }
5886                    }
5887                }
5888            }
5889        }
5890
5891        return finalList;
5892    }
5893
5894    @Override
5895    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5896        if (!sUserManager.exists(userId)) return null;
5897        flags = augmentFlagsForUser(flags, userId);
5898        // reader
5899        synchronized (mPackages) {
5900            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5901            PackageSetting ps = provider != null
5902                    ? mSettings.mPackages.get(provider.owner.packageName)
5903                    : null;
5904            return ps != null
5905                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5906                    && (!mSafeMode || (provider.info.applicationInfo.flags
5907                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5908                    ? PackageParser.generateProviderInfo(provider, flags,
5909                            ps.readUserState(userId), userId)
5910                    : null;
5911        }
5912    }
5913
5914    /**
5915     * @deprecated
5916     */
5917    @Deprecated
5918    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5919        // reader
5920        synchronized (mPackages) {
5921            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5922                    .entrySet().iterator();
5923            final int userId = UserHandle.getCallingUserId();
5924            while (i.hasNext()) {
5925                Map.Entry<String, PackageParser.Provider> entry = i.next();
5926                PackageParser.Provider p = entry.getValue();
5927                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5928
5929                if (ps != null && p.syncable
5930                        && (!mSafeMode || (p.info.applicationInfo.flags
5931                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5932                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5933                            ps.readUserState(userId), userId);
5934                    if (info != null) {
5935                        outNames.add(entry.getKey());
5936                        outInfo.add(info);
5937                    }
5938                }
5939            }
5940        }
5941    }
5942
5943    @Override
5944    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5945            int uid, int flags) {
5946        final int userId = processName != null ? UserHandle.getUserId(uid)
5947                : UserHandle.getCallingUserId();
5948        if (!sUserManager.exists(userId)) return null;
5949        flags = augmentFlagsForUser(flags, userId);
5950
5951        ArrayList<ProviderInfo> finalList = null;
5952        // reader
5953        synchronized (mPackages) {
5954            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5955            while (i.hasNext()) {
5956                final PackageParser.Provider p = i.next();
5957                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5958                if (ps != null && p.info.authority != null
5959                        && (processName == null
5960                                || (p.info.processName.equals(processName)
5961                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5962                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5963                        && (!mSafeMode
5964                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5965                    if (finalList == null) {
5966                        finalList = new ArrayList<ProviderInfo>(3);
5967                    }
5968                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5969                            ps.readUserState(userId), userId);
5970                    if (info != null) {
5971                        finalList.add(info);
5972                    }
5973                }
5974            }
5975        }
5976
5977        if (finalList != null) {
5978            Collections.sort(finalList, mProviderInitOrderSorter);
5979            return new ParceledListSlice<ProviderInfo>(finalList);
5980        }
5981
5982        return null;
5983    }
5984
5985    @Override
5986    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5987            int flags) {
5988        // reader
5989        synchronized (mPackages) {
5990            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5991            return PackageParser.generateInstrumentationInfo(i, flags);
5992        }
5993    }
5994
5995    @Override
5996    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5997            int flags) {
5998        ArrayList<InstrumentationInfo> finalList =
5999            new ArrayList<InstrumentationInfo>();
6000
6001        // reader
6002        synchronized (mPackages) {
6003            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6004            while (i.hasNext()) {
6005                final PackageParser.Instrumentation p = i.next();
6006                if (targetPackage == null
6007                        || targetPackage.equals(p.info.targetPackage)) {
6008                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6009                            flags);
6010                    if (ii != null) {
6011                        finalList.add(ii);
6012                    }
6013                }
6014            }
6015        }
6016
6017        return finalList;
6018    }
6019
6020    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6021        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6022        if (overlays == null) {
6023            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6024            return;
6025        }
6026        for (PackageParser.Package opkg : overlays.values()) {
6027            // Not much to do if idmap fails: we already logged the error
6028            // and we certainly don't want to abort installation of pkg simply
6029            // because an overlay didn't fit properly. For these reasons,
6030            // ignore the return value of createIdmapForPackagePairLI.
6031            createIdmapForPackagePairLI(pkg, opkg);
6032        }
6033    }
6034
6035    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6036            PackageParser.Package opkg) {
6037        if (!opkg.mTrustedOverlay) {
6038            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6039                    opkg.baseCodePath + ": overlay not trusted");
6040            return false;
6041        }
6042        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6043        if (overlaySet == null) {
6044            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6045                    opkg.baseCodePath + " but target package has no known overlays");
6046            return false;
6047        }
6048        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6049        // TODO: generate idmap for split APKs
6050        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6051            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6052                    + opkg.baseCodePath);
6053            return false;
6054        }
6055        PackageParser.Package[] overlayArray =
6056            overlaySet.values().toArray(new PackageParser.Package[0]);
6057        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6058            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6059                return p1.mOverlayPriority - p2.mOverlayPriority;
6060            }
6061        };
6062        Arrays.sort(overlayArray, cmp);
6063
6064        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6065        int i = 0;
6066        for (PackageParser.Package p : overlayArray) {
6067            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6068        }
6069        return true;
6070    }
6071
6072    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6073        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6074        try {
6075            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6076        } finally {
6077            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6078        }
6079    }
6080
6081    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6082        final File[] files = dir.listFiles();
6083        if (ArrayUtils.isEmpty(files)) {
6084            Log.d(TAG, "No files in app dir " + dir);
6085            return;
6086        }
6087
6088        if (DEBUG_PACKAGE_SCANNING) {
6089            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6090                    + " flags=0x" + Integer.toHexString(parseFlags));
6091        }
6092
6093        for (File file : files) {
6094            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6095                    && !PackageInstallerService.isStageName(file.getName());
6096            if (!isPackage) {
6097                // Ignore entries which are not packages
6098                continue;
6099            }
6100            try {
6101                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6102                        scanFlags, currentTime, null);
6103            } catch (PackageManagerException e) {
6104                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6105
6106                // Delete invalid userdata apps
6107                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6108                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6109                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6110                    if (file.isDirectory()) {
6111                        mInstaller.rmPackageDir(file.getAbsolutePath());
6112                    } else {
6113                        file.delete();
6114                    }
6115                }
6116            }
6117        }
6118    }
6119
6120    private static File getSettingsProblemFile() {
6121        File dataDir = Environment.getDataDirectory();
6122        File systemDir = new File(dataDir, "system");
6123        File fname = new File(systemDir, "uiderrors.txt");
6124        return fname;
6125    }
6126
6127    static void reportSettingsProblem(int priority, String msg) {
6128        logCriticalInfo(priority, msg);
6129    }
6130
6131    static void logCriticalInfo(int priority, String msg) {
6132        Slog.println(priority, TAG, msg);
6133        EventLogTags.writePmCriticalInfo(msg);
6134        try {
6135            File fname = getSettingsProblemFile();
6136            FileOutputStream out = new FileOutputStream(fname, true);
6137            PrintWriter pw = new FastPrintWriter(out);
6138            SimpleDateFormat formatter = new SimpleDateFormat();
6139            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6140            pw.println(dateString + ": " + msg);
6141            pw.close();
6142            FileUtils.setPermissions(
6143                    fname.toString(),
6144                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6145                    -1, -1);
6146        } catch (java.io.IOException e) {
6147        }
6148    }
6149
6150    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6151            PackageParser.Package pkg, File srcFile, int parseFlags)
6152            throws PackageManagerException {
6153        if (ps != null
6154                && ps.codePath.equals(srcFile)
6155                && ps.timeStamp == srcFile.lastModified()
6156                && !isCompatSignatureUpdateNeeded(pkg)
6157                && !isRecoverSignatureUpdateNeeded(pkg)) {
6158            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6159            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6160            ArraySet<PublicKey> signingKs;
6161            synchronized (mPackages) {
6162                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6163            }
6164            if (ps.signatures.mSignatures != null
6165                    && ps.signatures.mSignatures.length != 0
6166                    && signingKs != null) {
6167                // Optimization: reuse the existing cached certificates
6168                // if the package appears to be unchanged.
6169                pkg.mSignatures = ps.signatures.mSignatures;
6170                pkg.mSigningKeys = signingKs;
6171                return;
6172            }
6173
6174            Slog.w(TAG, "PackageSetting for " + ps.name
6175                    + " is missing signatures.  Collecting certs again to recover them.");
6176        } else {
6177            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6178        }
6179
6180        try {
6181            pp.collectCertificates(pkg, parseFlags);
6182            pp.collectManifestDigest(pkg);
6183        } catch (PackageParserException e) {
6184            throw PackageManagerException.from(e);
6185        }
6186    }
6187
6188    /**
6189     *  Traces a package scan.
6190     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6191     */
6192    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6193            long currentTime, UserHandle user) throws PackageManagerException {
6194        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6195        try {
6196            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6197        } finally {
6198            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6199        }
6200    }
6201
6202    /**
6203     *  Scans a package and returns the newly parsed package.
6204     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6205     */
6206    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6207            long currentTime, UserHandle user) throws PackageManagerException {
6208        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6209        parseFlags |= mDefParseFlags;
6210        PackageParser pp = new PackageParser();
6211        pp.setSeparateProcesses(mSeparateProcesses);
6212        pp.setOnlyCoreApps(mOnlyCore);
6213        pp.setDisplayMetrics(mMetrics);
6214
6215        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6216            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6217        }
6218
6219        final PackageParser.Package pkg;
6220        try {
6221            pkg = pp.parsePackage(scanFile, parseFlags);
6222        } catch (PackageParserException e) {
6223            throw PackageManagerException.from(e);
6224        }
6225
6226        PackageSetting ps = null;
6227        PackageSetting updatedPkg;
6228        // reader
6229        synchronized (mPackages) {
6230            // Look to see if we already know about this package.
6231            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6232            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6233                // This package has been renamed to its original name.  Let's
6234                // use that.
6235                ps = mSettings.peekPackageLPr(oldName);
6236            }
6237            // If there was no original package, see one for the real package name.
6238            if (ps == null) {
6239                ps = mSettings.peekPackageLPr(pkg.packageName);
6240            }
6241            // Check to see if this package could be hiding/updating a system
6242            // package.  Must look for it either under the original or real
6243            // package name depending on our state.
6244            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6245            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6246        }
6247        boolean updatedPkgBetter = false;
6248        // First check if this is a system package that may involve an update
6249        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6250            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6251            // it needs to drop FLAG_PRIVILEGED.
6252            if (locationIsPrivileged(scanFile)) {
6253                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6254            } else {
6255                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6256            }
6257
6258            if (ps != null && !ps.codePath.equals(scanFile)) {
6259                // The path has changed from what was last scanned...  check the
6260                // version of the new path against what we have stored to determine
6261                // what to do.
6262                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6263                if (pkg.mVersionCode <= ps.versionCode) {
6264                    // The system package has been updated and the code path does not match
6265                    // Ignore entry. Skip it.
6266                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6267                            + " ignored: updated version " + ps.versionCode
6268                            + " better than this " + pkg.mVersionCode);
6269                    if (!updatedPkg.codePath.equals(scanFile)) {
6270                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6271                                + ps.name + " changing from " + updatedPkg.codePathString
6272                                + " to " + scanFile);
6273                        updatedPkg.codePath = scanFile;
6274                        updatedPkg.codePathString = scanFile.toString();
6275                        updatedPkg.resourcePath = scanFile;
6276                        updatedPkg.resourcePathString = scanFile.toString();
6277                    }
6278                    updatedPkg.pkg = pkg;
6279                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6280                            "Package " + ps.name + " at " + scanFile
6281                                    + " ignored: updated version " + ps.versionCode
6282                                    + " better than this " + pkg.mVersionCode);
6283                } else {
6284                    // The current app on the system partition is better than
6285                    // what we have updated to on the data partition; switch
6286                    // back to the system partition version.
6287                    // At this point, its safely assumed that package installation for
6288                    // apps in system partition will go through. If not there won't be a working
6289                    // version of the app
6290                    // writer
6291                    synchronized (mPackages) {
6292                        // Just remove the loaded entries from package lists.
6293                        mPackages.remove(ps.name);
6294                    }
6295
6296                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6297                            + " reverting from " + ps.codePathString
6298                            + ": new version " + pkg.mVersionCode
6299                            + " better than installed " + ps.versionCode);
6300
6301                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6302                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6303                    synchronized (mInstallLock) {
6304                        args.cleanUpResourcesLI();
6305                    }
6306                    synchronized (mPackages) {
6307                        mSettings.enableSystemPackageLPw(ps.name);
6308                    }
6309                    updatedPkgBetter = true;
6310                }
6311            }
6312        }
6313
6314        if (updatedPkg != null) {
6315            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6316            // initially
6317            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6318
6319            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6320            // flag set initially
6321            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6322                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6323            }
6324        }
6325
6326        // Verify certificates against what was last scanned
6327        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6328
6329        /*
6330         * A new system app appeared, but we already had a non-system one of the
6331         * same name installed earlier.
6332         */
6333        boolean shouldHideSystemApp = false;
6334        if (updatedPkg == null && ps != null
6335                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6336            /*
6337             * Check to make sure the signatures match first. If they don't,
6338             * wipe the installed application and its data.
6339             */
6340            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6341                    != PackageManager.SIGNATURE_MATCH) {
6342                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6343                        + " signatures don't match existing userdata copy; removing");
6344                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6345                ps = null;
6346            } else {
6347                /*
6348                 * If the newly-added system app is an older version than the
6349                 * already installed version, hide it. It will be scanned later
6350                 * and re-added like an update.
6351                 */
6352                if (pkg.mVersionCode <= ps.versionCode) {
6353                    shouldHideSystemApp = true;
6354                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6355                            + " but new version " + pkg.mVersionCode + " better than installed "
6356                            + ps.versionCode + "; hiding system");
6357                } else {
6358                    /*
6359                     * The newly found system app is a newer version that the
6360                     * one previously installed. Simply remove the
6361                     * already-installed application and replace it with our own
6362                     * while keeping the application data.
6363                     */
6364                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6365                            + " reverting from " + ps.codePathString + ": new version "
6366                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6367                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6368                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6369                    synchronized (mInstallLock) {
6370                        args.cleanUpResourcesLI();
6371                    }
6372                }
6373            }
6374        }
6375
6376        // The apk is forward locked (not public) if its code and resources
6377        // are kept in different files. (except for app in either system or
6378        // vendor path).
6379        // TODO grab this value from PackageSettings
6380        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6381            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6382                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6383            }
6384        }
6385
6386        // TODO: extend to support forward-locked splits
6387        String resourcePath = null;
6388        String baseResourcePath = null;
6389        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6390            if (ps != null && ps.resourcePathString != null) {
6391                resourcePath = ps.resourcePathString;
6392                baseResourcePath = ps.resourcePathString;
6393            } else {
6394                // Should not happen at all. Just log an error.
6395                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6396            }
6397        } else {
6398            resourcePath = pkg.codePath;
6399            baseResourcePath = pkg.baseCodePath;
6400        }
6401
6402        // Set application objects path explicitly.
6403        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6404        pkg.applicationInfo.setCodePath(pkg.codePath);
6405        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6406        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6407        pkg.applicationInfo.setResourcePath(resourcePath);
6408        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6409        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6410
6411        // Note that we invoke the following method only if we are about to unpack an application
6412        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6413                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6414
6415        /*
6416         * If the system app should be overridden by a previously installed
6417         * data, hide the system app now and let the /data/app scan pick it up
6418         * again.
6419         */
6420        if (shouldHideSystemApp) {
6421            synchronized (mPackages) {
6422                mSettings.disableSystemPackageLPw(pkg.packageName);
6423            }
6424        }
6425
6426        return scannedPkg;
6427    }
6428
6429    private static String fixProcessName(String defProcessName,
6430            String processName, int uid) {
6431        if (processName == null) {
6432            return defProcessName;
6433        }
6434        return processName;
6435    }
6436
6437    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6438            throws PackageManagerException {
6439        if (pkgSetting.signatures.mSignatures != null) {
6440            // Already existing package. Make sure signatures match
6441            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6442                    == PackageManager.SIGNATURE_MATCH;
6443            if (!match) {
6444                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6445                        == PackageManager.SIGNATURE_MATCH;
6446            }
6447            if (!match) {
6448                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6449                        == PackageManager.SIGNATURE_MATCH;
6450            }
6451            if (!match) {
6452                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6453                        + pkg.packageName + " signatures do not match the "
6454                        + "previously installed version; ignoring!");
6455            }
6456        }
6457
6458        // Check for shared user signatures
6459        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6460            // Already existing package. Make sure signatures match
6461            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6462                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6463            if (!match) {
6464                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6465                        == PackageManager.SIGNATURE_MATCH;
6466            }
6467            if (!match) {
6468                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6469                        == PackageManager.SIGNATURE_MATCH;
6470            }
6471            if (!match) {
6472                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6473                        "Package " + pkg.packageName
6474                        + " has no signatures that match those in shared user "
6475                        + pkgSetting.sharedUser.name + "; ignoring!");
6476            }
6477        }
6478    }
6479
6480    /**
6481     * Enforces that only the system UID or root's UID can call a method exposed
6482     * via Binder.
6483     *
6484     * @param message used as message if SecurityException is thrown
6485     * @throws SecurityException if the caller is not system or root
6486     */
6487    private static final void enforceSystemOrRoot(String message) {
6488        final int uid = Binder.getCallingUid();
6489        if (uid != Process.SYSTEM_UID && uid != 0) {
6490            throw new SecurityException(message);
6491        }
6492    }
6493
6494    @Override
6495    public void performFstrimIfNeeded() {
6496        enforceSystemOrRoot("Only the system can request fstrim");
6497
6498        // Before everything else, see whether we need to fstrim.
6499        try {
6500            IMountService ms = PackageHelper.getMountService();
6501            if (ms != null) {
6502                final boolean isUpgrade = isUpgrade();
6503                boolean doTrim = isUpgrade;
6504                if (doTrim) {
6505                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6506                } else {
6507                    final long interval = android.provider.Settings.Global.getLong(
6508                            mContext.getContentResolver(),
6509                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6510                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6511                    if (interval > 0) {
6512                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6513                        if (timeSinceLast > interval) {
6514                            doTrim = true;
6515                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6516                                    + "; running immediately");
6517                        }
6518                    }
6519                }
6520                if (doTrim) {
6521                    if (!isFirstBoot()) {
6522                        try {
6523                            ActivityManagerNative.getDefault().showBootMessage(
6524                                    mContext.getResources().getString(
6525                                            R.string.android_upgrading_fstrim), true);
6526                        } catch (RemoteException e) {
6527                        }
6528                    }
6529                    ms.runMaintenance();
6530                }
6531            } else {
6532                Slog.e(TAG, "Mount service unavailable!");
6533            }
6534        } catch (RemoteException e) {
6535            // Can't happen; MountService is local
6536        }
6537    }
6538
6539    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6540        List<ResolveInfo> ris = null;
6541        try {
6542            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6543                    intent, null, 0, userId);
6544        } catch (RemoteException e) {
6545        }
6546        ArraySet<String> pkgNames = new ArraySet<String>();
6547        if (ris != null) {
6548            for (ResolveInfo ri : ris) {
6549                pkgNames.add(ri.activityInfo.packageName);
6550            }
6551        }
6552        return pkgNames;
6553    }
6554
6555    @Override
6556    public void notifyPackageUse(String packageName) {
6557        synchronized (mPackages) {
6558            PackageParser.Package p = mPackages.get(packageName);
6559            if (p == null) {
6560                return;
6561            }
6562            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6563        }
6564    }
6565
6566    @Override
6567    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6568        return performDexOptTraced(packageName, instructionSet);
6569    }
6570
6571    public boolean performDexOpt(String packageName, String instructionSet) {
6572        return performDexOptTraced(packageName, instructionSet);
6573    }
6574
6575    private boolean performDexOptTraced(String packageName, String instructionSet) {
6576        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6577        try {
6578            return performDexOptInternal(packageName, instructionSet);
6579        } finally {
6580            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6581        }
6582    }
6583
6584    private boolean performDexOptInternal(String packageName, String instructionSet) {
6585        PackageParser.Package p;
6586        final String targetInstructionSet;
6587        synchronized (mPackages) {
6588            p = mPackages.get(packageName);
6589            if (p == null) {
6590                return false;
6591            }
6592            mPackageUsage.write(false);
6593
6594            targetInstructionSet = instructionSet != null ? instructionSet :
6595                    getPrimaryInstructionSet(p.applicationInfo);
6596            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6597                return false;
6598            }
6599        }
6600        long callingId = Binder.clearCallingIdentity();
6601        try {
6602            synchronized (mInstallLock) {
6603                final String[] instructionSets = new String[] { targetInstructionSet };
6604                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6605                        true /* inclDependencies */);
6606                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6607            }
6608        } finally {
6609            Binder.restoreCallingIdentity(callingId);
6610        }
6611    }
6612
6613    public ArraySet<String> getPackagesThatNeedDexOpt() {
6614        ArraySet<String> pkgs = null;
6615        synchronized (mPackages) {
6616            for (PackageParser.Package p : mPackages.values()) {
6617                if (DEBUG_DEXOPT) {
6618                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6619                }
6620                if (!p.mDexOptPerformed.isEmpty()) {
6621                    continue;
6622                }
6623                if (pkgs == null) {
6624                    pkgs = new ArraySet<String>();
6625                }
6626                pkgs.add(p.packageName);
6627            }
6628        }
6629        return pkgs;
6630    }
6631
6632    public void shutdown() {
6633        mPackageUsage.write(true);
6634    }
6635
6636    @Override
6637    public void forceDexOpt(String packageName) {
6638        enforceSystemOrRoot("forceDexOpt");
6639
6640        PackageParser.Package pkg;
6641        synchronized (mPackages) {
6642            pkg = mPackages.get(packageName);
6643            if (pkg == null) {
6644                throw new IllegalArgumentException("Missing package: " + packageName);
6645            }
6646        }
6647
6648        synchronized (mInstallLock) {
6649            final String[] instructionSets = new String[] {
6650                    getPrimaryInstructionSet(pkg.applicationInfo) };
6651
6652            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6653
6654            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6655                    true /* inclDependencies */);
6656
6657            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6658            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6659                throw new IllegalStateException("Failed to dexopt: " + res);
6660            }
6661        }
6662    }
6663
6664    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6665        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6666            Slog.w(TAG, "Unable to update from " + oldPkg.name
6667                    + " to " + newPkg.packageName
6668                    + ": old package not in system partition");
6669            return false;
6670        } else if (mPackages.get(oldPkg.name) != null) {
6671            Slog.w(TAG, "Unable to update from " + oldPkg.name
6672                    + " to " + newPkg.packageName
6673                    + ": old package still exists");
6674            return false;
6675        }
6676        return true;
6677    }
6678
6679    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6680            throws PackageManagerException {
6681        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6682        if (res != 0) {
6683            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6684                    "Failed to install " + packageName + ": " + res);
6685        }
6686
6687        final int[] users = sUserManager.getUserIds();
6688        for (int user : users) {
6689            if (user != 0) {
6690                res = mInstaller.createUserData(volumeUuid, packageName,
6691                        UserHandle.getUid(user, uid), user, seinfo);
6692                if (res != 0) {
6693                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6694                            "Failed to createUserData " + packageName + ": " + res);
6695                }
6696            }
6697        }
6698    }
6699
6700    private int removeDataDirsLI(String volumeUuid, String packageName) {
6701        int[] users = sUserManager.getUserIds();
6702        int res = 0;
6703        for (int user : users) {
6704            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6705            if (resInner < 0) {
6706                res = resInner;
6707            }
6708        }
6709
6710        return res;
6711    }
6712
6713    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6714        int[] users = sUserManager.getUserIds();
6715        int res = 0;
6716        for (int user : users) {
6717            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6718            if (resInner < 0) {
6719                res = resInner;
6720            }
6721        }
6722        return res;
6723    }
6724
6725    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6726            PackageParser.Package changingLib) {
6727        if (file.path != null) {
6728            usesLibraryFiles.add(file.path);
6729            return;
6730        }
6731        PackageParser.Package p = mPackages.get(file.apk);
6732        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6733            // If we are doing this while in the middle of updating a library apk,
6734            // then we need to make sure to use that new apk for determining the
6735            // dependencies here.  (We haven't yet finished committing the new apk
6736            // to the package manager state.)
6737            if (p == null || p.packageName.equals(changingLib.packageName)) {
6738                p = changingLib;
6739            }
6740        }
6741        if (p != null) {
6742            usesLibraryFiles.addAll(p.getAllCodePaths());
6743        }
6744    }
6745
6746    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6747            PackageParser.Package changingLib) throws PackageManagerException {
6748        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6749            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6750            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6751            for (int i=0; i<N; i++) {
6752                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6753                if (file == null) {
6754                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6755                            "Package " + pkg.packageName + " requires unavailable shared library "
6756                            + pkg.usesLibraries.get(i) + "; failing!");
6757                }
6758                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6759            }
6760            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6761            for (int i=0; i<N; i++) {
6762                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6763                if (file == null) {
6764                    Slog.w(TAG, "Package " + pkg.packageName
6765                            + " desires unavailable shared library "
6766                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6767                } else {
6768                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6769                }
6770            }
6771            N = usesLibraryFiles.size();
6772            if (N > 0) {
6773                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6774            } else {
6775                pkg.usesLibraryFiles = null;
6776            }
6777        }
6778    }
6779
6780    private static boolean hasString(List<String> list, List<String> which) {
6781        if (list == null) {
6782            return false;
6783        }
6784        for (int i=list.size()-1; i>=0; i--) {
6785            for (int j=which.size()-1; j>=0; j--) {
6786                if (which.get(j).equals(list.get(i))) {
6787                    return true;
6788                }
6789            }
6790        }
6791        return false;
6792    }
6793
6794    private void updateAllSharedLibrariesLPw() {
6795        for (PackageParser.Package pkg : mPackages.values()) {
6796            try {
6797                updateSharedLibrariesLPw(pkg, null);
6798            } catch (PackageManagerException e) {
6799                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6800            }
6801        }
6802    }
6803
6804    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6805            PackageParser.Package changingPkg) {
6806        ArrayList<PackageParser.Package> res = null;
6807        for (PackageParser.Package pkg : mPackages.values()) {
6808            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6809                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6810                if (res == null) {
6811                    res = new ArrayList<PackageParser.Package>();
6812                }
6813                res.add(pkg);
6814                try {
6815                    updateSharedLibrariesLPw(pkg, changingPkg);
6816                } catch (PackageManagerException e) {
6817                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6818                }
6819            }
6820        }
6821        return res;
6822    }
6823
6824    /**
6825     * Derive the value of the {@code cpuAbiOverride} based on the provided
6826     * value and an optional stored value from the package settings.
6827     */
6828    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6829        String cpuAbiOverride = null;
6830
6831        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6832            cpuAbiOverride = null;
6833        } else if (abiOverride != null) {
6834            cpuAbiOverride = abiOverride;
6835        } else if (settings != null) {
6836            cpuAbiOverride = settings.cpuAbiOverrideString;
6837        }
6838
6839        return cpuAbiOverride;
6840    }
6841
6842    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6843            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6844        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6845        try {
6846            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6847        } finally {
6848            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6849        }
6850    }
6851
6852    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6853            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6854        boolean success = false;
6855        try {
6856            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6857                    currentTime, user);
6858            success = true;
6859            return res;
6860        } finally {
6861            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6862                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6863            }
6864        }
6865    }
6866
6867    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6868            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6869        final File scanFile = new File(pkg.codePath);
6870        if (pkg.applicationInfo.getCodePath() == null ||
6871                pkg.applicationInfo.getResourcePath() == null) {
6872            // Bail out. The resource and code paths haven't been set.
6873            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6874                    "Code and resource paths haven't been set correctly");
6875        }
6876
6877        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6878            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6879        } else {
6880            // Only allow system apps to be flagged as core apps.
6881            pkg.coreApp = false;
6882        }
6883
6884        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6885            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6886        }
6887
6888        if (mCustomResolverComponentName != null &&
6889                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6890            setUpCustomResolverActivity(pkg);
6891        }
6892
6893        if (pkg.packageName.equals("android")) {
6894            synchronized (mPackages) {
6895                if (mAndroidApplication != null) {
6896                    Slog.w(TAG, "*************************************************");
6897                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6898                    Slog.w(TAG, " file=" + scanFile);
6899                    Slog.w(TAG, "*************************************************");
6900                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6901                            "Core android package being redefined.  Skipping.");
6902                }
6903
6904                // Set up information for our fall-back user intent resolution activity.
6905                mPlatformPackage = pkg;
6906                pkg.mVersionCode = mSdkVersion;
6907                mAndroidApplication = pkg.applicationInfo;
6908
6909                if (!mResolverReplaced) {
6910                    mResolveActivity.applicationInfo = mAndroidApplication;
6911                    mResolveActivity.name = ResolverActivity.class.getName();
6912                    mResolveActivity.packageName = mAndroidApplication.packageName;
6913                    mResolveActivity.processName = "system:ui";
6914                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6915                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6916                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6917                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6918                    mResolveActivity.exported = true;
6919                    mResolveActivity.enabled = true;
6920                    mResolveInfo.activityInfo = mResolveActivity;
6921                    mResolveInfo.priority = 0;
6922                    mResolveInfo.preferredOrder = 0;
6923                    mResolveInfo.match = 0;
6924                    mResolveComponentName = new ComponentName(
6925                            mAndroidApplication.packageName, mResolveActivity.name);
6926                }
6927            }
6928        }
6929
6930        if (DEBUG_PACKAGE_SCANNING) {
6931            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6932                Log.d(TAG, "Scanning package " + pkg.packageName);
6933        }
6934
6935        if (mPackages.containsKey(pkg.packageName)
6936                || mSharedLibraries.containsKey(pkg.packageName)) {
6937            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6938                    "Application package " + pkg.packageName
6939                    + " already installed.  Skipping duplicate.");
6940        }
6941
6942        // If we're only installing presumed-existing packages, require that the
6943        // scanned APK is both already known and at the path previously established
6944        // for it.  Previously unknown packages we pick up normally, but if we have an
6945        // a priori expectation about this package's install presence, enforce it.
6946        // With a singular exception for new system packages. When an OTA contains
6947        // a new system package, we allow the codepath to change from a system location
6948        // to the user-installed location. If we don't allow this change, any newer,
6949        // user-installed version of the application will be ignored.
6950        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6951            if (mExpectingBetter.containsKey(pkg.packageName)) {
6952                logCriticalInfo(Log.WARN,
6953                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6954            } else {
6955                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6956                if (known != null) {
6957                    if (DEBUG_PACKAGE_SCANNING) {
6958                        Log.d(TAG, "Examining " + pkg.codePath
6959                                + " and requiring known paths " + known.codePathString
6960                                + " & " + known.resourcePathString);
6961                    }
6962                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6963                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6964                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6965                                "Application package " + pkg.packageName
6966                                + " found at " + pkg.applicationInfo.getCodePath()
6967                                + " but expected at " + known.codePathString + "; ignoring.");
6968                    }
6969                }
6970            }
6971        }
6972
6973        // Initialize package source and resource directories
6974        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6975        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6976
6977        SharedUserSetting suid = null;
6978        PackageSetting pkgSetting = null;
6979
6980        if (!isSystemApp(pkg)) {
6981            // Only system apps can use these features.
6982            pkg.mOriginalPackages = null;
6983            pkg.mRealPackage = null;
6984            pkg.mAdoptPermissions = null;
6985        }
6986
6987        // writer
6988        synchronized (mPackages) {
6989            if (pkg.mSharedUserId != null) {
6990                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6991                if (suid == null) {
6992                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6993                            "Creating application package " + pkg.packageName
6994                            + " for shared user failed");
6995                }
6996                if (DEBUG_PACKAGE_SCANNING) {
6997                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6998                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6999                                + "): packages=" + suid.packages);
7000                }
7001            }
7002
7003            // Check if we are renaming from an original package name.
7004            PackageSetting origPackage = null;
7005            String realName = null;
7006            if (pkg.mOriginalPackages != null) {
7007                // This package may need to be renamed to a previously
7008                // installed name.  Let's check on that...
7009                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7010                if (pkg.mOriginalPackages.contains(renamed)) {
7011                    // This package had originally been installed as the
7012                    // original name, and we have already taken care of
7013                    // transitioning to the new one.  Just update the new
7014                    // one to continue using the old name.
7015                    realName = pkg.mRealPackage;
7016                    if (!pkg.packageName.equals(renamed)) {
7017                        // Callers into this function may have already taken
7018                        // care of renaming the package; only do it here if
7019                        // it is not already done.
7020                        pkg.setPackageName(renamed);
7021                    }
7022
7023                } else {
7024                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7025                        if ((origPackage = mSettings.peekPackageLPr(
7026                                pkg.mOriginalPackages.get(i))) != null) {
7027                            // We do have the package already installed under its
7028                            // original name...  should we use it?
7029                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7030                                // New package is not compatible with original.
7031                                origPackage = null;
7032                                continue;
7033                            } else if (origPackage.sharedUser != null) {
7034                                // Make sure uid is compatible between packages.
7035                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7036                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7037                                            + " to " + pkg.packageName + ": old uid "
7038                                            + origPackage.sharedUser.name
7039                                            + " differs from " + pkg.mSharedUserId);
7040                                    origPackage = null;
7041                                    continue;
7042                                }
7043                            } else {
7044                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7045                                        + pkg.packageName + " to old name " + origPackage.name);
7046                            }
7047                            break;
7048                        }
7049                    }
7050                }
7051            }
7052
7053            if (mTransferedPackages.contains(pkg.packageName)) {
7054                Slog.w(TAG, "Package " + pkg.packageName
7055                        + " was transferred to another, but its .apk remains");
7056            }
7057
7058            // Just create the setting, don't add it yet. For already existing packages
7059            // the PkgSetting exists already and doesn't have to be created.
7060            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7061                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7062                    pkg.applicationInfo.primaryCpuAbi,
7063                    pkg.applicationInfo.secondaryCpuAbi,
7064                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7065                    user, false);
7066            if (pkgSetting == null) {
7067                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7068                        "Creating application package " + pkg.packageName + " failed");
7069            }
7070
7071            if (pkgSetting.origPackage != null) {
7072                // If we are first transitioning from an original package,
7073                // fix up the new package's name now.  We need to do this after
7074                // looking up the package under its new name, so getPackageLP
7075                // can take care of fiddling things correctly.
7076                pkg.setPackageName(origPackage.name);
7077
7078                // File a report about this.
7079                String msg = "New package " + pkgSetting.realName
7080                        + " renamed to replace old package " + pkgSetting.name;
7081                reportSettingsProblem(Log.WARN, msg);
7082
7083                // Make a note of it.
7084                mTransferedPackages.add(origPackage.name);
7085
7086                // No longer need to retain this.
7087                pkgSetting.origPackage = null;
7088            }
7089
7090            if (realName != null) {
7091                // Make a note of it.
7092                mTransferedPackages.add(pkg.packageName);
7093            }
7094
7095            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7096                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7097            }
7098
7099            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7100                // Check all shared libraries and map to their actual file path.
7101                // We only do this here for apps not on a system dir, because those
7102                // are the only ones that can fail an install due to this.  We
7103                // will take care of the system apps by updating all of their
7104                // library paths after the scan is done.
7105                updateSharedLibrariesLPw(pkg, null);
7106            }
7107
7108            if (mFoundPolicyFile) {
7109                SELinuxMMAC.assignSeinfoValue(pkg);
7110            }
7111
7112            pkg.applicationInfo.uid = pkgSetting.appId;
7113            pkg.mExtras = pkgSetting;
7114            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7115                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7116                    // We just determined the app is signed correctly, so bring
7117                    // over the latest parsed certs.
7118                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7119                } else {
7120                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7121                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7122                                "Package " + pkg.packageName + " upgrade keys do not match the "
7123                                + "previously installed version");
7124                    } else {
7125                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7126                        String msg = "System package " + pkg.packageName
7127                            + " signature changed; retaining data.";
7128                        reportSettingsProblem(Log.WARN, msg);
7129                    }
7130                }
7131            } else {
7132                try {
7133                    verifySignaturesLP(pkgSetting, pkg);
7134                    // We just determined the app is signed correctly, so bring
7135                    // over the latest parsed certs.
7136                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7137                } catch (PackageManagerException e) {
7138                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7139                        throw e;
7140                    }
7141                    // The signature has changed, but this package is in the system
7142                    // image...  let's recover!
7143                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7144                    // However...  if this package is part of a shared user, but it
7145                    // doesn't match the signature of the shared user, let's fail.
7146                    // What this means is that you can't change the signatures
7147                    // associated with an overall shared user, which doesn't seem all
7148                    // that unreasonable.
7149                    if (pkgSetting.sharedUser != null) {
7150                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7151                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7152                            throw new PackageManagerException(
7153                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7154                                            "Signature mismatch for shared user : "
7155                                            + pkgSetting.sharedUser);
7156                        }
7157                    }
7158                    // File a report about this.
7159                    String msg = "System package " + pkg.packageName
7160                        + " signature changed; retaining data.";
7161                    reportSettingsProblem(Log.WARN, msg);
7162                }
7163            }
7164            // Verify that this new package doesn't have any content providers
7165            // that conflict with existing packages.  Only do this if the
7166            // package isn't already installed, since we don't want to break
7167            // things that are installed.
7168            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7169                final int N = pkg.providers.size();
7170                int i;
7171                for (i=0; i<N; i++) {
7172                    PackageParser.Provider p = pkg.providers.get(i);
7173                    if (p.info.authority != null) {
7174                        String names[] = p.info.authority.split(";");
7175                        for (int j = 0; j < names.length; j++) {
7176                            if (mProvidersByAuthority.containsKey(names[j])) {
7177                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7178                                final String otherPackageName =
7179                                        ((other != null && other.getComponentName() != null) ?
7180                                                other.getComponentName().getPackageName() : "?");
7181                                throw new PackageManagerException(
7182                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7183                                                "Can't install because provider name " + names[j]
7184                                                + " (in package " + pkg.applicationInfo.packageName
7185                                                + ") is already used by " + otherPackageName);
7186                            }
7187                        }
7188                    }
7189                }
7190            }
7191
7192            if (pkg.mAdoptPermissions != null) {
7193                // This package wants to adopt ownership of permissions from
7194                // another package.
7195                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7196                    final String origName = pkg.mAdoptPermissions.get(i);
7197                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7198                    if (orig != null) {
7199                        if (verifyPackageUpdateLPr(orig, pkg)) {
7200                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7201                                    + pkg.packageName);
7202                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7203                        }
7204                    }
7205                }
7206            }
7207        }
7208
7209        final String pkgName = pkg.packageName;
7210
7211        final long scanFileTime = scanFile.lastModified();
7212        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7213        pkg.applicationInfo.processName = fixProcessName(
7214                pkg.applicationInfo.packageName,
7215                pkg.applicationInfo.processName,
7216                pkg.applicationInfo.uid);
7217
7218        if (pkg != mPlatformPackage) {
7219            // This is a normal package, need to make its data directory.
7220            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7221                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7222
7223            boolean uidError = false;
7224            if (dataPath.exists()) {
7225                int currentUid = 0;
7226                try {
7227                    StructStat stat = Os.stat(dataPath.getPath());
7228                    currentUid = stat.st_uid;
7229                } catch (ErrnoException e) {
7230                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7231                }
7232
7233                // If we have mismatched owners for the data path, we have a problem.
7234                if (currentUid != pkg.applicationInfo.uid) {
7235                    boolean recovered = false;
7236                    if (currentUid == 0) {
7237                        // The directory somehow became owned by root.  Wow.
7238                        // This is probably because the system was stopped while
7239                        // installd was in the middle of messing with its libs
7240                        // directory.  Ask installd to fix that.
7241                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7242                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7243                        if (ret >= 0) {
7244                            recovered = true;
7245                            String msg = "Package " + pkg.packageName
7246                                    + " unexpectedly changed to uid 0; recovered to " +
7247                                    + pkg.applicationInfo.uid;
7248                            reportSettingsProblem(Log.WARN, msg);
7249                        }
7250                    }
7251                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7252                            || (scanFlags&SCAN_BOOTING) != 0)) {
7253                        // If this is a system app, we can at least delete its
7254                        // current data so the application will still work.
7255                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7256                        if (ret >= 0) {
7257                            // TODO: Kill the processes first
7258                            // Old data gone!
7259                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7260                                    ? "System package " : "Third party package ";
7261                            String msg = prefix + pkg.packageName
7262                                    + " has changed from uid: "
7263                                    + currentUid + " to "
7264                                    + pkg.applicationInfo.uid + "; old data erased";
7265                            reportSettingsProblem(Log.WARN, msg);
7266                            recovered = true;
7267                        }
7268                        if (!recovered) {
7269                            mHasSystemUidErrors = true;
7270                        }
7271                    } else if (!recovered) {
7272                        // If we allow this install to proceed, we will be broken.
7273                        // Abort, abort!
7274                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7275                                "scanPackageLI");
7276                    }
7277                    if (!recovered) {
7278                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7279                            + pkg.applicationInfo.uid + "/fs_"
7280                            + currentUid;
7281                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7282                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7283                        String msg = "Package " + pkg.packageName
7284                                + " has mismatched uid: "
7285                                + currentUid + " on disk, "
7286                                + pkg.applicationInfo.uid + " in settings";
7287                        // writer
7288                        synchronized (mPackages) {
7289                            mSettings.mReadMessages.append(msg);
7290                            mSettings.mReadMessages.append('\n');
7291                            uidError = true;
7292                            if (!pkgSetting.uidError) {
7293                                reportSettingsProblem(Log.ERROR, msg);
7294                            }
7295                        }
7296                    }
7297                }
7298
7299                // Ensure that directories are prepared
7300                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7301                        pkg.applicationInfo.seinfo);
7302
7303                if (mShouldRestoreconData) {
7304                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7305                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7306                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7307                }
7308            } else {
7309                if (DEBUG_PACKAGE_SCANNING) {
7310                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7311                        Log.v(TAG, "Want this data dir: " + dataPath);
7312                }
7313                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7314                        pkg.applicationInfo.seinfo);
7315            }
7316
7317            // Get all of our default paths setup
7318            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7319
7320            pkgSetting.uidError = uidError;
7321        }
7322
7323        final String path = scanFile.getPath();
7324        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7325
7326        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7327            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7328
7329            // Some system apps still use directory structure for native libraries
7330            // in which case we might end up not detecting abi solely based on apk
7331            // structure. Try to detect abi based on directory structure.
7332            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7333                    pkg.applicationInfo.primaryCpuAbi == null) {
7334                setBundledAppAbisAndRoots(pkg, pkgSetting);
7335                setNativeLibraryPaths(pkg);
7336            }
7337
7338        } else {
7339            if ((scanFlags & SCAN_MOVE) != 0) {
7340                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7341                // but we already have this packages package info in the PackageSetting. We just
7342                // use that and derive the native library path based on the new codepath.
7343                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7344                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7345            }
7346
7347            // Set native library paths again. For moves, the path will be updated based on the
7348            // ABIs we've determined above. For non-moves, the path will be updated based on the
7349            // ABIs we determined during compilation, but the path will depend on the final
7350            // package path (after the rename away from the stage path).
7351            setNativeLibraryPaths(pkg);
7352        }
7353
7354        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7355        final int[] userIds = sUserManager.getUserIds();
7356        synchronized (mInstallLock) {
7357            // Make sure all user data directories are ready to roll; we're okay
7358            // if they already exist
7359            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7360                for (int userId : userIds) {
7361                    if (userId != UserHandle.USER_SYSTEM) {
7362                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7363                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7364                                pkg.applicationInfo.seinfo);
7365                    }
7366                }
7367            }
7368
7369            // Create a native library symlink only if we have native libraries
7370            // and if the native libraries are 32 bit libraries. We do not provide
7371            // this symlink for 64 bit libraries.
7372            if (pkg.applicationInfo.primaryCpuAbi != null &&
7373                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7374                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7375                try {
7376                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7377                    for (int userId : userIds) {
7378                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7379                                nativeLibPath, userId) < 0) {
7380                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7381                                    "Failed linking native library dir (user=" + userId + ")");
7382                        }
7383                    }
7384                } finally {
7385                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7386                }
7387            }
7388        }
7389
7390        // This is a special case for the "system" package, where the ABI is
7391        // dictated by the zygote configuration (and init.rc). We should keep track
7392        // of this ABI so that we can deal with "normal" applications that run under
7393        // the same UID correctly.
7394        if (mPlatformPackage == pkg) {
7395            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7396                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7397        }
7398
7399        // If there's a mismatch between the abi-override in the package setting
7400        // and the abiOverride specified for the install. Warn about this because we
7401        // would've already compiled the app without taking the package setting into
7402        // account.
7403        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7404            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7405                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7406                        " for package: " + pkg.packageName);
7407            }
7408        }
7409
7410        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7411        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7412        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7413
7414        // Copy the derived override back to the parsed package, so that we can
7415        // update the package settings accordingly.
7416        pkg.cpuAbiOverride = cpuAbiOverride;
7417
7418        if (DEBUG_ABI_SELECTION) {
7419            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7420                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7421                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7422        }
7423
7424        // Push the derived path down into PackageSettings so we know what to
7425        // clean up at uninstall time.
7426        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7427
7428        if (DEBUG_ABI_SELECTION) {
7429            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7430                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7431                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7432        }
7433
7434        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7435            // We don't do this here during boot because we can do it all
7436            // at once after scanning all existing packages.
7437            //
7438            // We also do this *before* we perform dexopt on this package, so that
7439            // we can avoid redundant dexopts, and also to make sure we've got the
7440            // code and package path correct.
7441            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7442                    pkg, true /* boot complete */);
7443        }
7444
7445        if (mFactoryTest && pkg.requestedPermissions.contains(
7446                android.Manifest.permission.FACTORY_TEST)) {
7447            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7448        }
7449
7450        ArrayList<PackageParser.Package> clientLibPkgs = null;
7451
7452        // writer
7453        synchronized (mPackages) {
7454            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7455                // Only system apps can add new shared libraries.
7456                if (pkg.libraryNames != null) {
7457                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7458                        String name = pkg.libraryNames.get(i);
7459                        boolean allowed = false;
7460                        if (pkg.isUpdatedSystemApp()) {
7461                            // New library entries can only be added through the
7462                            // system image.  This is important to get rid of a lot
7463                            // of nasty edge cases: for example if we allowed a non-
7464                            // system update of the app to add a library, then uninstalling
7465                            // the update would make the library go away, and assumptions
7466                            // we made such as through app install filtering would now
7467                            // have allowed apps on the device which aren't compatible
7468                            // with it.  Better to just have the restriction here, be
7469                            // conservative, and create many fewer cases that can negatively
7470                            // impact the user experience.
7471                            final PackageSetting sysPs = mSettings
7472                                    .getDisabledSystemPkgLPr(pkg.packageName);
7473                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7474                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7475                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7476                                        allowed = true;
7477                                        break;
7478                                    }
7479                                }
7480                            }
7481                        } else {
7482                            allowed = true;
7483                        }
7484                        if (allowed) {
7485                            if (!mSharedLibraries.containsKey(name)) {
7486                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7487                            } else if (!name.equals(pkg.packageName)) {
7488                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7489                                        + name + " already exists; skipping");
7490                            }
7491                        } else {
7492                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7493                                    + name + " that is not declared on system image; skipping");
7494                        }
7495                    }
7496                    if ((scanFlags & SCAN_BOOTING) == 0) {
7497                        // If we are not booting, we need to update any applications
7498                        // that are clients of our shared library.  If we are booting,
7499                        // this will all be done once the scan is complete.
7500                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7501                    }
7502                }
7503            }
7504        }
7505
7506        // Request the ActivityManager to kill the process(only for existing packages)
7507        // so that we do not end up in a confused state while the user is still using the older
7508        // version of the application while the new one gets installed.
7509        if ((scanFlags & SCAN_REPLACING) != 0) {
7510            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7511
7512            killApplication(pkg.applicationInfo.packageName,
7513                        pkg.applicationInfo.uid, "replace pkg");
7514
7515            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7516        }
7517
7518        // Also need to kill any apps that are dependent on the library.
7519        if (clientLibPkgs != null) {
7520            for (int i=0; i<clientLibPkgs.size(); i++) {
7521                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7522                killApplication(clientPkg.applicationInfo.packageName,
7523                        clientPkg.applicationInfo.uid, "update lib");
7524            }
7525        }
7526
7527        // Make sure we're not adding any bogus keyset info
7528        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7529        ksms.assertScannedPackageValid(pkg);
7530
7531        // writer
7532        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7533
7534        boolean createIdmapFailed = false;
7535        synchronized (mPackages) {
7536            // We don't expect installation to fail beyond this point
7537
7538            // Add the new setting to mSettings
7539            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7540            // Add the new setting to mPackages
7541            mPackages.put(pkg.applicationInfo.packageName, pkg);
7542            // Make sure we don't accidentally delete its data.
7543            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7544            while (iter.hasNext()) {
7545                PackageCleanItem item = iter.next();
7546                if (pkgName.equals(item.packageName)) {
7547                    iter.remove();
7548                }
7549            }
7550
7551            // Take care of first install / last update times.
7552            if (currentTime != 0) {
7553                if (pkgSetting.firstInstallTime == 0) {
7554                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7555                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7556                    pkgSetting.lastUpdateTime = currentTime;
7557                }
7558            } else if (pkgSetting.firstInstallTime == 0) {
7559                // We need *something*.  Take time time stamp of the file.
7560                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7561            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7562                if (scanFileTime != pkgSetting.timeStamp) {
7563                    // A package on the system image has changed; consider this
7564                    // to be an update.
7565                    pkgSetting.lastUpdateTime = scanFileTime;
7566                }
7567            }
7568
7569            // Add the package's KeySets to the global KeySetManagerService
7570            ksms.addScannedPackageLPw(pkg);
7571
7572            int N = pkg.providers.size();
7573            StringBuilder r = null;
7574            int i;
7575            for (i=0; i<N; i++) {
7576                PackageParser.Provider p = pkg.providers.get(i);
7577                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7578                        p.info.processName, pkg.applicationInfo.uid);
7579                mProviders.addProvider(p);
7580                p.syncable = p.info.isSyncable;
7581                if (p.info.authority != null) {
7582                    String names[] = p.info.authority.split(";");
7583                    p.info.authority = null;
7584                    for (int j = 0; j < names.length; j++) {
7585                        if (j == 1 && p.syncable) {
7586                            // We only want the first authority for a provider to possibly be
7587                            // syncable, so if we already added this provider using a different
7588                            // authority clear the syncable flag. We copy the provider before
7589                            // changing it because the mProviders object contains a reference
7590                            // to a provider that we don't want to change.
7591                            // Only do this for the second authority since the resulting provider
7592                            // object can be the same for all future authorities for this provider.
7593                            p = new PackageParser.Provider(p);
7594                            p.syncable = false;
7595                        }
7596                        if (!mProvidersByAuthority.containsKey(names[j])) {
7597                            mProvidersByAuthority.put(names[j], p);
7598                            if (p.info.authority == null) {
7599                                p.info.authority = names[j];
7600                            } else {
7601                                p.info.authority = p.info.authority + ";" + names[j];
7602                            }
7603                            if (DEBUG_PACKAGE_SCANNING) {
7604                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7605                                    Log.d(TAG, "Registered content provider: " + names[j]
7606                                            + ", className = " + p.info.name + ", isSyncable = "
7607                                            + p.info.isSyncable);
7608                            }
7609                        } else {
7610                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7611                            Slog.w(TAG, "Skipping provider name " + names[j] +
7612                                    " (in package " + pkg.applicationInfo.packageName +
7613                                    "): name already used by "
7614                                    + ((other != null && other.getComponentName() != null)
7615                                            ? other.getComponentName().getPackageName() : "?"));
7616                        }
7617                    }
7618                }
7619                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7620                    if (r == null) {
7621                        r = new StringBuilder(256);
7622                    } else {
7623                        r.append(' ');
7624                    }
7625                    r.append(p.info.name);
7626                }
7627            }
7628            if (r != null) {
7629                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7630            }
7631
7632            N = pkg.services.size();
7633            r = null;
7634            for (i=0; i<N; i++) {
7635                PackageParser.Service s = pkg.services.get(i);
7636                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7637                        s.info.processName, pkg.applicationInfo.uid);
7638                mServices.addService(s);
7639                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7640                    if (r == null) {
7641                        r = new StringBuilder(256);
7642                    } else {
7643                        r.append(' ');
7644                    }
7645                    r.append(s.info.name);
7646                }
7647            }
7648            if (r != null) {
7649                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7650            }
7651
7652            N = pkg.receivers.size();
7653            r = null;
7654            for (i=0; i<N; i++) {
7655                PackageParser.Activity a = pkg.receivers.get(i);
7656                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7657                        a.info.processName, pkg.applicationInfo.uid);
7658                mReceivers.addActivity(a, "receiver");
7659                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7660                    if (r == null) {
7661                        r = new StringBuilder(256);
7662                    } else {
7663                        r.append(' ');
7664                    }
7665                    r.append(a.info.name);
7666                }
7667            }
7668            if (r != null) {
7669                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7670            }
7671
7672            N = pkg.activities.size();
7673            r = null;
7674            for (i=0; i<N; i++) {
7675                PackageParser.Activity a = pkg.activities.get(i);
7676                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7677                        a.info.processName, pkg.applicationInfo.uid);
7678                mActivities.addActivity(a, "activity");
7679                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7680                    if (r == null) {
7681                        r = new StringBuilder(256);
7682                    } else {
7683                        r.append(' ');
7684                    }
7685                    r.append(a.info.name);
7686                }
7687            }
7688            if (r != null) {
7689                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7690            }
7691
7692            N = pkg.permissionGroups.size();
7693            r = null;
7694            for (i=0; i<N; i++) {
7695                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7696                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7697                if (cur == null) {
7698                    mPermissionGroups.put(pg.info.name, pg);
7699                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7700                        if (r == null) {
7701                            r = new StringBuilder(256);
7702                        } else {
7703                            r.append(' ');
7704                        }
7705                        r.append(pg.info.name);
7706                    }
7707                } else {
7708                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7709                            + pg.info.packageName + " ignored: original from "
7710                            + cur.info.packageName);
7711                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7712                        if (r == null) {
7713                            r = new StringBuilder(256);
7714                        } else {
7715                            r.append(' ');
7716                        }
7717                        r.append("DUP:");
7718                        r.append(pg.info.name);
7719                    }
7720                }
7721            }
7722            if (r != null) {
7723                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7724            }
7725
7726            N = pkg.permissions.size();
7727            r = null;
7728            for (i=0; i<N; i++) {
7729                PackageParser.Permission p = pkg.permissions.get(i);
7730
7731                // Assume by default that we did not install this permission into the system.
7732                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7733
7734                // Now that permission groups have a special meaning, we ignore permission
7735                // groups for legacy apps to prevent unexpected behavior. In particular,
7736                // permissions for one app being granted to someone just becuase they happen
7737                // to be in a group defined by another app (before this had no implications).
7738                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7739                    p.group = mPermissionGroups.get(p.info.group);
7740                    // Warn for a permission in an unknown group.
7741                    if (p.info.group != null && p.group == null) {
7742                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7743                                + p.info.packageName + " in an unknown group " + p.info.group);
7744                    }
7745                }
7746
7747                ArrayMap<String, BasePermission> permissionMap =
7748                        p.tree ? mSettings.mPermissionTrees
7749                                : mSettings.mPermissions;
7750                BasePermission bp = permissionMap.get(p.info.name);
7751
7752                // Allow system apps to redefine non-system permissions
7753                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7754                    final boolean currentOwnerIsSystem = (bp.perm != null
7755                            && isSystemApp(bp.perm.owner));
7756                    if (isSystemApp(p.owner)) {
7757                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7758                            // It's a built-in permission and no owner, take ownership now
7759                            bp.packageSetting = pkgSetting;
7760                            bp.perm = p;
7761                            bp.uid = pkg.applicationInfo.uid;
7762                            bp.sourcePackage = p.info.packageName;
7763                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7764                        } else if (!currentOwnerIsSystem) {
7765                            String msg = "New decl " + p.owner + " of permission  "
7766                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7767                            reportSettingsProblem(Log.WARN, msg);
7768                            bp = null;
7769                        }
7770                    }
7771                }
7772
7773                if (bp == null) {
7774                    bp = new BasePermission(p.info.name, p.info.packageName,
7775                            BasePermission.TYPE_NORMAL);
7776                    permissionMap.put(p.info.name, bp);
7777                }
7778
7779                if (bp.perm == null) {
7780                    if (bp.sourcePackage == null
7781                            || bp.sourcePackage.equals(p.info.packageName)) {
7782                        BasePermission tree = findPermissionTreeLP(p.info.name);
7783                        if (tree == null
7784                                || tree.sourcePackage.equals(p.info.packageName)) {
7785                            bp.packageSetting = pkgSetting;
7786                            bp.perm = p;
7787                            bp.uid = pkg.applicationInfo.uid;
7788                            bp.sourcePackage = p.info.packageName;
7789                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7790                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7791                                if (r == null) {
7792                                    r = new StringBuilder(256);
7793                                } else {
7794                                    r.append(' ');
7795                                }
7796                                r.append(p.info.name);
7797                            }
7798                        } else {
7799                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7800                                    + p.info.packageName + " ignored: base tree "
7801                                    + tree.name + " is from package "
7802                                    + tree.sourcePackage);
7803                        }
7804                    } else {
7805                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7806                                + p.info.packageName + " ignored: original from "
7807                                + bp.sourcePackage);
7808                    }
7809                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7810                    if (r == null) {
7811                        r = new StringBuilder(256);
7812                    } else {
7813                        r.append(' ');
7814                    }
7815                    r.append("DUP:");
7816                    r.append(p.info.name);
7817                }
7818                if (bp.perm == p) {
7819                    bp.protectionLevel = p.info.protectionLevel;
7820                }
7821            }
7822
7823            if (r != null) {
7824                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7825            }
7826
7827            N = pkg.instrumentation.size();
7828            r = null;
7829            for (i=0; i<N; i++) {
7830                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7831                a.info.packageName = pkg.applicationInfo.packageName;
7832                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7833                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7834                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7835                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7836                a.info.dataDir = pkg.applicationInfo.dataDir;
7837                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7838                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7839
7840                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7841                // need other information about the application, like the ABI and what not ?
7842                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7843                mInstrumentation.put(a.getComponentName(), a);
7844                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7845                    if (r == null) {
7846                        r = new StringBuilder(256);
7847                    } else {
7848                        r.append(' ');
7849                    }
7850                    r.append(a.info.name);
7851                }
7852            }
7853            if (r != null) {
7854                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7855            }
7856
7857            if (pkg.protectedBroadcasts != null) {
7858                N = pkg.protectedBroadcasts.size();
7859                for (i=0; i<N; i++) {
7860                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7861                }
7862            }
7863
7864            pkgSetting.setTimeStamp(scanFileTime);
7865
7866            // Create idmap files for pairs of (packages, overlay packages).
7867            // Note: "android", ie framework-res.apk, is handled by native layers.
7868            if (pkg.mOverlayTarget != null) {
7869                // This is an overlay package.
7870                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7871                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7872                        mOverlays.put(pkg.mOverlayTarget,
7873                                new ArrayMap<String, PackageParser.Package>());
7874                    }
7875                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7876                    map.put(pkg.packageName, pkg);
7877                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7878                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7879                        createIdmapFailed = true;
7880                    }
7881                }
7882            } else if (mOverlays.containsKey(pkg.packageName) &&
7883                    !pkg.packageName.equals("android")) {
7884                // This is a regular package, with one or more known overlay packages.
7885                createIdmapsForPackageLI(pkg);
7886            }
7887        }
7888
7889        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7890
7891        if (createIdmapFailed) {
7892            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7893                    "scanPackageLI failed to createIdmap");
7894        }
7895        return pkg;
7896    }
7897
7898    /**
7899     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7900     * is derived purely on the basis of the contents of {@code scanFile} and
7901     * {@code cpuAbiOverride}.
7902     *
7903     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7904     */
7905    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7906                                 String cpuAbiOverride, boolean extractLibs)
7907            throws PackageManagerException {
7908        // TODO: We can probably be smarter about this stuff. For installed apps,
7909        // we can calculate this information at install time once and for all. For
7910        // system apps, we can probably assume that this information doesn't change
7911        // after the first boot scan. As things stand, we do lots of unnecessary work.
7912
7913        // Give ourselves some initial paths; we'll come back for another
7914        // pass once we've determined ABI below.
7915        setNativeLibraryPaths(pkg);
7916
7917        // We would never need to extract libs for forward-locked and external packages,
7918        // since the container service will do it for us. We shouldn't attempt to
7919        // extract libs from system app when it was not updated.
7920        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7921                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7922            extractLibs = false;
7923        }
7924
7925        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7926        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7927
7928        NativeLibraryHelper.Handle handle = null;
7929        try {
7930            handle = NativeLibraryHelper.Handle.create(pkg);
7931            // TODO(multiArch): This can be null for apps that didn't go through the
7932            // usual installation process. We can calculate it again, like we
7933            // do during install time.
7934            //
7935            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7936            // unnecessary.
7937            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7938
7939            // Null out the abis so that they can be recalculated.
7940            pkg.applicationInfo.primaryCpuAbi = null;
7941            pkg.applicationInfo.secondaryCpuAbi = null;
7942            if (isMultiArch(pkg.applicationInfo)) {
7943                // Warn if we've set an abiOverride for multi-lib packages..
7944                // By definition, we need to copy both 32 and 64 bit libraries for
7945                // such packages.
7946                if (pkg.cpuAbiOverride != null
7947                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7948                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7949                }
7950
7951                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7952                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7953                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7954                    if (extractLibs) {
7955                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7956                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7957                                useIsaSpecificSubdirs);
7958                    } else {
7959                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7960                    }
7961                }
7962
7963                maybeThrowExceptionForMultiArchCopy(
7964                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7965
7966                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7967                    if (extractLibs) {
7968                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7969                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7970                                useIsaSpecificSubdirs);
7971                    } else {
7972                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7973                    }
7974                }
7975
7976                maybeThrowExceptionForMultiArchCopy(
7977                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7978
7979                if (abi64 >= 0) {
7980                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7981                }
7982
7983                if (abi32 >= 0) {
7984                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7985                    if (abi64 >= 0) {
7986                        pkg.applicationInfo.secondaryCpuAbi = abi;
7987                    } else {
7988                        pkg.applicationInfo.primaryCpuAbi = abi;
7989                    }
7990                }
7991            } else {
7992                String[] abiList = (cpuAbiOverride != null) ?
7993                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7994
7995                // Enable gross and lame hacks for apps that are built with old
7996                // SDK tools. We must scan their APKs for renderscript bitcode and
7997                // not launch them if it's present. Don't bother checking on devices
7998                // that don't have 64 bit support.
7999                boolean needsRenderScriptOverride = false;
8000                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8001                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8002                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8003                    needsRenderScriptOverride = true;
8004                }
8005
8006                final int copyRet;
8007                if (extractLibs) {
8008                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8009                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8010                } else {
8011                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8012                }
8013
8014                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8015                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8016                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8017                }
8018
8019                if (copyRet >= 0) {
8020                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8021                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8022                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8023                } else if (needsRenderScriptOverride) {
8024                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8025                }
8026            }
8027        } catch (IOException ioe) {
8028            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8029        } finally {
8030            IoUtils.closeQuietly(handle);
8031        }
8032
8033        // Now that we've calculated the ABIs and determined if it's an internal app,
8034        // we will go ahead and populate the nativeLibraryPath.
8035        setNativeLibraryPaths(pkg);
8036    }
8037
8038    /**
8039     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8040     * i.e, so that all packages can be run inside a single process if required.
8041     *
8042     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8043     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8044     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8045     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8046     * updating a package that belongs to a shared user.
8047     *
8048     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8049     * adds unnecessary complexity.
8050     */
8051    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8052            PackageParser.Package scannedPackage, boolean bootComplete) {
8053        String requiredInstructionSet = null;
8054        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8055            requiredInstructionSet = VMRuntime.getInstructionSet(
8056                     scannedPackage.applicationInfo.primaryCpuAbi);
8057        }
8058
8059        PackageSetting requirer = null;
8060        for (PackageSetting ps : packagesForUser) {
8061            // If packagesForUser contains scannedPackage, we skip it. This will happen
8062            // when scannedPackage is an update of an existing package. Without this check,
8063            // we will never be able to change the ABI of any package belonging to a shared
8064            // user, even if it's compatible with other packages.
8065            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8066                if (ps.primaryCpuAbiString == null) {
8067                    continue;
8068                }
8069
8070                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8071                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8072                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8073                    // this but there's not much we can do.
8074                    String errorMessage = "Instruction set mismatch, "
8075                            + ((requirer == null) ? "[caller]" : requirer)
8076                            + " requires " + requiredInstructionSet + " whereas " + ps
8077                            + " requires " + instructionSet;
8078                    Slog.w(TAG, errorMessage);
8079                }
8080
8081                if (requiredInstructionSet == null) {
8082                    requiredInstructionSet = instructionSet;
8083                    requirer = ps;
8084                }
8085            }
8086        }
8087
8088        if (requiredInstructionSet != null) {
8089            String adjustedAbi;
8090            if (requirer != null) {
8091                // requirer != null implies that either scannedPackage was null or that scannedPackage
8092                // did not require an ABI, in which case we have to adjust scannedPackage to match
8093                // the ABI of the set (which is the same as requirer's ABI)
8094                adjustedAbi = requirer.primaryCpuAbiString;
8095                if (scannedPackage != null) {
8096                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8097                }
8098            } else {
8099                // requirer == null implies that we're updating all ABIs in the set to
8100                // match scannedPackage.
8101                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8102            }
8103
8104            for (PackageSetting ps : packagesForUser) {
8105                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8106                    if (ps.primaryCpuAbiString != null) {
8107                        continue;
8108                    }
8109
8110                    ps.primaryCpuAbiString = adjustedAbi;
8111                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8112                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8113                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8114                        mInstaller.rmdex(ps.codePathString,
8115                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8116                    }
8117                }
8118            }
8119        }
8120    }
8121
8122    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8123        synchronized (mPackages) {
8124            mResolverReplaced = true;
8125            // Set up information for custom user intent resolution activity.
8126            mResolveActivity.applicationInfo = pkg.applicationInfo;
8127            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8128            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8129            mResolveActivity.processName = pkg.applicationInfo.packageName;
8130            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8131            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8132                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8133            mResolveActivity.theme = 0;
8134            mResolveActivity.exported = true;
8135            mResolveActivity.enabled = true;
8136            mResolveInfo.activityInfo = mResolveActivity;
8137            mResolveInfo.priority = 0;
8138            mResolveInfo.preferredOrder = 0;
8139            mResolveInfo.match = 0;
8140            mResolveComponentName = mCustomResolverComponentName;
8141            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8142                    mResolveComponentName);
8143        }
8144    }
8145
8146    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8147        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8148
8149        // Set up information for ephemeral installer activity
8150        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8151        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8152        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8153        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8154        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8155        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8156                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8157        mEphemeralInstallerActivity.theme = 0;
8158        mEphemeralInstallerActivity.exported = true;
8159        mEphemeralInstallerActivity.enabled = true;
8160        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8161        mEphemeralInstallerInfo.priority = 0;
8162        mEphemeralInstallerInfo.preferredOrder = 0;
8163        mEphemeralInstallerInfo.match = 0;
8164
8165        if (DEBUG_EPHEMERAL) {
8166            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8167        }
8168    }
8169
8170    private static String calculateBundledApkRoot(final String codePathString) {
8171        final File codePath = new File(codePathString);
8172        final File codeRoot;
8173        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8174            codeRoot = Environment.getRootDirectory();
8175        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8176            codeRoot = Environment.getOemDirectory();
8177        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8178            codeRoot = Environment.getVendorDirectory();
8179        } else {
8180            // Unrecognized code path; take its top real segment as the apk root:
8181            // e.g. /something/app/blah.apk => /something
8182            try {
8183                File f = codePath.getCanonicalFile();
8184                File parent = f.getParentFile();    // non-null because codePath is a file
8185                File tmp;
8186                while ((tmp = parent.getParentFile()) != null) {
8187                    f = parent;
8188                    parent = tmp;
8189                }
8190                codeRoot = f;
8191                Slog.w(TAG, "Unrecognized code path "
8192                        + codePath + " - using " + codeRoot);
8193            } catch (IOException e) {
8194                // Can't canonicalize the code path -- shenanigans?
8195                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8196                return Environment.getRootDirectory().getPath();
8197            }
8198        }
8199        return codeRoot.getPath();
8200    }
8201
8202    /**
8203     * Derive and set the location of native libraries for the given package,
8204     * which varies depending on where and how the package was installed.
8205     */
8206    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8207        final ApplicationInfo info = pkg.applicationInfo;
8208        final String codePath = pkg.codePath;
8209        final File codeFile = new File(codePath);
8210        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8211        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8212
8213        info.nativeLibraryRootDir = null;
8214        info.nativeLibraryRootRequiresIsa = false;
8215        info.nativeLibraryDir = null;
8216        info.secondaryNativeLibraryDir = null;
8217
8218        if (isApkFile(codeFile)) {
8219            // Monolithic install
8220            if (bundledApp) {
8221                // If "/system/lib64/apkname" exists, assume that is the per-package
8222                // native library directory to use; otherwise use "/system/lib/apkname".
8223                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8224                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8225                        getPrimaryInstructionSet(info));
8226
8227                // This is a bundled system app so choose the path based on the ABI.
8228                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8229                // is just the default path.
8230                final String apkName = deriveCodePathName(codePath);
8231                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8232                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8233                        apkName).getAbsolutePath();
8234
8235                if (info.secondaryCpuAbi != null) {
8236                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8237                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8238                            secondaryLibDir, apkName).getAbsolutePath();
8239                }
8240            } else if (asecApp) {
8241                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8242                        .getAbsolutePath();
8243            } else {
8244                final String apkName = deriveCodePathName(codePath);
8245                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8246                        .getAbsolutePath();
8247            }
8248
8249            info.nativeLibraryRootRequiresIsa = false;
8250            info.nativeLibraryDir = info.nativeLibraryRootDir;
8251        } else {
8252            // Cluster install
8253            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8254            info.nativeLibraryRootRequiresIsa = true;
8255
8256            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8257                    getPrimaryInstructionSet(info)).getAbsolutePath();
8258
8259            if (info.secondaryCpuAbi != null) {
8260                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8261                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8262            }
8263        }
8264    }
8265
8266    /**
8267     * Calculate the abis and roots for a bundled app. These can uniquely
8268     * be determined from the contents of the system partition, i.e whether
8269     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8270     * of this information, and instead assume that the system was built
8271     * sensibly.
8272     */
8273    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8274                                           PackageSetting pkgSetting) {
8275        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8276
8277        // If "/system/lib64/apkname" exists, assume that is the per-package
8278        // native library directory to use; otherwise use "/system/lib/apkname".
8279        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8280        setBundledAppAbi(pkg, apkRoot, apkName);
8281        // pkgSetting might be null during rescan following uninstall of updates
8282        // to a bundled app, so accommodate that possibility.  The settings in
8283        // that case will be established later from the parsed package.
8284        //
8285        // If the settings aren't null, sync them up with what we've just derived.
8286        // note that apkRoot isn't stored in the package settings.
8287        if (pkgSetting != null) {
8288            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8289            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8290        }
8291    }
8292
8293    /**
8294     * Deduces the ABI of a bundled app and sets the relevant fields on the
8295     * parsed pkg object.
8296     *
8297     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8298     *        under which system libraries are installed.
8299     * @param apkName the name of the installed package.
8300     */
8301    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8302        final File codeFile = new File(pkg.codePath);
8303
8304        final boolean has64BitLibs;
8305        final boolean has32BitLibs;
8306        if (isApkFile(codeFile)) {
8307            // Monolithic install
8308            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8309            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8310        } else {
8311            // Cluster install
8312            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8313            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8314                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8315                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8316                has64BitLibs = (new File(rootDir, isa)).exists();
8317            } else {
8318                has64BitLibs = false;
8319            }
8320            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8321                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8322                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8323                has32BitLibs = (new File(rootDir, isa)).exists();
8324            } else {
8325                has32BitLibs = false;
8326            }
8327        }
8328
8329        if (has64BitLibs && !has32BitLibs) {
8330            // The package has 64 bit libs, but not 32 bit libs. Its primary
8331            // ABI should be 64 bit. We can safely assume here that the bundled
8332            // native libraries correspond to the most preferred ABI in the list.
8333
8334            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8335            pkg.applicationInfo.secondaryCpuAbi = null;
8336        } else if (has32BitLibs && !has64BitLibs) {
8337            // The package has 32 bit libs but not 64 bit libs. Its primary
8338            // ABI should be 32 bit.
8339
8340            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8341            pkg.applicationInfo.secondaryCpuAbi = null;
8342        } else if (has32BitLibs && has64BitLibs) {
8343            // The application has both 64 and 32 bit bundled libraries. We check
8344            // here that the app declares multiArch support, and warn if it doesn't.
8345            //
8346            // We will be lenient here and record both ABIs. The primary will be the
8347            // ABI that's higher on the list, i.e, a device that's configured to prefer
8348            // 64 bit apps will see a 64 bit primary ABI,
8349
8350            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8351                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8352            }
8353
8354            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8355                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8356                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8357            } else {
8358                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8359                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8360            }
8361        } else {
8362            pkg.applicationInfo.primaryCpuAbi = null;
8363            pkg.applicationInfo.secondaryCpuAbi = null;
8364        }
8365    }
8366
8367    private void killApplication(String pkgName, int appId, String reason) {
8368        // Request the ActivityManager to kill the process(only for existing packages)
8369        // so that we do not end up in a confused state while the user is still using the older
8370        // version of the application while the new one gets installed.
8371        IActivityManager am = ActivityManagerNative.getDefault();
8372        if (am != null) {
8373            try {
8374                am.killApplicationWithAppId(pkgName, appId, reason);
8375            } catch (RemoteException e) {
8376            }
8377        }
8378    }
8379
8380    void removePackageLI(PackageSetting ps, boolean chatty) {
8381        if (DEBUG_INSTALL) {
8382            if (chatty)
8383                Log.d(TAG, "Removing package " + ps.name);
8384        }
8385
8386        // writer
8387        synchronized (mPackages) {
8388            mPackages.remove(ps.name);
8389            final PackageParser.Package pkg = ps.pkg;
8390            if (pkg != null) {
8391                cleanPackageDataStructuresLILPw(pkg, chatty);
8392            }
8393        }
8394    }
8395
8396    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8397        if (DEBUG_INSTALL) {
8398            if (chatty)
8399                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8400        }
8401
8402        // writer
8403        synchronized (mPackages) {
8404            mPackages.remove(pkg.applicationInfo.packageName);
8405            cleanPackageDataStructuresLILPw(pkg, chatty);
8406        }
8407    }
8408
8409    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8410        int N = pkg.providers.size();
8411        StringBuilder r = null;
8412        int i;
8413        for (i=0; i<N; i++) {
8414            PackageParser.Provider p = pkg.providers.get(i);
8415            mProviders.removeProvider(p);
8416            if (p.info.authority == null) {
8417
8418                /* There was another ContentProvider with this authority when
8419                 * this app was installed so this authority is null,
8420                 * Ignore it as we don't have to unregister the provider.
8421                 */
8422                continue;
8423            }
8424            String names[] = p.info.authority.split(";");
8425            for (int j = 0; j < names.length; j++) {
8426                if (mProvidersByAuthority.get(names[j]) == p) {
8427                    mProvidersByAuthority.remove(names[j]);
8428                    if (DEBUG_REMOVE) {
8429                        if (chatty)
8430                            Log.d(TAG, "Unregistered content provider: " + names[j]
8431                                    + ", className = " + p.info.name + ", isSyncable = "
8432                                    + p.info.isSyncable);
8433                    }
8434                }
8435            }
8436            if (DEBUG_REMOVE && chatty) {
8437                if (r == null) {
8438                    r = new StringBuilder(256);
8439                } else {
8440                    r.append(' ');
8441                }
8442                r.append(p.info.name);
8443            }
8444        }
8445        if (r != null) {
8446            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8447        }
8448
8449        N = pkg.services.size();
8450        r = null;
8451        for (i=0; i<N; i++) {
8452            PackageParser.Service s = pkg.services.get(i);
8453            mServices.removeService(s);
8454            if (chatty) {
8455                if (r == null) {
8456                    r = new StringBuilder(256);
8457                } else {
8458                    r.append(' ');
8459                }
8460                r.append(s.info.name);
8461            }
8462        }
8463        if (r != null) {
8464            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8465        }
8466
8467        N = pkg.receivers.size();
8468        r = null;
8469        for (i=0; i<N; i++) {
8470            PackageParser.Activity a = pkg.receivers.get(i);
8471            mReceivers.removeActivity(a, "receiver");
8472            if (DEBUG_REMOVE && chatty) {
8473                if (r == null) {
8474                    r = new StringBuilder(256);
8475                } else {
8476                    r.append(' ');
8477                }
8478                r.append(a.info.name);
8479            }
8480        }
8481        if (r != null) {
8482            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8483        }
8484
8485        N = pkg.activities.size();
8486        r = null;
8487        for (i=0; i<N; i++) {
8488            PackageParser.Activity a = pkg.activities.get(i);
8489            mActivities.removeActivity(a, "activity");
8490            if (DEBUG_REMOVE && chatty) {
8491                if (r == null) {
8492                    r = new StringBuilder(256);
8493                } else {
8494                    r.append(' ');
8495                }
8496                r.append(a.info.name);
8497            }
8498        }
8499        if (r != null) {
8500            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8501        }
8502
8503        N = pkg.permissions.size();
8504        r = null;
8505        for (i=0; i<N; i++) {
8506            PackageParser.Permission p = pkg.permissions.get(i);
8507            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8508            if (bp == null) {
8509                bp = mSettings.mPermissionTrees.get(p.info.name);
8510            }
8511            if (bp != null && bp.perm == p) {
8512                bp.perm = null;
8513                if (DEBUG_REMOVE && chatty) {
8514                    if (r == null) {
8515                        r = new StringBuilder(256);
8516                    } else {
8517                        r.append(' ');
8518                    }
8519                    r.append(p.info.name);
8520                }
8521            }
8522            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8523                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8524                if (appOpPkgs != null) {
8525                    appOpPkgs.remove(pkg.packageName);
8526                }
8527            }
8528        }
8529        if (r != null) {
8530            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8531        }
8532
8533        N = pkg.requestedPermissions.size();
8534        r = null;
8535        for (i=0; i<N; i++) {
8536            String perm = pkg.requestedPermissions.get(i);
8537            BasePermission bp = mSettings.mPermissions.get(perm);
8538            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8539                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8540                if (appOpPkgs != null) {
8541                    appOpPkgs.remove(pkg.packageName);
8542                    if (appOpPkgs.isEmpty()) {
8543                        mAppOpPermissionPackages.remove(perm);
8544                    }
8545                }
8546            }
8547        }
8548        if (r != null) {
8549            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8550        }
8551
8552        N = pkg.instrumentation.size();
8553        r = null;
8554        for (i=0; i<N; i++) {
8555            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8556            mInstrumentation.remove(a.getComponentName());
8557            if (DEBUG_REMOVE && chatty) {
8558                if (r == null) {
8559                    r = new StringBuilder(256);
8560                } else {
8561                    r.append(' ');
8562                }
8563                r.append(a.info.name);
8564            }
8565        }
8566        if (r != null) {
8567            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8568        }
8569
8570        r = null;
8571        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8572            // Only system apps can hold shared libraries.
8573            if (pkg.libraryNames != null) {
8574                for (i=0; i<pkg.libraryNames.size(); i++) {
8575                    String name = pkg.libraryNames.get(i);
8576                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8577                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8578                        mSharedLibraries.remove(name);
8579                        if (DEBUG_REMOVE && chatty) {
8580                            if (r == null) {
8581                                r = new StringBuilder(256);
8582                            } else {
8583                                r.append(' ');
8584                            }
8585                            r.append(name);
8586                        }
8587                    }
8588                }
8589            }
8590        }
8591        if (r != null) {
8592            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8593        }
8594    }
8595
8596    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8597        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8598            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8599                return true;
8600            }
8601        }
8602        return false;
8603    }
8604
8605    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8606    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8607    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8608
8609    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8610            int flags) {
8611        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8612        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8613    }
8614
8615    private void updatePermissionsLPw(String changingPkg,
8616            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8617        // Make sure there are no dangling permission trees.
8618        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8619        while (it.hasNext()) {
8620            final BasePermission bp = it.next();
8621            if (bp.packageSetting == null) {
8622                // We may not yet have parsed the package, so just see if
8623                // we still know about its settings.
8624                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8625            }
8626            if (bp.packageSetting == null) {
8627                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8628                        + " from package " + bp.sourcePackage);
8629                it.remove();
8630            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8631                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8632                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8633                            + " from package " + bp.sourcePackage);
8634                    flags |= UPDATE_PERMISSIONS_ALL;
8635                    it.remove();
8636                }
8637            }
8638        }
8639
8640        // Make sure all dynamic permissions have been assigned to a package,
8641        // and make sure there are no dangling permissions.
8642        it = mSettings.mPermissions.values().iterator();
8643        while (it.hasNext()) {
8644            final BasePermission bp = it.next();
8645            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8646                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8647                        + bp.name + " pkg=" + bp.sourcePackage
8648                        + " info=" + bp.pendingInfo);
8649                if (bp.packageSetting == null && bp.pendingInfo != null) {
8650                    final BasePermission tree = findPermissionTreeLP(bp.name);
8651                    if (tree != null && tree.perm != null) {
8652                        bp.packageSetting = tree.packageSetting;
8653                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8654                                new PermissionInfo(bp.pendingInfo));
8655                        bp.perm.info.packageName = tree.perm.info.packageName;
8656                        bp.perm.info.name = bp.name;
8657                        bp.uid = tree.uid;
8658                    }
8659                }
8660            }
8661            if (bp.packageSetting == null) {
8662                // We may not yet have parsed the package, so just see if
8663                // we still know about its settings.
8664                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8665            }
8666            if (bp.packageSetting == null) {
8667                Slog.w(TAG, "Removing dangling permission: " + bp.name
8668                        + " from package " + bp.sourcePackage);
8669                it.remove();
8670            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8671                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8672                    Slog.i(TAG, "Removing old permission: " + bp.name
8673                            + " from package " + bp.sourcePackage);
8674                    flags |= UPDATE_PERMISSIONS_ALL;
8675                    it.remove();
8676                }
8677            }
8678        }
8679
8680        // Now update the permissions for all packages, in particular
8681        // replace the granted permissions of the system packages.
8682        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8683            for (PackageParser.Package pkg : mPackages.values()) {
8684                if (pkg != pkgInfo) {
8685                    // Only replace for packages on requested volume
8686                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8687                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8688                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8689                    grantPermissionsLPw(pkg, replace, changingPkg);
8690                }
8691            }
8692        }
8693
8694        if (pkgInfo != null) {
8695            // Only replace for packages on requested volume
8696            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8697            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8698                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8699            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8700        }
8701    }
8702
8703    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8704            String packageOfInterest) {
8705        // IMPORTANT: There are two types of permissions: install and runtime.
8706        // Install time permissions are granted when the app is installed to
8707        // all device users and users added in the future. Runtime permissions
8708        // are granted at runtime explicitly to specific users. Normal and signature
8709        // protected permissions are install time permissions. Dangerous permissions
8710        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8711        // otherwise they are runtime permissions. This function does not manage
8712        // runtime permissions except for the case an app targeting Lollipop MR1
8713        // being upgraded to target a newer SDK, in which case dangerous permissions
8714        // are transformed from install time to runtime ones.
8715
8716        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8717        if (ps == null) {
8718            return;
8719        }
8720
8721        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8722
8723        PermissionsState permissionsState = ps.getPermissionsState();
8724        PermissionsState origPermissions = permissionsState;
8725
8726        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8727
8728        boolean runtimePermissionsRevoked = false;
8729        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8730
8731        boolean changedInstallPermission = false;
8732
8733        if (replace) {
8734            ps.installPermissionsFixed = false;
8735            if (!ps.isSharedUser()) {
8736                origPermissions = new PermissionsState(permissionsState);
8737                permissionsState.reset();
8738            } else {
8739                // We need to know only about runtime permission changes since the
8740                // calling code always writes the install permissions state but
8741                // the runtime ones are written only if changed. The only cases of
8742                // changed runtime permissions here are promotion of an install to
8743                // runtime and revocation of a runtime from a shared user.
8744                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8745                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8746                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8747                    runtimePermissionsRevoked = true;
8748                }
8749            }
8750        }
8751
8752        permissionsState.setGlobalGids(mGlobalGids);
8753
8754        final int N = pkg.requestedPermissions.size();
8755        for (int i=0; i<N; i++) {
8756            final String name = pkg.requestedPermissions.get(i);
8757            final BasePermission bp = mSettings.mPermissions.get(name);
8758
8759            if (DEBUG_INSTALL) {
8760                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8761            }
8762
8763            if (bp == null || bp.packageSetting == null) {
8764                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8765                    Slog.w(TAG, "Unknown permission " + name
8766                            + " in package " + pkg.packageName);
8767                }
8768                continue;
8769            }
8770
8771            final String perm = bp.name;
8772            boolean allowedSig = false;
8773            int grant = GRANT_DENIED;
8774
8775            // Keep track of app op permissions.
8776            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8777                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8778                if (pkgs == null) {
8779                    pkgs = new ArraySet<>();
8780                    mAppOpPermissionPackages.put(bp.name, pkgs);
8781                }
8782                pkgs.add(pkg.packageName);
8783            }
8784
8785            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8786            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8787                    >= Build.VERSION_CODES.M;
8788            switch (level) {
8789                case PermissionInfo.PROTECTION_NORMAL: {
8790                    // For all apps normal permissions are install time ones.
8791                    grant = GRANT_INSTALL;
8792                } break;
8793
8794                case PermissionInfo.PROTECTION_DANGEROUS: {
8795                    // If a permission review is required for legacy apps we represent
8796                    // their permissions as always granted runtime ones since we need
8797                    // to keep the review required permission flag per user while an
8798                    // install permission's state is shared across all users.
8799                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8800                        // For legacy apps dangerous permissions are install time ones.
8801                        grant = GRANT_INSTALL;
8802                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8803                        // For legacy apps that became modern, install becomes runtime.
8804                        grant = GRANT_UPGRADE;
8805                    } else if (mPromoteSystemApps
8806                            && isSystemApp(ps)
8807                            && mExistingSystemPackages.contains(ps.name)) {
8808                        // For legacy system apps, install becomes runtime.
8809                        // We cannot check hasInstallPermission() for system apps since those
8810                        // permissions were granted implicitly and not persisted pre-M.
8811                        grant = GRANT_UPGRADE;
8812                    } else {
8813                        // For modern apps keep runtime permissions unchanged.
8814                        grant = GRANT_RUNTIME;
8815                    }
8816                } break;
8817
8818                case PermissionInfo.PROTECTION_SIGNATURE: {
8819                    // For all apps signature permissions are install time ones.
8820                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8821                    if (allowedSig) {
8822                        grant = GRANT_INSTALL;
8823                    }
8824                } break;
8825            }
8826
8827            if (DEBUG_INSTALL) {
8828                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8829            }
8830
8831            if (grant != GRANT_DENIED) {
8832                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8833                    // If this is an existing, non-system package, then
8834                    // we can't add any new permissions to it.
8835                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8836                        // Except...  if this is a permission that was added
8837                        // to the platform (note: need to only do this when
8838                        // updating the platform).
8839                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8840                            grant = GRANT_DENIED;
8841                        }
8842                    }
8843                }
8844
8845                switch (grant) {
8846                    case GRANT_INSTALL: {
8847                        // Revoke this as runtime permission to handle the case of
8848                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8849                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8850                            if (origPermissions.getRuntimePermissionState(
8851                                    bp.name, userId) != null) {
8852                                // Revoke the runtime permission and clear the flags.
8853                                origPermissions.revokeRuntimePermission(bp, userId);
8854                                origPermissions.updatePermissionFlags(bp, userId,
8855                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8856                                // If we revoked a permission permission, we have to write.
8857                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8858                                        changedRuntimePermissionUserIds, userId);
8859                            }
8860                        }
8861                        // Grant an install permission.
8862                        if (permissionsState.grantInstallPermission(bp) !=
8863                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8864                            changedInstallPermission = true;
8865                        }
8866                    } break;
8867
8868                    case GRANT_RUNTIME: {
8869                        // Grant previously granted runtime permissions.
8870                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8871                            PermissionState permissionState = origPermissions
8872                                    .getRuntimePermissionState(bp.name, userId);
8873                            int flags = permissionState != null
8874                                    ? permissionState.getFlags() : 0;
8875                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8876                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8877                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8878                                    // If we cannot put the permission as it was, we have to write.
8879                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8880                                            changedRuntimePermissionUserIds, userId);
8881                                }
8882                                // If the app supports runtime permissions no need for a review.
8883                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8884                                        && appSupportsRuntimePermissions
8885                                        && (flags & PackageManager
8886                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8887                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8888                                    // Since we changed the flags, we have to write.
8889                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8890                                            changedRuntimePermissionUserIds, userId);
8891                                }
8892                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8893                                    && !appSupportsRuntimePermissions) {
8894                                // For legacy apps that need a permission review, every new
8895                                // runtime permission is granted but it is pending a review.
8896                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8897                                    permissionsState.grantRuntimePermission(bp, userId);
8898                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8899                                    // We changed the permission and flags, hence have to write.
8900                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8901                                            changedRuntimePermissionUserIds, userId);
8902                                }
8903                            }
8904                            // Propagate the permission flags.
8905                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8906                        }
8907                    } break;
8908
8909                    case GRANT_UPGRADE: {
8910                        // Grant runtime permissions for a previously held install permission.
8911                        PermissionState permissionState = origPermissions
8912                                .getInstallPermissionState(bp.name);
8913                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8914
8915                        if (origPermissions.revokeInstallPermission(bp)
8916                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8917                            // We will be transferring the permission flags, so clear them.
8918                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8919                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8920                            changedInstallPermission = true;
8921                        }
8922
8923                        // If the permission is not to be promoted to runtime we ignore it and
8924                        // also its other flags as they are not applicable to install permissions.
8925                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8926                            for (int userId : currentUserIds) {
8927                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8928                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8929                                    // Transfer the permission flags.
8930                                    permissionsState.updatePermissionFlags(bp, userId,
8931                                            flags, flags);
8932                                    // If we granted the permission, we have to write.
8933                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8934                                            changedRuntimePermissionUserIds, userId);
8935                                }
8936                            }
8937                        }
8938                    } break;
8939
8940                    default: {
8941                        if (packageOfInterest == null
8942                                || packageOfInterest.equals(pkg.packageName)) {
8943                            Slog.w(TAG, "Not granting permission " + perm
8944                                    + " to package " + pkg.packageName
8945                                    + " because it was previously installed without");
8946                        }
8947                    } break;
8948                }
8949            } else {
8950                if (permissionsState.revokeInstallPermission(bp) !=
8951                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8952                    // Also drop the permission flags.
8953                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8954                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8955                    changedInstallPermission = true;
8956                    Slog.i(TAG, "Un-granting permission " + perm
8957                            + " from package " + pkg.packageName
8958                            + " (protectionLevel=" + bp.protectionLevel
8959                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8960                            + ")");
8961                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8962                    // Don't print warning for app op permissions, since it is fine for them
8963                    // not to be granted, there is a UI for the user to decide.
8964                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8965                        Slog.w(TAG, "Not granting permission " + perm
8966                                + " to package " + pkg.packageName
8967                                + " (protectionLevel=" + bp.protectionLevel
8968                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8969                                + ")");
8970                    }
8971                }
8972            }
8973        }
8974
8975        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8976                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8977            // This is the first that we have heard about this package, so the
8978            // permissions we have now selected are fixed until explicitly
8979            // changed.
8980            ps.installPermissionsFixed = true;
8981        }
8982
8983        // Persist the runtime permissions state for users with changes. If permissions
8984        // were revoked because no app in the shared user declares them we have to
8985        // write synchronously to avoid losing runtime permissions state.
8986        for (int userId : changedRuntimePermissionUserIds) {
8987            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8988        }
8989
8990        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8991    }
8992
8993    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8994        boolean allowed = false;
8995        final int NP = PackageParser.NEW_PERMISSIONS.length;
8996        for (int ip=0; ip<NP; ip++) {
8997            final PackageParser.NewPermissionInfo npi
8998                    = PackageParser.NEW_PERMISSIONS[ip];
8999            if (npi.name.equals(perm)
9000                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9001                allowed = true;
9002                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9003                        + pkg.packageName);
9004                break;
9005            }
9006        }
9007        return allowed;
9008    }
9009
9010    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9011            BasePermission bp, PermissionsState origPermissions) {
9012        boolean allowed;
9013        allowed = (compareSignatures(
9014                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9015                        == PackageManager.SIGNATURE_MATCH)
9016                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9017                        == PackageManager.SIGNATURE_MATCH);
9018        if (!allowed && (bp.protectionLevel
9019                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9020            if (isSystemApp(pkg)) {
9021                // For updated system applications, a system permission
9022                // is granted only if it had been defined by the original application.
9023                if (pkg.isUpdatedSystemApp()) {
9024                    final PackageSetting sysPs = mSettings
9025                            .getDisabledSystemPkgLPr(pkg.packageName);
9026                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9027                        // If the original was granted this permission, we take
9028                        // that grant decision as read and propagate it to the
9029                        // update.
9030                        if (sysPs.isPrivileged()) {
9031                            allowed = true;
9032                        }
9033                    } else {
9034                        // The system apk may have been updated with an older
9035                        // version of the one on the data partition, but which
9036                        // granted a new system permission that it didn't have
9037                        // before.  In this case we do want to allow the app to
9038                        // now get the new permission if the ancestral apk is
9039                        // privileged to get it.
9040                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9041                            for (int j=0;
9042                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9043                                if (perm.equals(
9044                                        sysPs.pkg.requestedPermissions.get(j))) {
9045                                    allowed = true;
9046                                    break;
9047                                }
9048                            }
9049                        }
9050                    }
9051                } else {
9052                    allowed = isPrivilegedApp(pkg);
9053                }
9054            }
9055        }
9056        if (!allowed) {
9057            if (!allowed && (bp.protectionLevel
9058                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9059                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9060                // If this was a previously normal/dangerous permission that got moved
9061                // to a system permission as part of the runtime permission redesign, then
9062                // we still want to blindly grant it to old apps.
9063                allowed = true;
9064            }
9065            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9066                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9067                // If this permission is to be granted to the system installer and
9068                // this app is an installer, then it gets the permission.
9069                allowed = true;
9070            }
9071            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9072                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9073                // If this permission is to be granted to the system verifier and
9074                // this app is a verifier, then it gets the permission.
9075                allowed = true;
9076            }
9077            if (!allowed && (bp.protectionLevel
9078                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9079                    && isSystemApp(pkg)) {
9080                // Any pre-installed system app is allowed to get this permission.
9081                allowed = true;
9082            }
9083            if (!allowed && (bp.protectionLevel
9084                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9085                // For development permissions, a development permission
9086                // is granted only if it was already granted.
9087                allowed = origPermissions.hasInstallPermission(perm);
9088            }
9089        }
9090        return allowed;
9091    }
9092
9093    final class ActivityIntentResolver
9094            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9095        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9096                boolean defaultOnly, int userId) {
9097            if (!sUserManager.exists(userId)) return null;
9098            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9099            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9100        }
9101
9102        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9103                int userId) {
9104            if (!sUserManager.exists(userId)) return null;
9105            mFlags = flags;
9106            return super.queryIntent(intent, resolvedType,
9107                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9108        }
9109
9110        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9111                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9112            if (!sUserManager.exists(userId)) return null;
9113            if (packageActivities == null) {
9114                return null;
9115            }
9116            mFlags = flags;
9117            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9118            final int N = packageActivities.size();
9119            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9120                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9121
9122            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9123            for (int i = 0; i < N; ++i) {
9124                intentFilters = packageActivities.get(i).intents;
9125                if (intentFilters != null && intentFilters.size() > 0) {
9126                    PackageParser.ActivityIntentInfo[] array =
9127                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9128                    intentFilters.toArray(array);
9129                    listCut.add(array);
9130                }
9131            }
9132            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9133        }
9134
9135        public final void addActivity(PackageParser.Activity a, String type) {
9136            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9137            mActivities.put(a.getComponentName(), a);
9138            if (DEBUG_SHOW_INFO)
9139                Log.v(
9140                TAG, "  " + type + " " +
9141                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9142            if (DEBUG_SHOW_INFO)
9143                Log.v(TAG, "    Class=" + a.info.name);
9144            final int NI = a.intents.size();
9145            for (int j=0; j<NI; j++) {
9146                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9147                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9148                    intent.setPriority(0);
9149                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9150                            + a.className + " with priority > 0, forcing to 0");
9151                }
9152                if (DEBUG_SHOW_INFO) {
9153                    Log.v(TAG, "    IntentFilter:");
9154                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9155                }
9156                if (!intent.debugCheck()) {
9157                    Log.w(TAG, "==> For Activity " + a.info.name);
9158                }
9159                addFilter(intent);
9160            }
9161        }
9162
9163        public final void removeActivity(PackageParser.Activity a, String type) {
9164            mActivities.remove(a.getComponentName());
9165            if (DEBUG_SHOW_INFO) {
9166                Log.v(TAG, "  " + type + " "
9167                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9168                                : a.info.name) + ":");
9169                Log.v(TAG, "    Class=" + a.info.name);
9170            }
9171            final int NI = a.intents.size();
9172            for (int j=0; j<NI; j++) {
9173                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9174                if (DEBUG_SHOW_INFO) {
9175                    Log.v(TAG, "    IntentFilter:");
9176                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9177                }
9178                removeFilter(intent);
9179            }
9180        }
9181
9182        @Override
9183        protected boolean allowFilterResult(
9184                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9185            ActivityInfo filterAi = filter.activity.info;
9186            for (int i=dest.size()-1; i>=0; i--) {
9187                ActivityInfo destAi = dest.get(i).activityInfo;
9188                if (destAi.name == filterAi.name
9189                        && destAi.packageName == filterAi.packageName) {
9190                    return false;
9191                }
9192            }
9193            return true;
9194        }
9195
9196        @Override
9197        protected ActivityIntentInfo[] newArray(int size) {
9198            return new ActivityIntentInfo[size];
9199        }
9200
9201        @Override
9202        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9203            if (!sUserManager.exists(userId)) return true;
9204            PackageParser.Package p = filter.activity.owner;
9205            if (p != null) {
9206                PackageSetting ps = (PackageSetting)p.mExtras;
9207                if (ps != null) {
9208                    // System apps are never considered stopped for purposes of
9209                    // filtering, because there may be no way for the user to
9210                    // actually re-launch them.
9211                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9212                            && ps.getStopped(userId);
9213                }
9214            }
9215            return false;
9216        }
9217
9218        @Override
9219        protected boolean isPackageForFilter(String packageName,
9220                PackageParser.ActivityIntentInfo info) {
9221            return packageName.equals(info.activity.owner.packageName);
9222        }
9223
9224        @Override
9225        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9226                int match, int userId) {
9227            if (!sUserManager.exists(userId)) return null;
9228            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9229                return null;
9230            }
9231            final PackageParser.Activity activity = info.activity;
9232            if (mSafeMode && (activity.info.applicationInfo.flags
9233                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9234                return null;
9235            }
9236            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9237            if (ps == null) {
9238                return null;
9239            }
9240            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9241                    ps.readUserState(userId), userId);
9242            if (ai == null) {
9243                return null;
9244            }
9245            final ResolveInfo res = new ResolveInfo();
9246            res.activityInfo = ai;
9247            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9248                res.filter = info;
9249            }
9250            if (info != null) {
9251                res.handleAllWebDataURI = info.handleAllWebDataURI();
9252            }
9253            res.priority = info.getPriority();
9254            res.preferredOrder = activity.owner.mPreferredOrder;
9255            //System.out.println("Result: " + res.activityInfo.className +
9256            //                   " = " + res.priority);
9257            res.match = match;
9258            res.isDefault = info.hasDefault;
9259            res.labelRes = info.labelRes;
9260            res.nonLocalizedLabel = info.nonLocalizedLabel;
9261            if (userNeedsBadging(userId)) {
9262                res.noResourceId = true;
9263            } else {
9264                res.icon = info.icon;
9265            }
9266            res.iconResourceId = info.icon;
9267            res.system = res.activityInfo.applicationInfo.isSystemApp();
9268            return res;
9269        }
9270
9271        @Override
9272        protected void sortResults(List<ResolveInfo> results) {
9273            Collections.sort(results, mResolvePrioritySorter);
9274        }
9275
9276        @Override
9277        protected void dumpFilter(PrintWriter out, String prefix,
9278                PackageParser.ActivityIntentInfo filter) {
9279            out.print(prefix); out.print(
9280                    Integer.toHexString(System.identityHashCode(filter.activity)));
9281                    out.print(' ');
9282                    filter.activity.printComponentShortName(out);
9283                    out.print(" filter ");
9284                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9285        }
9286
9287        @Override
9288        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9289            return filter.activity;
9290        }
9291
9292        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9293            PackageParser.Activity activity = (PackageParser.Activity)label;
9294            out.print(prefix); out.print(
9295                    Integer.toHexString(System.identityHashCode(activity)));
9296                    out.print(' ');
9297                    activity.printComponentShortName(out);
9298            if (count > 1) {
9299                out.print(" ("); out.print(count); out.print(" filters)");
9300            }
9301            out.println();
9302        }
9303
9304//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9305//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9306//            final List<ResolveInfo> retList = Lists.newArrayList();
9307//            while (i.hasNext()) {
9308//                final ResolveInfo resolveInfo = i.next();
9309//                if (isEnabledLP(resolveInfo.activityInfo)) {
9310//                    retList.add(resolveInfo);
9311//                }
9312//            }
9313//            return retList;
9314//        }
9315
9316        // Keys are String (activity class name), values are Activity.
9317        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9318                = new ArrayMap<ComponentName, PackageParser.Activity>();
9319        private int mFlags;
9320    }
9321
9322    private final class ServiceIntentResolver
9323            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9324        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9325                boolean defaultOnly, int userId) {
9326            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9327            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9328        }
9329
9330        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9331                int userId) {
9332            if (!sUserManager.exists(userId)) return null;
9333            mFlags = flags;
9334            return super.queryIntent(intent, resolvedType,
9335                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9336        }
9337
9338        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9339                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9340            if (!sUserManager.exists(userId)) return null;
9341            if (packageServices == null) {
9342                return null;
9343            }
9344            mFlags = flags;
9345            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9346            final int N = packageServices.size();
9347            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9348                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9349
9350            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9351            for (int i = 0; i < N; ++i) {
9352                intentFilters = packageServices.get(i).intents;
9353                if (intentFilters != null && intentFilters.size() > 0) {
9354                    PackageParser.ServiceIntentInfo[] array =
9355                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9356                    intentFilters.toArray(array);
9357                    listCut.add(array);
9358                }
9359            }
9360            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9361        }
9362
9363        public final void addService(PackageParser.Service s) {
9364            mServices.put(s.getComponentName(), s);
9365            if (DEBUG_SHOW_INFO) {
9366                Log.v(TAG, "  "
9367                        + (s.info.nonLocalizedLabel != null
9368                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9369                Log.v(TAG, "    Class=" + s.info.name);
9370            }
9371            final int NI = s.intents.size();
9372            int j;
9373            for (j=0; j<NI; j++) {
9374                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9375                if (DEBUG_SHOW_INFO) {
9376                    Log.v(TAG, "    IntentFilter:");
9377                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9378                }
9379                if (!intent.debugCheck()) {
9380                    Log.w(TAG, "==> For Service " + s.info.name);
9381                }
9382                addFilter(intent);
9383            }
9384        }
9385
9386        public final void removeService(PackageParser.Service s) {
9387            mServices.remove(s.getComponentName());
9388            if (DEBUG_SHOW_INFO) {
9389                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9390                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9391                Log.v(TAG, "    Class=" + s.info.name);
9392            }
9393            final int NI = s.intents.size();
9394            int j;
9395            for (j=0; j<NI; j++) {
9396                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9397                if (DEBUG_SHOW_INFO) {
9398                    Log.v(TAG, "    IntentFilter:");
9399                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9400                }
9401                removeFilter(intent);
9402            }
9403        }
9404
9405        @Override
9406        protected boolean allowFilterResult(
9407                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9408            ServiceInfo filterSi = filter.service.info;
9409            for (int i=dest.size()-1; i>=0; i--) {
9410                ServiceInfo destAi = dest.get(i).serviceInfo;
9411                if (destAi.name == filterSi.name
9412                        && destAi.packageName == filterSi.packageName) {
9413                    return false;
9414                }
9415            }
9416            return true;
9417        }
9418
9419        @Override
9420        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9421            return new PackageParser.ServiceIntentInfo[size];
9422        }
9423
9424        @Override
9425        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9426            if (!sUserManager.exists(userId)) return true;
9427            PackageParser.Package p = filter.service.owner;
9428            if (p != null) {
9429                PackageSetting ps = (PackageSetting)p.mExtras;
9430                if (ps != null) {
9431                    // System apps are never considered stopped for purposes of
9432                    // filtering, because there may be no way for the user to
9433                    // actually re-launch them.
9434                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9435                            && ps.getStopped(userId);
9436                }
9437            }
9438            return false;
9439        }
9440
9441        @Override
9442        protected boolean isPackageForFilter(String packageName,
9443                PackageParser.ServiceIntentInfo info) {
9444            return packageName.equals(info.service.owner.packageName);
9445        }
9446
9447        @Override
9448        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9449                int match, int userId) {
9450            if (!sUserManager.exists(userId)) return null;
9451            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9452            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9453                return null;
9454            }
9455            final PackageParser.Service service = info.service;
9456            if (mSafeMode && (service.info.applicationInfo.flags
9457                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9458                return null;
9459            }
9460            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9461            if (ps == null) {
9462                return null;
9463            }
9464            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9465                    ps.readUserState(userId), userId);
9466            if (si == null) {
9467                return null;
9468            }
9469            final ResolveInfo res = new ResolveInfo();
9470            res.serviceInfo = si;
9471            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9472                res.filter = filter;
9473            }
9474            res.priority = info.getPriority();
9475            res.preferredOrder = service.owner.mPreferredOrder;
9476            res.match = match;
9477            res.isDefault = info.hasDefault;
9478            res.labelRes = info.labelRes;
9479            res.nonLocalizedLabel = info.nonLocalizedLabel;
9480            res.icon = info.icon;
9481            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9482            return res;
9483        }
9484
9485        @Override
9486        protected void sortResults(List<ResolveInfo> results) {
9487            Collections.sort(results, mResolvePrioritySorter);
9488        }
9489
9490        @Override
9491        protected void dumpFilter(PrintWriter out, String prefix,
9492                PackageParser.ServiceIntentInfo filter) {
9493            out.print(prefix); out.print(
9494                    Integer.toHexString(System.identityHashCode(filter.service)));
9495                    out.print(' ');
9496                    filter.service.printComponentShortName(out);
9497                    out.print(" filter ");
9498                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9499        }
9500
9501        @Override
9502        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9503            return filter.service;
9504        }
9505
9506        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9507            PackageParser.Service service = (PackageParser.Service)label;
9508            out.print(prefix); out.print(
9509                    Integer.toHexString(System.identityHashCode(service)));
9510                    out.print(' ');
9511                    service.printComponentShortName(out);
9512            if (count > 1) {
9513                out.print(" ("); out.print(count); out.print(" filters)");
9514            }
9515            out.println();
9516        }
9517
9518//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9519//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9520//            final List<ResolveInfo> retList = Lists.newArrayList();
9521//            while (i.hasNext()) {
9522//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9523//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9524//                    retList.add(resolveInfo);
9525//                }
9526//            }
9527//            return retList;
9528//        }
9529
9530        // Keys are String (activity class name), values are Activity.
9531        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9532                = new ArrayMap<ComponentName, PackageParser.Service>();
9533        private int mFlags;
9534    };
9535
9536    private final class ProviderIntentResolver
9537            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9538        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9539                boolean defaultOnly, int userId) {
9540            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9541            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9542        }
9543
9544        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9545                int userId) {
9546            if (!sUserManager.exists(userId))
9547                return null;
9548            mFlags = flags;
9549            return super.queryIntent(intent, resolvedType,
9550                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9551        }
9552
9553        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9554                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9555            if (!sUserManager.exists(userId))
9556                return null;
9557            if (packageProviders == null) {
9558                return null;
9559            }
9560            mFlags = flags;
9561            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9562            final int N = packageProviders.size();
9563            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9564                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9565
9566            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9567            for (int i = 0; i < N; ++i) {
9568                intentFilters = packageProviders.get(i).intents;
9569                if (intentFilters != null && intentFilters.size() > 0) {
9570                    PackageParser.ProviderIntentInfo[] array =
9571                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9572                    intentFilters.toArray(array);
9573                    listCut.add(array);
9574                }
9575            }
9576            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9577        }
9578
9579        public final void addProvider(PackageParser.Provider p) {
9580            if (mProviders.containsKey(p.getComponentName())) {
9581                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9582                return;
9583            }
9584
9585            mProviders.put(p.getComponentName(), p);
9586            if (DEBUG_SHOW_INFO) {
9587                Log.v(TAG, "  "
9588                        + (p.info.nonLocalizedLabel != null
9589                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9590                Log.v(TAG, "    Class=" + p.info.name);
9591            }
9592            final int NI = p.intents.size();
9593            int j;
9594            for (j = 0; j < NI; j++) {
9595                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9596                if (DEBUG_SHOW_INFO) {
9597                    Log.v(TAG, "    IntentFilter:");
9598                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9599                }
9600                if (!intent.debugCheck()) {
9601                    Log.w(TAG, "==> For Provider " + p.info.name);
9602                }
9603                addFilter(intent);
9604            }
9605        }
9606
9607        public final void removeProvider(PackageParser.Provider p) {
9608            mProviders.remove(p.getComponentName());
9609            if (DEBUG_SHOW_INFO) {
9610                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9611                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9612                Log.v(TAG, "    Class=" + p.info.name);
9613            }
9614            final int NI = p.intents.size();
9615            int j;
9616            for (j = 0; j < NI; j++) {
9617                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9618                if (DEBUG_SHOW_INFO) {
9619                    Log.v(TAG, "    IntentFilter:");
9620                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9621                }
9622                removeFilter(intent);
9623            }
9624        }
9625
9626        @Override
9627        protected boolean allowFilterResult(
9628                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9629            ProviderInfo filterPi = filter.provider.info;
9630            for (int i = dest.size() - 1; i >= 0; i--) {
9631                ProviderInfo destPi = dest.get(i).providerInfo;
9632                if (destPi.name == filterPi.name
9633                        && destPi.packageName == filterPi.packageName) {
9634                    return false;
9635                }
9636            }
9637            return true;
9638        }
9639
9640        @Override
9641        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9642            return new PackageParser.ProviderIntentInfo[size];
9643        }
9644
9645        @Override
9646        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9647            if (!sUserManager.exists(userId))
9648                return true;
9649            PackageParser.Package p = filter.provider.owner;
9650            if (p != null) {
9651                PackageSetting ps = (PackageSetting) p.mExtras;
9652                if (ps != null) {
9653                    // System apps are never considered stopped for purposes of
9654                    // filtering, because there may be no way for the user to
9655                    // actually re-launch them.
9656                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9657                            && ps.getStopped(userId);
9658                }
9659            }
9660            return false;
9661        }
9662
9663        @Override
9664        protected boolean isPackageForFilter(String packageName,
9665                PackageParser.ProviderIntentInfo info) {
9666            return packageName.equals(info.provider.owner.packageName);
9667        }
9668
9669        @Override
9670        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9671                int match, int userId) {
9672            if (!sUserManager.exists(userId))
9673                return null;
9674            final PackageParser.ProviderIntentInfo info = filter;
9675            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9676                return null;
9677            }
9678            final PackageParser.Provider provider = info.provider;
9679            if (mSafeMode && (provider.info.applicationInfo.flags
9680                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9681                return null;
9682            }
9683            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9684            if (ps == null) {
9685                return null;
9686            }
9687            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9688                    ps.readUserState(userId), userId);
9689            if (pi == null) {
9690                return null;
9691            }
9692            final ResolveInfo res = new ResolveInfo();
9693            res.providerInfo = pi;
9694            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9695                res.filter = filter;
9696            }
9697            res.priority = info.getPriority();
9698            res.preferredOrder = provider.owner.mPreferredOrder;
9699            res.match = match;
9700            res.isDefault = info.hasDefault;
9701            res.labelRes = info.labelRes;
9702            res.nonLocalizedLabel = info.nonLocalizedLabel;
9703            res.icon = info.icon;
9704            res.system = res.providerInfo.applicationInfo.isSystemApp();
9705            return res;
9706        }
9707
9708        @Override
9709        protected void sortResults(List<ResolveInfo> results) {
9710            Collections.sort(results, mResolvePrioritySorter);
9711        }
9712
9713        @Override
9714        protected void dumpFilter(PrintWriter out, String prefix,
9715                PackageParser.ProviderIntentInfo filter) {
9716            out.print(prefix);
9717            out.print(
9718                    Integer.toHexString(System.identityHashCode(filter.provider)));
9719            out.print(' ');
9720            filter.provider.printComponentShortName(out);
9721            out.print(" filter ");
9722            out.println(Integer.toHexString(System.identityHashCode(filter)));
9723        }
9724
9725        @Override
9726        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9727            return filter.provider;
9728        }
9729
9730        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9731            PackageParser.Provider provider = (PackageParser.Provider)label;
9732            out.print(prefix); out.print(
9733                    Integer.toHexString(System.identityHashCode(provider)));
9734                    out.print(' ');
9735                    provider.printComponentShortName(out);
9736            if (count > 1) {
9737                out.print(" ("); out.print(count); out.print(" filters)");
9738            }
9739            out.println();
9740        }
9741
9742        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9743                = new ArrayMap<ComponentName, PackageParser.Provider>();
9744        private int mFlags;
9745    }
9746
9747    private static final class EphemeralIntentResolver
9748            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9749        @Override
9750        protected EphemeralResolveIntentInfo[] newArray(int size) {
9751            return new EphemeralResolveIntentInfo[size];
9752        }
9753
9754        @Override
9755        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9756            return true;
9757        }
9758
9759        @Override
9760        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9761                int userId) {
9762            if (!sUserManager.exists(userId)) {
9763                return null;
9764            }
9765            return info.getEphemeralResolveInfo();
9766        }
9767    }
9768
9769    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9770            new Comparator<ResolveInfo>() {
9771        public int compare(ResolveInfo r1, ResolveInfo r2) {
9772            int v1 = r1.priority;
9773            int v2 = r2.priority;
9774            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9775            if (v1 != v2) {
9776                return (v1 > v2) ? -1 : 1;
9777            }
9778            v1 = r1.preferredOrder;
9779            v2 = r2.preferredOrder;
9780            if (v1 != v2) {
9781                return (v1 > v2) ? -1 : 1;
9782            }
9783            if (r1.isDefault != r2.isDefault) {
9784                return r1.isDefault ? -1 : 1;
9785            }
9786            v1 = r1.match;
9787            v2 = r2.match;
9788            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9789            if (v1 != v2) {
9790                return (v1 > v2) ? -1 : 1;
9791            }
9792            if (r1.system != r2.system) {
9793                return r1.system ? -1 : 1;
9794            }
9795            if (r1.activityInfo != null) {
9796                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9797            }
9798            if (r1.serviceInfo != null) {
9799                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9800            }
9801            if (r1.providerInfo != null) {
9802                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9803            }
9804            return 0;
9805        }
9806    };
9807
9808    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9809            new Comparator<ProviderInfo>() {
9810        public int compare(ProviderInfo p1, ProviderInfo p2) {
9811            final int v1 = p1.initOrder;
9812            final int v2 = p2.initOrder;
9813            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9814        }
9815    };
9816
9817    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9818            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9819            final int[] userIds) {
9820        mHandler.post(new Runnable() {
9821            @Override
9822            public void run() {
9823                try {
9824                    final IActivityManager am = ActivityManagerNative.getDefault();
9825                    if (am == null) return;
9826                    final int[] resolvedUserIds;
9827                    if (userIds == null) {
9828                        resolvedUserIds = am.getRunningUserIds();
9829                    } else {
9830                        resolvedUserIds = userIds;
9831                    }
9832                    for (int id : resolvedUserIds) {
9833                        final Intent intent = new Intent(action,
9834                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9835                        if (extras != null) {
9836                            intent.putExtras(extras);
9837                        }
9838                        if (targetPkg != null) {
9839                            intent.setPackage(targetPkg);
9840                        }
9841                        // Modify the UID when posting to other users
9842                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9843                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9844                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9845                            intent.putExtra(Intent.EXTRA_UID, uid);
9846                        }
9847                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9848                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9849                        if (DEBUG_BROADCASTS) {
9850                            RuntimeException here = new RuntimeException("here");
9851                            here.fillInStackTrace();
9852                            Slog.d(TAG, "Sending to user " + id + ": "
9853                                    + intent.toShortString(false, true, false, false)
9854                                    + " " + intent.getExtras(), here);
9855                        }
9856                        am.broadcastIntent(null, intent, null, finishedReceiver,
9857                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9858                                null, finishedReceiver != null, false, id);
9859                    }
9860                } catch (RemoteException ex) {
9861                }
9862            }
9863        });
9864    }
9865
9866    /**
9867     * Check if the external storage media is available. This is true if there
9868     * is a mounted external storage medium or if the external storage is
9869     * emulated.
9870     */
9871    private boolean isExternalMediaAvailable() {
9872        return mMediaMounted || Environment.isExternalStorageEmulated();
9873    }
9874
9875    @Override
9876    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9877        // writer
9878        synchronized (mPackages) {
9879            if (!isExternalMediaAvailable()) {
9880                // If the external storage is no longer mounted at this point,
9881                // the caller may not have been able to delete all of this
9882                // packages files and can not delete any more.  Bail.
9883                return null;
9884            }
9885            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9886            if (lastPackage != null) {
9887                pkgs.remove(lastPackage);
9888            }
9889            if (pkgs.size() > 0) {
9890                return pkgs.get(0);
9891            }
9892        }
9893        return null;
9894    }
9895
9896    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9897        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9898                userId, andCode ? 1 : 0, packageName);
9899        if (mSystemReady) {
9900            msg.sendToTarget();
9901        } else {
9902            if (mPostSystemReadyMessages == null) {
9903                mPostSystemReadyMessages = new ArrayList<>();
9904            }
9905            mPostSystemReadyMessages.add(msg);
9906        }
9907    }
9908
9909    void startCleaningPackages() {
9910        // reader
9911        synchronized (mPackages) {
9912            if (!isExternalMediaAvailable()) {
9913                return;
9914            }
9915            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9916                return;
9917            }
9918        }
9919        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9920        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9921        IActivityManager am = ActivityManagerNative.getDefault();
9922        if (am != null) {
9923            try {
9924                am.startService(null, intent, null, mContext.getOpPackageName(),
9925                        UserHandle.USER_SYSTEM);
9926            } catch (RemoteException e) {
9927            }
9928        }
9929    }
9930
9931    @Override
9932    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9933            int installFlags, String installerPackageName, VerificationParams verificationParams,
9934            String packageAbiOverride) {
9935        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9936                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9937    }
9938
9939    @Override
9940    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9941            int installFlags, String installerPackageName, VerificationParams verificationParams,
9942            String packageAbiOverride, int userId) {
9943        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9944
9945        final int callingUid = Binder.getCallingUid();
9946        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9947
9948        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9949            try {
9950                if (observer != null) {
9951                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9952                }
9953            } catch (RemoteException re) {
9954            }
9955            return;
9956        }
9957
9958        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9959            installFlags |= PackageManager.INSTALL_FROM_ADB;
9960
9961        } else {
9962            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9963            // about installerPackageName.
9964
9965            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9966            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9967        }
9968
9969        UserHandle user;
9970        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9971            user = UserHandle.ALL;
9972        } else {
9973            user = new UserHandle(userId);
9974        }
9975
9976        // Only system components can circumvent runtime permissions when installing.
9977        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9978                && mContext.checkCallingOrSelfPermission(Manifest.permission
9979                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9980            throw new SecurityException("You need the "
9981                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9982                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9983        }
9984
9985        verificationParams.setInstallerUid(callingUid);
9986
9987        final File originFile = new File(originPath);
9988        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9989
9990        final Message msg = mHandler.obtainMessage(INIT_COPY);
9991        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9992                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9993        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9994        msg.obj = params;
9995
9996        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9997                System.identityHashCode(msg.obj));
9998        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9999                System.identityHashCode(msg.obj));
10000
10001        mHandler.sendMessage(msg);
10002    }
10003
10004    void installStage(String packageName, File stagedDir, String stagedCid,
10005            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10006            String installerPackageName, int installerUid, UserHandle user) {
10007        if (DEBUG_EPHEMERAL) {
10008            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10009                Slog.d(TAG, "Ephemeral install of " + packageName);
10010            }
10011        }
10012        final VerificationParams verifParams = new VerificationParams(
10013                null, sessionParams.originatingUri, sessionParams.referrerUri,
10014                sessionParams.originatingUid, null);
10015        verifParams.setInstallerUid(installerUid);
10016
10017        final OriginInfo origin;
10018        if (stagedDir != null) {
10019            origin = OriginInfo.fromStagedFile(stagedDir);
10020        } else {
10021            origin = OriginInfo.fromStagedContainer(stagedCid);
10022        }
10023
10024        final Message msg = mHandler.obtainMessage(INIT_COPY);
10025        final InstallParams params = new InstallParams(origin, null, observer,
10026                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10027                verifParams, user, sessionParams.abiOverride,
10028                sessionParams.grantedRuntimePermissions);
10029        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10030        msg.obj = params;
10031
10032        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10033                System.identityHashCode(msg.obj));
10034        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10035                System.identityHashCode(msg.obj));
10036
10037        mHandler.sendMessage(msg);
10038    }
10039
10040    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10041        Bundle extras = new Bundle(1);
10042        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10043
10044        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10045                packageName, extras, 0, null, null, new int[] {userId});
10046        try {
10047            IActivityManager am = ActivityManagerNative.getDefault();
10048            final boolean isSystem =
10049                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10050            if (isSystem && am.isUserRunning(userId, 0)) {
10051                // The just-installed/enabled app is bundled on the system, so presumed
10052                // to be able to run automatically without needing an explicit launch.
10053                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10054                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10055                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10056                        .setPackage(packageName);
10057                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10058                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10059            }
10060        } catch (RemoteException e) {
10061            // shouldn't happen
10062            Slog.w(TAG, "Unable to bootstrap installed package", e);
10063        }
10064    }
10065
10066    @Override
10067    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10068            int userId) {
10069        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10070        PackageSetting pkgSetting;
10071        final int uid = Binder.getCallingUid();
10072        enforceCrossUserPermission(uid, userId, true, true,
10073                "setApplicationHiddenSetting for user " + userId);
10074
10075        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10076            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10077            return false;
10078        }
10079
10080        long callingId = Binder.clearCallingIdentity();
10081        try {
10082            boolean sendAdded = false;
10083            boolean sendRemoved = false;
10084            // writer
10085            synchronized (mPackages) {
10086                pkgSetting = mSettings.mPackages.get(packageName);
10087                if (pkgSetting == null) {
10088                    return false;
10089                }
10090                if (pkgSetting.getHidden(userId) != hidden) {
10091                    pkgSetting.setHidden(hidden, userId);
10092                    mSettings.writePackageRestrictionsLPr(userId);
10093                    if (hidden) {
10094                        sendRemoved = true;
10095                    } else {
10096                        sendAdded = true;
10097                    }
10098                }
10099            }
10100            if (sendAdded) {
10101                sendPackageAddedForUser(packageName, pkgSetting, userId);
10102                return true;
10103            }
10104            if (sendRemoved) {
10105                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10106                        "hiding pkg");
10107                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10108                return true;
10109            }
10110        } finally {
10111            Binder.restoreCallingIdentity(callingId);
10112        }
10113        return false;
10114    }
10115
10116    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10117            int userId) {
10118        final PackageRemovedInfo info = new PackageRemovedInfo();
10119        info.removedPackage = packageName;
10120        info.removedUsers = new int[] {userId};
10121        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10122        info.sendBroadcast(false, false, false);
10123    }
10124
10125    /**
10126     * Returns true if application is not found or there was an error. Otherwise it returns
10127     * the hidden state of the package for the given user.
10128     */
10129    @Override
10130    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10131        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10132        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10133                false, "getApplicationHidden for user " + userId);
10134        PackageSetting pkgSetting;
10135        long callingId = Binder.clearCallingIdentity();
10136        try {
10137            // writer
10138            synchronized (mPackages) {
10139                pkgSetting = mSettings.mPackages.get(packageName);
10140                if (pkgSetting == null) {
10141                    return true;
10142                }
10143                return pkgSetting.getHidden(userId);
10144            }
10145        } finally {
10146            Binder.restoreCallingIdentity(callingId);
10147        }
10148    }
10149
10150    /**
10151     * @hide
10152     */
10153    @Override
10154    public int installExistingPackageAsUser(String packageName, int userId) {
10155        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10156                null);
10157        PackageSetting pkgSetting;
10158        final int uid = Binder.getCallingUid();
10159        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10160                + userId);
10161        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10162            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10163        }
10164
10165        long callingId = Binder.clearCallingIdentity();
10166        try {
10167            boolean sendAdded = false;
10168
10169            // writer
10170            synchronized (mPackages) {
10171                pkgSetting = mSettings.mPackages.get(packageName);
10172                if (pkgSetting == null) {
10173                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10174                }
10175                if (!pkgSetting.getInstalled(userId)) {
10176                    pkgSetting.setInstalled(true, userId);
10177                    pkgSetting.setHidden(false, userId);
10178                    mSettings.writePackageRestrictionsLPr(userId);
10179                    sendAdded = true;
10180                }
10181            }
10182
10183            if (sendAdded) {
10184                sendPackageAddedForUser(packageName, pkgSetting, userId);
10185            }
10186        } finally {
10187            Binder.restoreCallingIdentity(callingId);
10188        }
10189
10190        return PackageManager.INSTALL_SUCCEEDED;
10191    }
10192
10193    boolean isUserRestricted(int userId, String restrictionKey) {
10194        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10195        if (restrictions.getBoolean(restrictionKey, false)) {
10196            Log.w(TAG, "User is restricted: " + restrictionKey);
10197            return true;
10198        }
10199        return false;
10200    }
10201
10202    @Override
10203    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10204        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10205        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10206                "setPackageSuspended for user " + userId);
10207
10208        long callingId = Binder.clearCallingIdentity();
10209        try {
10210            synchronized (mPackages) {
10211                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10212                if (pkgSetting != null) {
10213                    if (pkgSetting.getSuspended(userId) != suspended) {
10214                        pkgSetting.setSuspended(suspended, userId);
10215                        mSettings.writePackageRestrictionsLPr(userId);
10216                    }
10217
10218                    // TODO:
10219                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10220                    // * remove app from recents (kill app it if it is running)
10221                    // * erase existing notifications for this app
10222                    return true;
10223                }
10224
10225                return false;
10226            }
10227        } finally {
10228            Binder.restoreCallingIdentity(callingId);
10229        }
10230    }
10231
10232    @Override
10233    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10234        mContext.enforceCallingOrSelfPermission(
10235                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10236                "Only package verification agents can verify applications");
10237
10238        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10239        final PackageVerificationResponse response = new PackageVerificationResponse(
10240                verificationCode, Binder.getCallingUid());
10241        msg.arg1 = id;
10242        msg.obj = response;
10243        mHandler.sendMessage(msg);
10244    }
10245
10246    @Override
10247    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10248            long millisecondsToDelay) {
10249        mContext.enforceCallingOrSelfPermission(
10250                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10251                "Only package verification agents can extend verification timeouts");
10252
10253        final PackageVerificationState state = mPendingVerification.get(id);
10254        final PackageVerificationResponse response = new PackageVerificationResponse(
10255                verificationCodeAtTimeout, Binder.getCallingUid());
10256
10257        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10258            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10259        }
10260        if (millisecondsToDelay < 0) {
10261            millisecondsToDelay = 0;
10262        }
10263        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10264                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10265            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10266        }
10267
10268        if ((state != null) && !state.timeoutExtended()) {
10269            state.extendTimeout();
10270
10271            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10272            msg.arg1 = id;
10273            msg.obj = response;
10274            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10275        }
10276    }
10277
10278    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10279            int verificationCode, UserHandle user) {
10280        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10281        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10282        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10283        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10284        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10285
10286        mContext.sendBroadcastAsUser(intent, user,
10287                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10288    }
10289
10290    private ComponentName matchComponentForVerifier(String packageName,
10291            List<ResolveInfo> receivers) {
10292        ActivityInfo targetReceiver = null;
10293
10294        final int NR = receivers.size();
10295        for (int i = 0; i < NR; i++) {
10296            final ResolveInfo info = receivers.get(i);
10297            if (info.activityInfo == null) {
10298                continue;
10299            }
10300
10301            if (packageName.equals(info.activityInfo.packageName)) {
10302                targetReceiver = info.activityInfo;
10303                break;
10304            }
10305        }
10306
10307        if (targetReceiver == null) {
10308            return null;
10309        }
10310
10311        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10312    }
10313
10314    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10315            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10316        if (pkgInfo.verifiers.length == 0) {
10317            return null;
10318        }
10319
10320        final int N = pkgInfo.verifiers.length;
10321        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10322        for (int i = 0; i < N; i++) {
10323            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10324
10325            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10326                    receivers);
10327            if (comp == null) {
10328                continue;
10329            }
10330
10331            final int verifierUid = getUidForVerifier(verifierInfo);
10332            if (verifierUid == -1) {
10333                continue;
10334            }
10335
10336            if (DEBUG_VERIFY) {
10337                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10338                        + " with the correct signature");
10339            }
10340            sufficientVerifiers.add(comp);
10341            verificationState.addSufficientVerifier(verifierUid);
10342        }
10343
10344        return sufficientVerifiers;
10345    }
10346
10347    private int getUidForVerifier(VerifierInfo verifierInfo) {
10348        synchronized (mPackages) {
10349            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10350            if (pkg == null) {
10351                return -1;
10352            } else if (pkg.mSignatures.length != 1) {
10353                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10354                        + " has more than one signature; ignoring");
10355                return -1;
10356            }
10357
10358            /*
10359             * If the public key of the package's signature does not match
10360             * our expected public key, then this is a different package and
10361             * we should skip.
10362             */
10363
10364            final byte[] expectedPublicKey;
10365            try {
10366                final Signature verifierSig = pkg.mSignatures[0];
10367                final PublicKey publicKey = verifierSig.getPublicKey();
10368                expectedPublicKey = publicKey.getEncoded();
10369            } catch (CertificateException e) {
10370                return -1;
10371            }
10372
10373            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10374
10375            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10376                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10377                        + " does not have the expected public key; ignoring");
10378                return -1;
10379            }
10380
10381            return pkg.applicationInfo.uid;
10382        }
10383    }
10384
10385    @Override
10386    public void finishPackageInstall(int token) {
10387        enforceSystemOrRoot("Only the system is allowed to finish installs");
10388
10389        if (DEBUG_INSTALL) {
10390            Slog.v(TAG, "BM finishing package install for " + token);
10391        }
10392        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10393
10394        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10395        mHandler.sendMessage(msg);
10396    }
10397
10398    /**
10399     * Get the verification agent timeout.
10400     *
10401     * @return verification timeout in milliseconds
10402     */
10403    private long getVerificationTimeout() {
10404        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10405                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10406                DEFAULT_VERIFICATION_TIMEOUT);
10407    }
10408
10409    /**
10410     * Get the default verification agent response code.
10411     *
10412     * @return default verification response code
10413     */
10414    private int getDefaultVerificationResponse() {
10415        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10416                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10417                DEFAULT_VERIFICATION_RESPONSE);
10418    }
10419
10420    /**
10421     * Check whether or not package verification has been enabled.
10422     *
10423     * @return true if verification should be performed
10424     */
10425    private boolean isVerificationEnabled(int userId, int installFlags) {
10426        if (!DEFAULT_VERIFY_ENABLE) {
10427            return false;
10428        }
10429        // TODO: fix b/25118622; don't bypass verification
10430        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10431            return false;
10432        }
10433        // Ephemeral apps don't get the full verification treatment
10434        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10435            if (DEBUG_EPHEMERAL) {
10436                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10437            }
10438            return false;
10439        }
10440
10441        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10442
10443        // Check if installing from ADB
10444        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10445            // Do not run verification in a test harness environment
10446            if (ActivityManager.isRunningInTestHarness()) {
10447                return false;
10448            }
10449            if (ensureVerifyAppsEnabled) {
10450                return true;
10451            }
10452            // Check if the developer does not want package verification for ADB installs
10453            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10454                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10455                return false;
10456            }
10457        }
10458
10459        if (ensureVerifyAppsEnabled) {
10460            return true;
10461        }
10462
10463        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10464                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10465    }
10466
10467    @Override
10468    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10469            throws RemoteException {
10470        mContext.enforceCallingOrSelfPermission(
10471                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10472                "Only intentfilter verification agents can verify applications");
10473
10474        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10475        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10476                Binder.getCallingUid(), verificationCode, failedDomains);
10477        msg.arg1 = id;
10478        msg.obj = response;
10479        mHandler.sendMessage(msg);
10480    }
10481
10482    @Override
10483    public int getIntentVerificationStatus(String packageName, int userId) {
10484        synchronized (mPackages) {
10485            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10486        }
10487    }
10488
10489    @Override
10490    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10491        mContext.enforceCallingOrSelfPermission(
10492                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10493
10494        boolean result = false;
10495        synchronized (mPackages) {
10496            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10497        }
10498        if (result) {
10499            scheduleWritePackageRestrictionsLocked(userId);
10500        }
10501        return result;
10502    }
10503
10504    @Override
10505    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10506        synchronized (mPackages) {
10507            return mSettings.getIntentFilterVerificationsLPr(packageName);
10508        }
10509    }
10510
10511    @Override
10512    public List<IntentFilter> getAllIntentFilters(String packageName) {
10513        if (TextUtils.isEmpty(packageName)) {
10514            return Collections.<IntentFilter>emptyList();
10515        }
10516        synchronized (mPackages) {
10517            PackageParser.Package pkg = mPackages.get(packageName);
10518            if (pkg == null || pkg.activities == null) {
10519                return Collections.<IntentFilter>emptyList();
10520            }
10521            final int count = pkg.activities.size();
10522            ArrayList<IntentFilter> result = new ArrayList<>();
10523            for (int n=0; n<count; n++) {
10524                PackageParser.Activity activity = pkg.activities.get(n);
10525                if (activity.intents != null && activity.intents.size() > 0) {
10526                    result.addAll(activity.intents);
10527                }
10528            }
10529            return result;
10530        }
10531    }
10532
10533    @Override
10534    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10535        mContext.enforceCallingOrSelfPermission(
10536                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10537
10538        synchronized (mPackages) {
10539            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10540            if (packageName != null) {
10541                result |= updateIntentVerificationStatus(packageName,
10542                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10543                        userId);
10544                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10545                        packageName, userId);
10546            }
10547            return result;
10548        }
10549    }
10550
10551    @Override
10552    public String getDefaultBrowserPackageName(int userId) {
10553        synchronized (mPackages) {
10554            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10555        }
10556    }
10557
10558    /**
10559     * Get the "allow unknown sources" setting.
10560     *
10561     * @return the current "allow unknown sources" setting
10562     */
10563    private int getUnknownSourcesSettings() {
10564        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10565                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10566                -1);
10567    }
10568
10569    @Override
10570    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10571        final int uid = Binder.getCallingUid();
10572        // writer
10573        synchronized (mPackages) {
10574            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10575            if (targetPackageSetting == null) {
10576                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10577            }
10578
10579            PackageSetting installerPackageSetting;
10580            if (installerPackageName != null) {
10581                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10582                if (installerPackageSetting == null) {
10583                    throw new IllegalArgumentException("Unknown installer package: "
10584                            + installerPackageName);
10585                }
10586            } else {
10587                installerPackageSetting = null;
10588            }
10589
10590            Signature[] callerSignature;
10591            Object obj = mSettings.getUserIdLPr(uid);
10592            if (obj != null) {
10593                if (obj instanceof SharedUserSetting) {
10594                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10595                } else if (obj instanceof PackageSetting) {
10596                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10597                } else {
10598                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10599                }
10600            } else {
10601                throw new SecurityException("Unknown calling uid " + uid);
10602            }
10603
10604            // Verify: can't set installerPackageName to a package that is
10605            // not signed with the same cert as the caller.
10606            if (installerPackageSetting != null) {
10607                if (compareSignatures(callerSignature,
10608                        installerPackageSetting.signatures.mSignatures)
10609                        != PackageManager.SIGNATURE_MATCH) {
10610                    throw new SecurityException(
10611                            "Caller does not have same cert as new installer package "
10612                            + installerPackageName);
10613                }
10614            }
10615
10616            // Verify: if target already has an installer package, it must
10617            // be signed with the same cert as the caller.
10618            if (targetPackageSetting.installerPackageName != null) {
10619                PackageSetting setting = mSettings.mPackages.get(
10620                        targetPackageSetting.installerPackageName);
10621                // If the currently set package isn't valid, then it's always
10622                // okay to change it.
10623                if (setting != null) {
10624                    if (compareSignatures(callerSignature,
10625                            setting.signatures.mSignatures)
10626                            != PackageManager.SIGNATURE_MATCH) {
10627                        throw new SecurityException(
10628                                "Caller does not have same cert as old installer package "
10629                                + targetPackageSetting.installerPackageName);
10630                    }
10631                }
10632            }
10633
10634            // Okay!
10635            targetPackageSetting.installerPackageName = installerPackageName;
10636            scheduleWriteSettingsLocked();
10637        }
10638    }
10639
10640    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10641        // Queue up an async operation since the package installation may take a little while.
10642        mHandler.post(new Runnable() {
10643            public void run() {
10644                mHandler.removeCallbacks(this);
10645                 // Result object to be returned
10646                PackageInstalledInfo res = new PackageInstalledInfo();
10647                res.returnCode = currentStatus;
10648                res.uid = -1;
10649                res.pkg = null;
10650                res.removedInfo = new PackageRemovedInfo();
10651                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10652                    args.doPreInstall(res.returnCode);
10653                    synchronized (mInstallLock) {
10654                        installPackageTracedLI(args, res);
10655                    }
10656                    args.doPostInstall(res.returnCode, res.uid);
10657                }
10658
10659                // A restore should be performed at this point if (a) the install
10660                // succeeded, (b) the operation is not an update, and (c) the new
10661                // package has not opted out of backup participation.
10662                final boolean update = res.removedInfo.removedPackage != null;
10663                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10664                boolean doRestore = !update
10665                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10666
10667                // Set up the post-install work request bookkeeping.  This will be used
10668                // and cleaned up by the post-install event handling regardless of whether
10669                // there's a restore pass performed.  Token values are >= 1.
10670                int token;
10671                if (mNextInstallToken < 0) mNextInstallToken = 1;
10672                token = mNextInstallToken++;
10673
10674                PostInstallData data = new PostInstallData(args, res);
10675                mRunningInstalls.put(token, data);
10676                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10677
10678                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10679                    // Pass responsibility to the Backup Manager.  It will perform a
10680                    // restore if appropriate, then pass responsibility back to the
10681                    // Package Manager to run the post-install observer callbacks
10682                    // and broadcasts.
10683                    IBackupManager bm = IBackupManager.Stub.asInterface(
10684                            ServiceManager.getService(Context.BACKUP_SERVICE));
10685                    if (bm != null) {
10686                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10687                                + " to BM for possible restore");
10688                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10689                        try {
10690                            // TODO: http://b/22388012
10691                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10692                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10693                            } else {
10694                                doRestore = false;
10695                            }
10696                        } catch (RemoteException e) {
10697                            // can't happen; the backup manager is local
10698                        } catch (Exception e) {
10699                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10700                            doRestore = false;
10701                        }
10702                    } else {
10703                        Slog.e(TAG, "Backup Manager not found!");
10704                        doRestore = false;
10705                    }
10706                }
10707
10708                if (!doRestore) {
10709                    // No restore possible, or the Backup Manager was mysteriously not
10710                    // available -- just fire the post-install work request directly.
10711                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10712
10713                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10714
10715                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10716                    mHandler.sendMessage(msg);
10717                }
10718            }
10719        });
10720    }
10721
10722    private abstract class HandlerParams {
10723        private static final int MAX_RETRIES = 4;
10724
10725        /**
10726         * Number of times startCopy() has been attempted and had a non-fatal
10727         * error.
10728         */
10729        private int mRetries = 0;
10730
10731        /** User handle for the user requesting the information or installation. */
10732        private final UserHandle mUser;
10733        String traceMethod;
10734        int traceCookie;
10735
10736        HandlerParams(UserHandle user) {
10737            mUser = user;
10738        }
10739
10740        UserHandle getUser() {
10741            return mUser;
10742        }
10743
10744        HandlerParams setTraceMethod(String traceMethod) {
10745            this.traceMethod = traceMethod;
10746            return this;
10747        }
10748
10749        HandlerParams setTraceCookie(int traceCookie) {
10750            this.traceCookie = traceCookie;
10751            return this;
10752        }
10753
10754        final boolean startCopy() {
10755            boolean res;
10756            try {
10757                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10758
10759                if (++mRetries > MAX_RETRIES) {
10760                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10761                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10762                    handleServiceError();
10763                    return false;
10764                } else {
10765                    handleStartCopy();
10766                    res = true;
10767                }
10768            } catch (RemoteException e) {
10769                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10770                mHandler.sendEmptyMessage(MCS_RECONNECT);
10771                res = false;
10772            }
10773            handleReturnCode();
10774            return res;
10775        }
10776
10777        final void serviceError() {
10778            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10779            handleServiceError();
10780            handleReturnCode();
10781        }
10782
10783        abstract void handleStartCopy() throws RemoteException;
10784        abstract void handleServiceError();
10785        abstract void handleReturnCode();
10786    }
10787
10788    class MeasureParams extends HandlerParams {
10789        private final PackageStats mStats;
10790        private boolean mSuccess;
10791
10792        private final IPackageStatsObserver mObserver;
10793
10794        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10795            super(new UserHandle(stats.userHandle));
10796            mObserver = observer;
10797            mStats = stats;
10798        }
10799
10800        @Override
10801        public String toString() {
10802            return "MeasureParams{"
10803                + Integer.toHexString(System.identityHashCode(this))
10804                + " " + mStats.packageName + "}";
10805        }
10806
10807        @Override
10808        void handleStartCopy() throws RemoteException {
10809            synchronized (mInstallLock) {
10810                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10811            }
10812
10813            if (mSuccess) {
10814                final boolean mounted;
10815                if (Environment.isExternalStorageEmulated()) {
10816                    mounted = true;
10817                } else {
10818                    final String status = Environment.getExternalStorageState();
10819                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10820                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10821                }
10822
10823                if (mounted) {
10824                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10825
10826                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10827                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10828
10829                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10830                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10831
10832                    // Always subtract cache size, since it's a subdirectory
10833                    mStats.externalDataSize -= mStats.externalCacheSize;
10834
10835                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10836                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10837
10838                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10839                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10840                }
10841            }
10842        }
10843
10844        @Override
10845        void handleReturnCode() {
10846            if (mObserver != null) {
10847                try {
10848                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10849                } catch (RemoteException e) {
10850                    Slog.i(TAG, "Observer no longer exists.");
10851                }
10852            }
10853        }
10854
10855        @Override
10856        void handleServiceError() {
10857            Slog.e(TAG, "Could not measure application " + mStats.packageName
10858                            + " external storage");
10859        }
10860    }
10861
10862    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10863            throws RemoteException {
10864        long result = 0;
10865        for (File path : paths) {
10866            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10867        }
10868        return result;
10869    }
10870
10871    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10872        for (File path : paths) {
10873            try {
10874                mcs.clearDirectory(path.getAbsolutePath());
10875            } catch (RemoteException e) {
10876            }
10877        }
10878    }
10879
10880    static class OriginInfo {
10881        /**
10882         * Location where install is coming from, before it has been
10883         * copied/renamed into place. This could be a single monolithic APK
10884         * file, or a cluster directory. This location may be untrusted.
10885         */
10886        final File file;
10887        final String cid;
10888
10889        /**
10890         * Flag indicating that {@link #file} or {@link #cid} has already been
10891         * staged, meaning downstream users don't need to defensively copy the
10892         * contents.
10893         */
10894        final boolean staged;
10895
10896        /**
10897         * Flag indicating that {@link #file} or {@link #cid} is an already
10898         * installed app that is being moved.
10899         */
10900        final boolean existing;
10901
10902        final String resolvedPath;
10903        final File resolvedFile;
10904
10905        static OriginInfo fromNothing() {
10906            return new OriginInfo(null, null, false, false);
10907        }
10908
10909        static OriginInfo fromUntrustedFile(File file) {
10910            return new OriginInfo(file, null, false, false);
10911        }
10912
10913        static OriginInfo fromExistingFile(File file) {
10914            return new OriginInfo(file, null, false, true);
10915        }
10916
10917        static OriginInfo fromStagedFile(File file) {
10918            return new OriginInfo(file, null, true, false);
10919        }
10920
10921        static OriginInfo fromStagedContainer(String cid) {
10922            return new OriginInfo(null, cid, true, false);
10923        }
10924
10925        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10926            this.file = file;
10927            this.cid = cid;
10928            this.staged = staged;
10929            this.existing = existing;
10930
10931            if (cid != null) {
10932                resolvedPath = PackageHelper.getSdDir(cid);
10933                resolvedFile = new File(resolvedPath);
10934            } else if (file != null) {
10935                resolvedPath = file.getAbsolutePath();
10936                resolvedFile = file;
10937            } else {
10938                resolvedPath = null;
10939                resolvedFile = null;
10940            }
10941        }
10942    }
10943
10944    static class MoveInfo {
10945        final int moveId;
10946        final String fromUuid;
10947        final String toUuid;
10948        final String packageName;
10949        final String dataAppName;
10950        final int appId;
10951        final String seinfo;
10952
10953        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10954                String dataAppName, int appId, String seinfo) {
10955            this.moveId = moveId;
10956            this.fromUuid = fromUuid;
10957            this.toUuid = toUuid;
10958            this.packageName = packageName;
10959            this.dataAppName = dataAppName;
10960            this.appId = appId;
10961            this.seinfo = seinfo;
10962        }
10963    }
10964
10965    class InstallParams extends HandlerParams {
10966        final OriginInfo origin;
10967        final MoveInfo move;
10968        final IPackageInstallObserver2 observer;
10969        int installFlags;
10970        final String installerPackageName;
10971        final String volumeUuid;
10972        final VerificationParams verificationParams;
10973        private InstallArgs mArgs;
10974        private int mRet;
10975        final String packageAbiOverride;
10976        final String[] grantedRuntimePermissions;
10977
10978        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10979                int installFlags, String installerPackageName, String volumeUuid,
10980                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10981                String[] grantedPermissions) {
10982            super(user);
10983            this.origin = origin;
10984            this.move = move;
10985            this.observer = observer;
10986            this.installFlags = installFlags;
10987            this.installerPackageName = installerPackageName;
10988            this.volumeUuid = volumeUuid;
10989            this.verificationParams = verificationParams;
10990            this.packageAbiOverride = packageAbiOverride;
10991            this.grantedRuntimePermissions = grantedPermissions;
10992        }
10993
10994        @Override
10995        public String toString() {
10996            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10997                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10998        }
10999
11000        public ManifestDigest getManifestDigest() {
11001            if (verificationParams == null) {
11002                return null;
11003            }
11004            return verificationParams.getManifestDigest();
11005        }
11006
11007        private int installLocationPolicy(PackageInfoLite pkgLite) {
11008            String packageName = pkgLite.packageName;
11009            int installLocation = pkgLite.installLocation;
11010            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11011            // reader
11012            synchronized (mPackages) {
11013                PackageParser.Package pkg = mPackages.get(packageName);
11014                if (pkg != null) {
11015                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11016                        // Check for downgrading.
11017                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11018                            try {
11019                                checkDowngrade(pkg, pkgLite);
11020                            } catch (PackageManagerException e) {
11021                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11022                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11023                            }
11024                        }
11025                        // Check for updated system application.
11026                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11027                            if (onSd) {
11028                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11029                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11030                            }
11031                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11032                        } else {
11033                            if (onSd) {
11034                                // Install flag overrides everything.
11035                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11036                            }
11037                            // If current upgrade specifies particular preference
11038                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11039                                // Application explicitly specified internal.
11040                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11041                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11042                                // App explictly prefers external. Let policy decide
11043                            } else {
11044                                // Prefer previous location
11045                                if (isExternal(pkg)) {
11046                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11047                                }
11048                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11049                            }
11050                        }
11051                    } else {
11052                        // Invalid install. Return error code
11053                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11054                    }
11055                }
11056            }
11057            // All the special cases have been taken care of.
11058            // Return result based on recommended install location.
11059            if (onSd) {
11060                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11061            }
11062            return pkgLite.recommendedInstallLocation;
11063        }
11064
11065        /*
11066         * Invoke remote method to get package information and install
11067         * location values. Override install location based on default
11068         * policy if needed and then create install arguments based
11069         * on the install location.
11070         */
11071        public void handleStartCopy() throws RemoteException {
11072            int ret = PackageManager.INSTALL_SUCCEEDED;
11073
11074            // If we're already staged, we've firmly committed to an install location
11075            if (origin.staged) {
11076                if (origin.file != null) {
11077                    installFlags |= PackageManager.INSTALL_INTERNAL;
11078                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11079                } else if (origin.cid != null) {
11080                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11081                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11082                } else {
11083                    throw new IllegalStateException("Invalid stage location");
11084                }
11085            }
11086
11087            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11088            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11089            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11090            PackageInfoLite pkgLite = null;
11091
11092            if (onInt && onSd) {
11093                // Check if both bits are set.
11094                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11095                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11096            } else if (onSd && ephemeral) {
11097                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11098                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11099            } else {
11100                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11101                        packageAbiOverride);
11102
11103                if (DEBUG_EPHEMERAL && ephemeral) {
11104                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11105                }
11106
11107                /*
11108                 * If we have too little free space, try to free cache
11109                 * before giving up.
11110                 */
11111                if (!origin.staged && pkgLite.recommendedInstallLocation
11112                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11113                    // TODO: focus freeing disk space on the target device
11114                    final StorageManager storage = StorageManager.from(mContext);
11115                    final long lowThreshold = storage.getStorageLowBytes(
11116                            Environment.getDataDirectory());
11117
11118                    final long sizeBytes = mContainerService.calculateInstalledSize(
11119                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11120
11121                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11122                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11123                                installFlags, packageAbiOverride);
11124                    }
11125
11126                    /*
11127                     * The cache free must have deleted the file we
11128                     * downloaded to install.
11129                     *
11130                     * TODO: fix the "freeCache" call to not delete
11131                     *       the file we care about.
11132                     */
11133                    if (pkgLite.recommendedInstallLocation
11134                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11135                        pkgLite.recommendedInstallLocation
11136                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11137                    }
11138                }
11139            }
11140
11141            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11142                int loc = pkgLite.recommendedInstallLocation;
11143                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11144                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11145                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11146                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11147                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11148                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11149                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11150                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11151                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11152                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11153                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11154                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11155                } else {
11156                    // Override with defaults if needed.
11157                    loc = installLocationPolicy(pkgLite);
11158                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11159                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11160                    } else if (!onSd && !onInt) {
11161                        // Override install location with flags
11162                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11163                            // Set the flag to install on external media.
11164                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11165                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11166                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11167                            if (DEBUG_EPHEMERAL) {
11168                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11169                            }
11170                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11171                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11172                                    |PackageManager.INSTALL_INTERNAL);
11173                        } else {
11174                            // Make sure the flag for installing on external
11175                            // media is unset
11176                            installFlags |= PackageManager.INSTALL_INTERNAL;
11177                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11178                        }
11179                    }
11180                }
11181            }
11182
11183            final InstallArgs args = createInstallArgs(this);
11184            mArgs = args;
11185
11186            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11187                // TODO: http://b/22976637
11188                // Apps installed for "all" users use the device owner to verify the app
11189                UserHandle verifierUser = getUser();
11190                if (verifierUser == UserHandle.ALL) {
11191                    verifierUser = UserHandle.SYSTEM;
11192                }
11193
11194                /*
11195                 * Determine if we have any installed package verifiers. If we
11196                 * do, then we'll defer to them to verify the packages.
11197                 */
11198                final int requiredUid = mRequiredVerifierPackage == null ? -1
11199                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11200                if (!origin.existing && requiredUid != -1
11201                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11202                    final Intent verification = new Intent(
11203                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11204                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11205                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11206                            PACKAGE_MIME_TYPE);
11207                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11208
11209                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11210                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11211                            verifierUser.getIdentifier());
11212
11213                    if (DEBUG_VERIFY) {
11214                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11215                                + verification.toString() + " with " + pkgLite.verifiers.length
11216                                + " optional verifiers");
11217                    }
11218
11219                    final int verificationId = mPendingVerificationToken++;
11220
11221                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11222
11223                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11224                            installerPackageName);
11225
11226                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11227                            installFlags);
11228
11229                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11230                            pkgLite.packageName);
11231
11232                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11233                            pkgLite.versionCode);
11234
11235                    if (verificationParams != null) {
11236                        if (verificationParams.getVerificationURI() != null) {
11237                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11238                                 verificationParams.getVerificationURI());
11239                        }
11240                        if (verificationParams.getOriginatingURI() != null) {
11241                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11242                                  verificationParams.getOriginatingURI());
11243                        }
11244                        if (verificationParams.getReferrer() != null) {
11245                            verification.putExtra(Intent.EXTRA_REFERRER,
11246                                  verificationParams.getReferrer());
11247                        }
11248                        if (verificationParams.getOriginatingUid() >= 0) {
11249                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11250                                  verificationParams.getOriginatingUid());
11251                        }
11252                        if (verificationParams.getInstallerUid() >= 0) {
11253                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11254                                  verificationParams.getInstallerUid());
11255                        }
11256                    }
11257
11258                    final PackageVerificationState verificationState = new PackageVerificationState(
11259                            requiredUid, args);
11260
11261                    mPendingVerification.append(verificationId, verificationState);
11262
11263                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11264                            receivers, verificationState);
11265
11266                    /*
11267                     * If any sufficient verifiers were listed in the package
11268                     * manifest, attempt to ask them.
11269                     */
11270                    if (sufficientVerifiers != null) {
11271                        final int N = sufficientVerifiers.size();
11272                        if (N == 0) {
11273                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11274                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11275                        } else {
11276                            for (int i = 0; i < N; i++) {
11277                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11278
11279                                final Intent sufficientIntent = new Intent(verification);
11280                                sufficientIntent.setComponent(verifierComponent);
11281                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11282                            }
11283                        }
11284                    }
11285
11286                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11287                            mRequiredVerifierPackage, receivers);
11288                    if (ret == PackageManager.INSTALL_SUCCEEDED
11289                            && mRequiredVerifierPackage != null) {
11290                        Trace.asyncTraceBegin(
11291                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11292                        /*
11293                         * Send the intent to the required verification agent,
11294                         * but only start the verification timeout after the
11295                         * target BroadcastReceivers have run.
11296                         */
11297                        verification.setComponent(requiredVerifierComponent);
11298                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11299                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11300                                new BroadcastReceiver() {
11301                                    @Override
11302                                    public void onReceive(Context context, Intent intent) {
11303                                        final Message msg = mHandler
11304                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11305                                        msg.arg1 = verificationId;
11306                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11307                                    }
11308                                }, null, 0, null, null);
11309
11310                        /*
11311                         * We don't want the copy to proceed until verification
11312                         * succeeds, so null out this field.
11313                         */
11314                        mArgs = null;
11315                    }
11316                } else {
11317                    /*
11318                     * No package verification is enabled, so immediately start
11319                     * the remote call to initiate copy using temporary file.
11320                     */
11321                    ret = args.copyApk(mContainerService, true);
11322                }
11323            }
11324
11325            mRet = ret;
11326        }
11327
11328        @Override
11329        void handleReturnCode() {
11330            // If mArgs is null, then MCS couldn't be reached. When it
11331            // reconnects, it will try again to install. At that point, this
11332            // will succeed.
11333            if (mArgs != null) {
11334                processPendingInstall(mArgs, mRet);
11335            }
11336        }
11337
11338        @Override
11339        void handleServiceError() {
11340            mArgs = createInstallArgs(this);
11341            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11342        }
11343
11344        public boolean isForwardLocked() {
11345            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11346        }
11347    }
11348
11349    /**
11350     * Used during creation of InstallArgs
11351     *
11352     * @param installFlags package installation flags
11353     * @return true if should be installed on external storage
11354     */
11355    private static boolean installOnExternalAsec(int installFlags) {
11356        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11357            return false;
11358        }
11359        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11360            return true;
11361        }
11362        return false;
11363    }
11364
11365    /**
11366     * Used during creation of InstallArgs
11367     *
11368     * @param installFlags package installation flags
11369     * @return true if should be installed as forward locked
11370     */
11371    private static boolean installForwardLocked(int installFlags) {
11372        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11373    }
11374
11375    private InstallArgs createInstallArgs(InstallParams params) {
11376        if (params.move != null) {
11377            return new MoveInstallArgs(params);
11378        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11379            return new AsecInstallArgs(params);
11380        } else {
11381            return new FileInstallArgs(params);
11382        }
11383    }
11384
11385    /**
11386     * Create args that describe an existing installed package. Typically used
11387     * when cleaning up old installs, or used as a move source.
11388     */
11389    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11390            String resourcePath, String[] instructionSets) {
11391        final boolean isInAsec;
11392        if (installOnExternalAsec(installFlags)) {
11393            /* Apps on SD card are always in ASEC containers. */
11394            isInAsec = true;
11395        } else if (installForwardLocked(installFlags)
11396                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11397            /*
11398             * Forward-locked apps are only in ASEC containers if they're the
11399             * new style
11400             */
11401            isInAsec = true;
11402        } else {
11403            isInAsec = false;
11404        }
11405
11406        if (isInAsec) {
11407            return new AsecInstallArgs(codePath, instructionSets,
11408                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11409        } else {
11410            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11411        }
11412    }
11413
11414    static abstract class InstallArgs {
11415        /** @see InstallParams#origin */
11416        final OriginInfo origin;
11417        /** @see InstallParams#move */
11418        final MoveInfo move;
11419
11420        final IPackageInstallObserver2 observer;
11421        // Always refers to PackageManager flags only
11422        final int installFlags;
11423        final String installerPackageName;
11424        final String volumeUuid;
11425        final ManifestDigest manifestDigest;
11426        final UserHandle user;
11427        final String abiOverride;
11428        final String[] installGrantPermissions;
11429        /** If non-null, drop an async trace when the install completes */
11430        final String traceMethod;
11431        final int traceCookie;
11432
11433        // The list of instruction sets supported by this app. This is currently
11434        // only used during the rmdex() phase to clean up resources. We can get rid of this
11435        // if we move dex files under the common app path.
11436        /* nullable */ String[] instructionSets;
11437
11438        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11439                int installFlags, String installerPackageName, String volumeUuid,
11440                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11441                String abiOverride, String[] installGrantPermissions,
11442                String traceMethod, int traceCookie) {
11443            this.origin = origin;
11444            this.move = move;
11445            this.installFlags = installFlags;
11446            this.observer = observer;
11447            this.installerPackageName = installerPackageName;
11448            this.volumeUuid = volumeUuid;
11449            this.manifestDigest = manifestDigest;
11450            this.user = user;
11451            this.instructionSets = instructionSets;
11452            this.abiOverride = abiOverride;
11453            this.installGrantPermissions = installGrantPermissions;
11454            this.traceMethod = traceMethod;
11455            this.traceCookie = traceCookie;
11456        }
11457
11458        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11459        abstract int doPreInstall(int status);
11460
11461        /**
11462         * Rename package into final resting place. All paths on the given
11463         * scanned package should be updated to reflect the rename.
11464         */
11465        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11466        abstract int doPostInstall(int status, int uid);
11467
11468        /** @see PackageSettingBase#codePathString */
11469        abstract String getCodePath();
11470        /** @see PackageSettingBase#resourcePathString */
11471        abstract String getResourcePath();
11472
11473        // Need installer lock especially for dex file removal.
11474        abstract void cleanUpResourcesLI();
11475        abstract boolean doPostDeleteLI(boolean delete);
11476
11477        /**
11478         * Called before the source arguments are copied. This is used mostly
11479         * for MoveParams when it needs to read the source file to put it in the
11480         * destination.
11481         */
11482        int doPreCopy() {
11483            return PackageManager.INSTALL_SUCCEEDED;
11484        }
11485
11486        /**
11487         * Called after the source arguments are copied. This is used mostly for
11488         * MoveParams when it needs to read the source file to put it in the
11489         * destination.
11490         *
11491         * @return
11492         */
11493        int doPostCopy(int uid) {
11494            return PackageManager.INSTALL_SUCCEEDED;
11495        }
11496
11497        protected boolean isFwdLocked() {
11498            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11499        }
11500
11501        protected boolean isExternalAsec() {
11502            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11503        }
11504
11505        protected boolean isEphemeral() {
11506            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11507        }
11508
11509        UserHandle getUser() {
11510            return user;
11511        }
11512    }
11513
11514    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11515        if (!allCodePaths.isEmpty()) {
11516            if (instructionSets == null) {
11517                throw new IllegalStateException("instructionSet == null");
11518            }
11519            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11520            for (String codePath : allCodePaths) {
11521                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11522                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11523                    if (retCode < 0) {
11524                        Slog.w(TAG, "Couldn't remove dex file for package: "
11525                                + " at location " + codePath + ", retcode=" + retCode);
11526                        // we don't consider this to be a failure of the core package deletion
11527                    }
11528                }
11529            }
11530        }
11531    }
11532
11533    /**
11534     * Logic to handle installation of non-ASEC applications, including copying
11535     * and renaming logic.
11536     */
11537    class FileInstallArgs extends InstallArgs {
11538        private File codeFile;
11539        private File resourceFile;
11540
11541        // Example topology:
11542        // /data/app/com.example/base.apk
11543        // /data/app/com.example/split_foo.apk
11544        // /data/app/com.example/lib/arm/libfoo.so
11545        // /data/app/com.example/lib/arm64/libfoo.so
11546        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11547
11548        /** New install */
11549        FileInstallArgs(InstallParams params) {
11550            super(params.origin, params.move, params.observer, params.installFlags,
11551                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11552                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11553                    params.grantedRuntimePermissions,
11554                    params.traceMethod, params.traceCookie);
11555            if (isFwdLocked()) {
11556                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11557            }
11558        }
11559
11560        /** Existing install */
11561        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11562            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11563                    null, null, null, 0);
11564            this.codeFile = (codePath != null) ? new File(codePath) : null;
11565            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11566        }
11567
11568        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11569            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11570            try {
11571                return doCopyApk(imcs, temp);
11572            } finally {
11573                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11574            }
11575        }
11576
11577        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11578            if (origin.staged) {
11579                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11580                codeFile = origin.file;
11581                resourceFile = origin.file;
11582                return PackageManager.INSTALL_SUCCEEDED;
11583            }
11584
11585            try {
11586                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11587                final File tempDir =
11588                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11589                codeFile = tempDir;
11590                resourceFile = tempDir;
11591            } catch (IOException e) {
11592                Slog.w(TAG, "Failed to create copy file: " + e);
11593                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11594            }
11595
11596            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11597                @Override
11598                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11599                    if (!FileUtils.isValidExtFilename(name)) {
11600                        throw new IllegalArgumentException("Invalid filename: " + name);
11601                    }
11602                    try {
11603                        final File file = new File(codeFile, name);
11604                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11605                                O_RDWR | O_CREAT, 0644);
11606                        Os.chmod(file.getAbsolutePath(), 0644);
11607                        return new ParcelFileDescriptor(fd);
11608                    } catch (ErrnoException e) {
11609                        throw new RemoteException("Failed to open: " + e.getMessage());
11610                    }
11611                }
11612            };
11613
11614            int ret = PackageManager.INSTALL_SUCCEEDED;
11615            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11616            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11617                Slog.e(TAG, "Failed to copy package");
11618                return ret;
11619            }
11620
11621            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11622            NativeLibraryHelper.Handle handle = null;
11623            try {
11624                handle = NativeLibraryHelper.Handle.create(codeFile);
11625                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11626                        abiOverride);
11627            } catch (IOException e) {
11628                Slog.e(TAG, "Copying native libraries failed", e);
11629                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11630            } finally {
11631                IoUtils.closeQuietly(handle);
11632            }
11633
11634            return ret;
11635        }
11636
11637        int doPreInstall(int status) {
11638            if (status != PackageManager.INSTALL_SUCCEEDED) {
11639                cleanUp();
11640            }
11641            return status;
11642        }
11643
11644        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11645            if (status != PackageManager.INSTALL_SUCCEEDED) {
11646                cleanUp();
11647                return false;
11648            }
11649
11650            final File targetDir = codeFile.getParentFile();
11651            final File beforeCodeFile = codeFile;
11652            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11653
11654            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11655            try {
11656                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11657            } catch (ErrnoException e) {
11658                Slog.w(TAG, "Failed to rename", e);
11659                return false;
11660            }
11661
11662            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11663                Slog.w(TAG, "Failed to restorecon");
11664                return false;
11665            }
11666
11667            // Reflect the rename internally
11668            codeFile = afterCodeFile;
11669            resourceFile = afterCodeFile;
11670
11671            // Reflect the rename in scanned details
11672            pkg.codePath = afterCodeFile.getAbsolutePath();
11673            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11674                    pkg.baseCodePath);
11675            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11676                    pkg.splitCodePaths);
11677
11678            // Reflect the rename in app info
11679            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11680            pkg.applicationInfo.setCodePath(pkg.codePath);
11681            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11682            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11683            pkg.applicationInfo.setResourcePath(pkg.codePath);
11684            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11685            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11686
11687            return true;
11688        }
11689
11690        int doPostInstall(int status, int uid) {
11691            if (status != PackageManager.INSTALL_SUCCEEDED) {
11692                cleanUp();
11693            }
11694            return status;
11695        }
11696
11697        @Override
11698        String getCodePath() {
11699            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11700        }
11701
11702        @Override
11703        String getResourcePath() {
11704            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11705        }
11706
11707        private boolean cleanUp() {
11708            if (codeFile == null || !codeFile.exists()) {
11709                return false;
11710            }
11711
11712            if (codeFile.isDirectory()) {
11713                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11714            } else {
11715                codeFile.delete();
11716            }
11717
11718            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11719                resourceFile.delete();
11720            }
11721
11722            return true;
11723        }
11724
11725        void cleanUpResourcesLI() {
11726            // Try enumerating all code paths before deleting
11727            List<String> allCodePaths = Collections.EMPTY_LIST;
11728            if (codeFile != null && codeFile.exists()) {
11729                try {
11730                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11731                    allCodePaths = pkg.getAllCodePaths();
11732                } catch (PackageParserException e) {
11733                    // Ignored; we tried our best
11734                }
11735            }
11736
11737            cleanUp();
11738            removeDexFiles(allCodePaths, instructionSets);
11739        }
11740
11741        boolean doPostDeleteLI(boolean delete) {
11742            // XXX err, shouldn't we respect the delete flag?
11743            cleanUpResourcesLI();
11744            return true;
11745        }
11746    }
11747
11748    private boolean isAsecExternal(String cid) {
11749        final String asecPath = PackageHelper.getSdFilesystem(cid);
11750        return !asecPath.startsWith(mAsecInternalPath);
11751    }
11752
11753    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11754            PackageManagerException {
11755        if (copyRet < 0) {
11756            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11757                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11758                throw new PackageManagerException(copyRet, message);
11759            }
11760        }
11761    }
11762
11763    /**
11764     * Extract the MountService "container ID" from the full code path of an
11765     * .apk.
11766     */
11767    static String cidFromCodePath(String fullCodePath) {
11768        int eidx = fullCodePath.lastIndexOf("/");
11769        String subStr1 = fullCodePath.substring(0, eidx);
11770        int sidx = subStr1.lastIndexOf("/");
11771        return subStr1.substring(sidx+1, eidx);
11772    }
11773
11774    /**
11775     * Logic to handle installation of ASEC applications, including copying and
11776     * renaming logic.
11777     */
11778    class AsecInstallArgs extends InstallArgs {
11779        static final String RES_FILE_NAME = "pkg.apk";
11780        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11781
11782        String cid;
11783        String packagePath;
11784        String resourcePath;
11785
11786        /** New install */
11787        AsecInstallArgs(InstallParams params) {
11788            super(params.origin, params.move, params.observer, params.installFlags,
11789                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11790                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11791                    params.grantedRuntimePermissions,
11792                    params.traceMethod, params.traceCookie);
11793        }
11794
11795        /** Existing install */
11796        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11797                        boolean isExternal, boolean isForwardLocked) {
11798            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11799                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11800                    instructionSets, null, null, null, 0);
11801            // Hackily pretend we're still looking at a full code path
11802            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11803                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11804            }
11805
11806            // Extract cid from fullCodePath
11807            int eidx = fullCodePath.lastIndexOf("/");
11808            String subStr1 = fullCodePath.substring(0, eidx);
11809            int sidx = subStr1.lastIndexOf("/");
11810            cid = subStr1.substring(sidx+1, eidx);
11811            setMountPath(subStr1);
11812        }
11813
11814        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11815            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11816                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11817                    instructionSets, null, null, null, 0);
11818            this.cid = cid;
11819            setMountPath(PackageHelper.getSdDir(cid));
11820        }
11821
11822        void createCopyFile() {
11823            cid = mInstallerService.allocateExternalStageCidLegacy();
11824        }
11825
11826        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11827            if (origin.staged && origin.cid != null) {
11828                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11829                cid = origin.cid;
11830                setMountPath(PackageHelper.getSdDir(cid));
11831                return PackageManager.INSTALL_SUCCEEDED;
11832            }
11833
11834            if (temp) {
11835                createCopyFile();
11836            } else {
11837                /*
11838                 * Pre-emptively destroy the container since it's destroyed if
11839                 * copying fails due to it existing anyway.
11840                 */
11841                PackageHelper.destroySdDir(cid);
11842            }
11843
11844            final String newMountPath = imcs.copyPackageToContainer(
11845                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11846                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11847
11848            if (newMountPath != null) {
11849                setMountPath(newMountPath);
11850                return PackageManager.INSTALL_SUCCEEDED;
11851            } else {
11852                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11853            }
11854        }
11855
11856        @Override
11857        String getCodePath() {
11858            return packagePath;
11859        }
11860
11861        @Override
11862        String getResourcePath() {
11863            return resourcePath;
11864        }
11865
11866        int doPreInstall(int status) {
11867            if (status != PackageManager.INSTALL_SUCCEEDED) {
11868                // Destroy container
11869                PackageHelper.destroySdDir(cid);
11870            } else {
11871                boolean mounted = PackageHelper.isContainerMounted(cid);
11872                if (!mounted) {
11873                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11874                            Process.SYSTEM_UID);
11875                    if (newMountPath != null) {
11876                        setMountPath(newMountPath);
11877                    } else {
11878                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11879                    }
11880                }
11881            }
11882            return status;
11883        }
11884
11885        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11886            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11887            String newMountPath = null;
11888            if (PackageHelper.isContainerMounted(cid)) {
11889                // Unmount the container
11890                if (!PackageHelper.unMountSdDir(cid)) {
11891                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11892                    return false;
11893                }
11894            }
11895            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11896                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11897                        " which might be stale. Will try to clean up.");
11898                // Clean up the stale container and proceed to recreate.
11899                if (!PackageHelper.destroySdDir(newCacheId)) {
11900                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11901                    return false;
11902                }
11903                // Successfully cleaned up stale container. Try to rename again.
11904                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11905                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11906                            + " inspite of cleaning it up.");
11907                    return false;
11908                }
11909            }
11910            if (!PackageHelper.isContainerMounted(newCacheId)) {
11911                Slog.w(TAG, "Mounting container " + newCacheId);
11912                newMountPath = PackageHelper.mountSdDir(newCacheId,
11913                        getEncryptKey(), Process.SYSTEM_UID);
11914            } else {
11915                newMountPath = PackageHelper.getSdDir(newCacheId);
11916            }
11917            if (newMountPath == null) {
11918                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11919                return false;
11920            }
11921            Log.i(TAG, "Succesfully renamed " + cid +
11922                    " to " + newCacheId +
11923                    " at new path: " + newMountPath);
11924            cid = newCacheId;
11925
11926            final File beforeCodeFile = new File(packagePath);
11927            setMountPath(newMountPath);
11928            final File afterCodeFile = new File(packagePath);
11929
11930            // Reflect the rename in scanned details
11931            pkg.codePath = afterCodeFile.getAbsolutePath();
11932            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11933                    pkg.baseCodePath);
11934            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11935                    pkg.splitCodePaths);
11936
11937            // Reflect the rename in app info
11938            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11939            pkg.applicationInfo.setCodePath(pkg.codePath);
11940            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11941            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11942            pkg.applicationInfo.setResourcePath(pkg.codePath);
11943            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11944            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11945
11946            return true;
11947        }
11948
11949        private void setMountPath(String mountPath) {
11950            final File mountFile = new File(mountPath);
11951
11952            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11953            if (monolithicFile.exists()) {
11954                packagePath = monolithicFile.getAbsolutePath();
11955                if (isFwdLocked()) {
11956                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11957                } else {
11958                    resourcePath = packagePath;
11959                }
11960            } else {
11961                packagePath = mountFile.getAbsolutePath();
11962                resourcePath = packagePath;
11963            }
11964        }
11965
11966        int doPostInstall(int status, int uid) {
11967            if (status != PackageManager.INSTALL_SUCCEEDED) {
11968                cleanUp();
11969            } else {
11970                final int groupOwner;
11971                final String protectedFile;
11972                if (isFwdLocked()) {
11973                    groupOwner = UserHandle.getSharedAppGid(uid);
11974                    protectedFile = RES_FILE_NAME;
11975                } else {
11976                    groupOwner = -1;
11977                    protectedFile = null;
11978                }
11979
11980                if (uid < Process.FIRST_APPLICATION_UID
11981                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11982                    Slog.e(TAG, "Failed to finalize " + cid);
11983                    PackageHelper.destroySdDir(cid);
11984                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11985                }
11986
11987                boolean mounted = PackageHelper.isContainerMounted(cid);
11988                if (!mounted) {
11989                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11990                }
11991            }
11992            return status;
11993        }
11994
11995        private void cleanUp() {
11996            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11997
11998            // Destroy secure container
11999            PackageHelper.destroySdDir(cid);
12000        }
12001
12002        private List<String> getAllCodePaths() {
12003            final File codeFile = new File(getCodePath());
12004            if (codeFile != null && codeFile.exists()) {
12005                try {
12006                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12007                    return pkg.getAllCodePaths();
12008                } catch (PackageParserException e) {
12009                    // Ignored; we tried our best
12010                }
12011            }
12012            return Collections.EMPTY_LIST;
12013        }
12014
12015        void cleanUpResourcesLI() {
12016            // Enumerate all code paths before deleting
12017            cleanUpResourcesLI(getAllCodePaths());
12018        }
12019
12020        private void cleanUpResourcesLI(List<String> allCodePaths) {
12021            cleanUp();
12022            removeDexFiles(allCodePaths, instructionSets);
12023        }
12024
12025        String getPackageName() {
12026            return getAsecPackageName(cid);
12027        }
12028
12029        boolean doPostDeleteLI(boolean delete) {
12030            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12031            final List<String> allCodePaths = getAllCodePaths();
12032            boolean mounted = PackageHelper.isContainerMounted(cid);
12033            if (mounted) {
12034                // Unmount first
12035                if (PackageHelper.unMountSdDir(cid)) {
12036                    mounted = false;
12037                }
12038            }
12039            if (!mounted && delete) {
12040                cleanUpResourcesLI(allCodePaths);
12041            }
12042            return !mounted;
12043        }
12044
12045        @Override
12046        int doPreCopy() {
12047            if (isFwdLocked()) {
12048                if (!PackageHelper.fixSdPermissions(cid,
12049                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12050                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12051                }
12052            }
12053
12054            return PackageManager.INSTALL_SUCCEEDED;
12055        }
12056
12057        @Override
12058        int doPostCopy(int uid) {
12059            if (isFwdLocked()) {
12060                if (uid < Process.FIRST_APPLICATION_UID
12061                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12062                                RES_FILE_NAME)) {
12063                    Slog.e(TAG, "Failed to finalize " + cid);
12064                    PackageHelper.destroySdDir(cid);
12065                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12066                }
12067            }
12068
12069            return PackageManager.INSTALL_SUCCEEDED;
12070        }
12071    }
12072
12073    /**
12074     * Logic to handle movement of existing installed applications.
12075     */
12076    class MoveInstallArgs extends InstallArgs {
12077        private File codeFile;
12078        private File resourceFile;
12079
12080        /** New install */
12081        MoveInstallArgs(InstallParams params) {
12082            super(params.origin, params.move, params.observer, params.installFlags,
12083                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
12084                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12085                    params.grantedRuntimePermissions,
12086                    params.traceMethod, params.traceCookie);
12087        }
12088
12089        int copyApk(IMediaContainerService imcs, boolean temp) {
12090            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12091                    + move.fromUuid + " to " + move.toUuid);
12092            synchronized (mInstaller) {
12093                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12094                        move.dataAppName, move.appId, move.seinfo) != 0) {
12095                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12096                }
12097            }
12098
12099            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12100            resourceFile = codeFile;
12101            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12102
12103            return PackageManager.INSTALL_SUCCEEDED;
12104        }
12105
12106        int doPreInstall(int status) {
12107            if (status != PackageManager.INSTALL_SUCCEEDED) {
12108                cleanUp(move.toUuid);
12109            }
12110            return status;
12111        }
12112
12113        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12114            if (status != PackageManager.INSTALL_SUCCEEDED) {
12115                cleanUp(move.toUuid);
12116                return false;
12117            }
12118
12119            // Reflect the move in app info
12120            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12121            pkg.applicationInfo.setCodePath(pkg.codePath);
12122            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12123            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12124            pkg.applicationInfo.setResourcePath(pkg.codePath);
12125            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12126            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12127
12128            return true;
12129        }
12130
12131        int doPostInstall(int status, int uid) {
12132            if (status == PackageManager.INSTALL_SUCCEEDED) {
12133                cleanUp(move.fromUuid);
12134            } else {
12135                cleanUp(move.toUuid);
12136            }
12137            return status;
12138        }
12139
12140        @Override
12141        String getCodePath() {
12142            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12143        }
12144
12145        @Override
12146        String getResourcePath() {
12147            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12148        }
12149
12150        private boolean cleanUp(String volumeUuid) {
12151            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12152                    move.dataAppName);
12153            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12154            synchronized (mInstallLock) {
12155                // Clean up both app data and code
12156                removeDataDirsLI(volumeUuid, move.packageName);
12157                if (codeFile.isDirectory()) {
12158                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12159                } else {
12160                    codeFile.delete();
12161                }
12162            }
12163            return true;
12164        }
12165
12166        void cleanUpResourcesLI() {
12167            throw new UnsupportedOperationException();
12168        }
12169
12170        boolean doPostDeleteLI(boolean delete) {
12171            throw new UnsupportedOperationException();
12172        }
12173    }
12174
12175    static String getAsecPackageName(String packageCid) {
12176        int idx = packageCid.lastIndexOf("-");
12177        if (idx == -1) {
12178            return packageCid;
12179        }
12180        return packageCid.substring(0, idx);
12181    }
12182
12183    // Utility method used to create code paths based on package name and available index.
12184    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12185        String idxStr = "";
12186        int idx = 1;
12187        // Fall back to default value of idx=1 if prefix is not
12188        // part of oldCodePath
12189        if (oldCodePath != null) {
12190            String subStr = oldCodePath;
12191            // Drop the suffix right away
12192            if (suffix != null && subStr.endsWith(suffix)) {
12193                subStr = subStr.substring(0, subStr.length() - suffix.length());
12194            }
12195            // If oldCodePath already contains prefix find out the
12196            // ending index to either increment or decrement.
12197            int sidx = subStr.lastIndexOf(prefix);
12198            if (sidx != -1) {
12199                subStr = subStr.substring(sidx + prefix.length());
12200                if (subStr != null) {
12201                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12202                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12203                    }
12204                    try {
12205                        idx = Integer.parseInt(subStr);
12206                        if (idx <= 1) {
12207                            idx++;
12208                        } else {
12209                            idx--;
12210                        }
12211                    } catch(NumberFormatException e) {
12212                    }
12213                }
12214            }
12215        }
12216        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12217        return prefix + idxStr;
12218    }
12219
12220    private File getNextCodePath(File targetDir, String packageName) {
12221        int suffix = 1;
12222        File result;
12223        do {
12224            result = new File(targetDir, packageName + "-" + suffix);
12225            suffix++;
12226        } while (result.exists());
12227        return result;
12228    }
12229
12230    // Utility method that returns the relative package path with respect
12231    // to the installation directory. Like say for /data/data/com.test-1.apk
12232    // string com.test-1 is returned.
12233    static String deriveCodePathName(String codePath) {
12234        if (codePath == null) {
12235            return null;
12236        }
12237        final File codeFile = new File(codePath);
12238        final String name = codeFile.getName();
12239        if (codeFile.isDirectory()) {
12240            return name;
12241        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12242            final int lastDot = name.lastIndexOf('.');
12243            return name.substring(0, lastDot);
12244        } else {
12245            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12246            return null;
12247        }
12248    }
12249
12250    static class PackageInstalledInfo {
12251        String name;
12252        int uid;
12253        // The set of users that originally had this package installed.
12254        int[] origUsers;
12255        // The set of users that now have this package installed.
12256        int[] newUsers;
12257        PackageParser.Package pkg;
12258        int returnCode;
12259        String returnMsg;
12260        PackageRemovedInfo removedInfo;
12261
12262        public void setError(int code, String msg) {
12263            returnCode = code;
12264            returnMsg = msg;
12265            Slog.w(TAG, msg);
12266        }
12267
12268        public void setError(String msg, PackageParserException e) {
12269            returnCode = e.error;
12270            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12271            Slog.w(TAG, msg, e);
12272        }
12273
12274        public void setError(String msg, PackageManagerException e) {
12275            returnCode = e.error;
12276            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12277            Slog.w(TAG, msg, e);
12278        }
12279
12280        // In some error cases we want to convey more info back to the observer
12281        String origPackage;
12282        String origPermission;
12283    }
12284
12285    /*
12286     * Install a non-existing package.
12287     */
12288    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12289            UserHandle user, String installerPackageName, String volumeUuid,
12290            PackageInstalledInfo res) {
12291        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12292
12293        // Remember this for later, in case we need to rollback this install
12294        String pkgName = pkg.packageName;
12295
12296        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12297        // TODO: b/23350563
12298        final boolean dataDirExists = Environment
12299                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12300
12301        synchronized(mPackages) {
12302            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12303                // A package with the same name is already installed, though
12304                // it has been renamed to an older name.  The package we
12305                // are trying to install should be installed as an update to
12306                // the existing one, but that has not been requested, so bail.
12307                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12308                        + " without first uninstalling package running as "
12309                        + mSettings.mRenamedPackages.get(pkgName));
12310                return;
12311            }
12312            if (mPackages.containsKey(pkgName)) {
12313                // Don't allow installation over an existing package with the same name.
12314                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12315                        + " without first uninstalling.");
12316                return;
12317            }
12318        }
12319
12320        try {
12321            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12322                    System.currentTimeMillis(), user);
12323
12324            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12325            // delete the partially installed application. the data directory will have to be
12326            // restored if it was already existing
12327            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12328                // remove package from internal structures.  Note that we want deletePackageX to
12329                // delete the package data and cache directories that it created in
12330                // scanPackageLocked, unless those directories existed before we even tried to
12331                // install.
12332                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12333                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12334                                res.removedInfo, true);
12335            }
12336
12337        } catch (PackageManagerException e) {
12338            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12339        }
12340
12341        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12342    }
12343
12344    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12345        // Can't rotate keys during boot or if sharedUser.
12346        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12347                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12348            return false;
12349        }
12350        // app is using upgradeKeySets; make sure all are valid
12351        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12352        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12353        for (int i = 0; i < upgradeKeySets.length; i++) {
12354            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12355                Slog.wtf(TAG, "Package "
12356                         + (oldPs.name != null ? oldPs.name : "<null>")
12357                         + " contains upgrade-key-set reference to unknown key-set: "
12358                         + upgradeKeySets[i]
12359                         + " reverting to signatures check.");
12360                return false;
12361            }
12362        }
12363        return true;
12364    }
12365
12366    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12367        // Upgrade keysets are being used.  Determine if new package has a superset of the
12368        // required keys.
12369        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12370        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12371        for (int i = 0; i < upgradeKeySets.length; i++) {
12372            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12373            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12374                return true;
12375            }
12376        }
12377        return false;
12378    }
12379
12380    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12381            UserHandle user, String installerPackageName, String volumeUuid,
12382            PackageInstalledInfo res) {
12383        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12384
12385        final PackageParser.Package oldPackage;
12386        final String pkgName = pkg.packageName;
12387        final int[] allUsers;
12388        final boolean[] perUserInstalled;
12389
12390        // First find the old package info and check signatures
12391        synchronized(mPackages) {
12392            oldPackage = mPackages.get(pkgName);
12393            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12394            if (isEphemeral && !oldIsEphemeral) {
12395                // can't downgrade from full to ephemeral
12396                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12397                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12398                return;
12399            }
12400            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12401            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12402            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12403                if(!checkUpgradeKeySetLP(ps, pkg)) {
12404                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12405                            "New package not signed by keys specified by upgrade-keysets: "
12406                            + pkgName);
12407                    return;
12408                }
12409            } else {
12410                // default to original signature matching
12411                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12412                    != PackageManager.SIGNATURE_MATCH) {
12413                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12414                            "New package has a different signature: " + pkgName);
12415                    return;
12416                }
12417            }
12418
12419            // In case of rollback, remember per-user/profile install state
12420            allUsers = sUserManager.getUserIds();
12421            perUserInstalled = new boolean[allUsers.length];
12422            for (int i = 0; i < allUsers.length; i++) {
12423                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12424            }
12425        }
12426
12427        boolean sysPkg = (isSystemApp(oldPackage));
12428        if (sysPkg) {
12429            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12430                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12431        } else {
12432            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12433                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12434        }
12435    }
12436
12437    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12438            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12439            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12440            String volumeUuid, PackageInstalledInfo res) {
12441        String pkgName = deletedPackage.packageName;
12442        boolean deletedPkg = true;
12443        boolean updatedSettings = false;
12444
12445        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12446                + deletedPackage);
12447        long origUpdateTime;
12448        if (pkg.mExtras != null) {
12449            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12450        } else {
12451            origUpdateTime = 0;
12452        }
12453
12454        // First delete the existing package while retaining the data directory
12455        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12456                res.removedInfo, true)) {
12457            // If the existing package wasn't successfully deleted
12458            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12459            deletedPkg = false;
12460        } else {
12461            // Successfully deleted the old package; proceed with replace.
12462
12463            // If deleted package lived in a container, give users a chance to
12464            // relinquish resources before killing.
12465            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12466                if (DEBUG_INSTALL) {
12467                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12468                }
12469                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12470                final ArrayList<String> pkgList = new ArrayList<String>(1);
12471                pkgList.add(deletedPackage.applicationInfo.packageName);
12472                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12473            }
12474
12475            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12476            try {
12477                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12478                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12479                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12480                        perUserInstalled, res, user);
12481                updatedSettings = true;
12482            } catch (PackageManagerException e) {
12483                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12484            }
12485        }
12486
12487        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12488            // remove package from internal structures.  Note that we want deletePackageX to
12489            // delete the package data and cache directories that it created in
12490            // scanPackageLocked, unless those directories existed before we even tried to
12491            // install.
12492            if(updatedSettings) {
12493                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12494                deletePackageLI(
12495                        pkgName, null, true, allUsers, perUserInstalled,
12496                        PackageManager.DELETE_KEEP_DATA,
12497                                res.removedInfo, true);
12498            }
12499            // Since we failed to install the new package we need to restore the old
12500            // package that we deleted.
12501            if (deletedPkg) {
12502                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12503                File restoreFile = new File(deletedPackage.codePath);
12504                // Parse old package
12505                boolean oldExternal = isExternal(deletedPackage);
12506                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12507                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12508                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12509                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12510                try {
12511                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12512                            null);
12513                } catch (PackageManagerException e) {
12514                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12515                            + e.getMessage());
12516                    return;
12517                }
12518                // Restore of old package succeeded. Update permissions.
12519                // writer
12520                synchronized (mPackages) {
12521                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12522                            UPDATE_PERMISSIONS_ALL);
12523                    // can downgrade to reader
12524                    mSettings.writeLPr();
12525                }
12526                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12527            }
12528        }
12529    }
12530
12531    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12532            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12533            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12534            String volumeUuid, PackageInstalledInfo res) {
12535        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12536                + ", old=" + deletedPackage);
12537        boolean disabledSystem = false;
12538        boolean updatedSettings = false;
12539        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12540        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12541                != 0) {
12542            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12543        }
12544        String packageName = deletedPackage.packageName;
12545        if (packageName == null) {
12546            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12547                    "Attempt to delete null packageName.");
12548            return;
12549        }
12550        PackageParser.Package oldPkg;
12551        PackageSetting oldPkgSetting;
12552        // reader
12553        synchronized (mPackages) {
12554            oldPkg = mPackages.get(packageName);
12555            oldPkgSetting = mSettings.mPackages.get(packageName);
12556            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12557                    (oldPkgSetting == null)) {
12558                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12559                        "Couldn't find package:" + packageName + " information");
12560                return;
12561            }
12562        }
12563
12564        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12565
12566        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12567        res.removedInfo.removedPackage = packageName;
12568        // Remove existing system package
12569        removePackageLI(oldPkgSetting, true);
12570        // writer
12571        synchronized (mPackages) {
12572            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12573            if (!disabledSystem && deletedPackage != null) {
12574                // We didn't need to disable the .apk as a current system package,
12575                // which means we are replacing another update that is already
12576                // installed.  We need to make sure to delete the older one's .apk.
12577                res.removedInfo.args = createInstallArgsForExisting(0,
12578                        deletedPackage.applicationInfo.getCodePath(),
12579                        deletedPackage.applicationInfo.getResourcePath(),
12580                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12581            } else {
12582                res.removedInfo.args = null;
12583            }
12584        }
12585
12586        // Successfully disabled the old package. Now proceed with re-installation
12587        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12588
12589        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12590        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12591
12592        PackageParser.Package newPackage = null;
12593        try {
12594            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12595            if (newPackage.mExtras != null) {
12596                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12597                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12598                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12599
12600                // is the update attempting to change shared user? that isn't going to work...
12601                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12602                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12603                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12604                            + " to " + newPkgSetting.sharedUser);
12605                    updatedSettings = true;
12606                }
12607            }
12608
12609            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12610                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12611                        perUserInstalled, res, user);
12612                updatedSettings = true;
12613            }
12614
12615        } catch (PackageManagerException e) {
12616            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12617        }
12618
12619        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12620            // Re installation failed. Restore old information
12621            // Remove new pkg information
12622            if (newPackage != null) {
12623                removeInstalledPackageLI(newPackage, true);
12624            }
12625            // Add back the old system package
12626            try {
12627                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12628            } catch (PackageManagerException e) {
12629                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12630            }
12631            // Restore the old system information in Settings
12632            synchronized (mPackages) {
12633                if (disabledSystem) {
12634                    mSettings.enableSystemPackageLPw(packageName);
12635                }
12636                if (updatedSettings) {
12637                    mSettings.setInstallerPackageName(packageName,
12638                            oldPkgSetting.installerPackageName);
12639                }
12640                mSettings.writeLPr();
12641            }
12642        }
12643    }
12644
12645    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12646        // Collect all used permissions in the UID
12647        ArraySet<String> usedPermissions = new ArraySet<>();
12648        final int packageCount = su.packages.size();
12649        for (int i = 0; i < packageCount; i++) {
12650            PackageSetting ps = su.packages.valueAt(i);
12651            if (ps.pkg == null) {
12652                continue;
12653            }
12654            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12655            for (int j = 0; j < requestedPermCount; j++) {
12656                String permission = ps.pkg.requestedPermissions.get(j);
12657                BasePermission bp = mSettings.mPermissions.get(permission);
12658                if (bp != null) {
12659                    usedPermissions.add(permission);
12660                }
12661            }
12662        }
12663
12664        PermissionsState permissionsState = su.getPermissionsState();
12665        // Prune install permissions
12666        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12667        final int installPermCount = installPermStates.size();
12668        for (int i = installPermCount - 1; i >= 0;  i--) {
12669            PermissionState permissionState = installPermStates.get(i);
12670            if (!usedPermissions.contains(permissionState.getName())) {
12671                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12672                if (bp != null) {
12673                    permissionsState.revokeInstallPermission(bp);
12674                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12675                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12676                }
12677            }
12678        }
12679
12680        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12681
12682        // Prune runtime permissions
12683        for (int userId : allUserIds) {
12684            List<PermissionState> runtimePermStates = permissionsState
12685                    .getRuntimePermissionStates(userId);
12686            final int runtimePermCount = runtimePermStates.size();
12687            for (int i = runtimePermCount - 1; i >= 0; i--) {
12688                PermissionState permissionState = runtimePermStates.get(i);
12689                if (!usedPermissions.contains(permissionState.getName())) {
12690                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12691                    if (bp != null) {
12692                        permissionsState.revokeRuntimePermission(bp, userId);
12693                        permissionsState.updatePermissionFlags(bp, userId,
12694                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12695                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12696                                runtimePermissionChangedUserIds, userId);
12697                    }
12698                }
12699            }
12700        }
12701
12702        return runtimePermissionChangedUserIds;
12703    }
12704
12705    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12706            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12707            UserHandle user) {
12708        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12709
12710        String pkgName = newPackage.packageName;
12711        synchronized (mPackages) {
12712            //write settings. the installStatus will be incomplete at this stage.
12713            //note that the new package setting would have already been
12714            //added to mPackages. It hasn't been persisted yet.
12715            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12716            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12717            mSettings.writeLPr();
12718            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12719        }
12720
12721        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12722        synchronized (mPackages) {
12723            updatePermissionsLPw(newPackage.packageName, newPackage,
12724                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12725                            ? UPDATE_PERMISSIONS_ALL : 0));
12726            // For system-bundled packages, we assume that installing an upgraded version
12727            // of the package implies that the user actually wants to run that new code,
12728            // so we enable the package.
12729            PackageSetting ps = mSettings.mPackages.get(pkgName);
12730            if (ps != null) {
12731                if (isSystemApp(newPackage)) {
12732                    // NB: implicit assumption that system package upgrades apply to all users
12733                    if (DEBUG_INSTALL) {
12734                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12735                    }
12736                    if (res.origUsers != null) {
12737                        for (int userHandle : res.origUsers) {
12738                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12739                                    userHandle, installerPackageName);
12740                        }
12741                    }
12742                    // Also convey the prior install/uninstall state
12743                    if (allUsers != null && perUserInstalled != null) {
12744                        for (int i = 0; i < allUsers.length; i++) {
12745                            if (DEBUG_INSTALL) {
12746                                Slog.d(TAG, "    user " + allUsers[i]
12747                                        + " => " + perUserInstalled[i]);
12748                            }
12749                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12750                        }
12751                        // these install state changes will be persisted in the
12752                        // upcoming call to mSettings.writeLPr().
12753                    }
12754                }
12755                // It's implied that when a user requests installation, they want the app to be
12756                // installed and enabled.
12757                int userId = user.getIdentifier();
12758                if (userId != UserHandle.USER_ALL) {
12759                    ps.setInstalled(true, userId);
12760                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12761                }
12762            }
12763            res.name = pkgName;
12764            res.uid = newPackage.applicationInfo.uid;
12765            res.pkg = newPackage;
12766            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12767            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12768            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12769            //to update install status
12770            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12771            mSettings.writeLPr();
12772            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12773        }
12774
12775        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12776    }
12777
12778    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12779        try {
12780            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12781            installPackageLI(args, res);
12782        } finally {
12783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12784        }
12785    }
12786
12787    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12788        final int installFlags = args.installFlags;
12789        final String installerPackageName = args.installerPackageName;
12790        final String volumeUuid = args.volumeUuid;
12791        final File tmpPackageFile = new File(args.getCodePath());
12792        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12793        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12794                || (args.volumeUuid != null));
12795        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12796        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12797        boolean replace = false;
12798        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12799        if (args.move != null) {
12800            // moving a complete application; perfom an initial scan on the new install location
12801            scanFlags |= SCAN_INITIAL;
12802        }
12803        // Result object to be returned
12804        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12805
12806        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12807
12808        // Sanity check
12809        if (ephemeral && (forwardLocked || onExternal)) {
12810            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12811                    + " external=" + onExternal);
12812            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12813            return;
12814        }
12815
12816        // Retrieve PackageSettings and parse package
12817        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12818                | PackageParser.PARSE_ENFORCE_CODE
12819                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12820                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12821                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0)
12822                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12823        PackageParser pp = new PackageParser();
12824        pp.setSeparateProcesses(mSeparateProcesses);
12825        pp.setDisplayMetrics(mMetrics);
12826
12827        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12828        final PackageParser.Package pkg;
12829        try {
12830            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12831        } catch (PackageParserException e) {
12832            res.setError("Failed parse during installPackageLI", e);
12833            return;
12834        } finally {
12835            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12836        }
12837
12838        // Mark that we have an install time CPU ABI override.
12839        pkg.cpuAbiOverride = args.abiOverride;
12840
12841        String pkgName = res.name = pkg.packageName;
12842        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12843            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12844                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12845                return;
12846            }
12847        }
12848
12849        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12850        try {
12851            pp.collectCertificates(pkg, parseFlags);
12852        } catch (PackageParserException e) {
12853            res.setError("Failed collect during installPackageLI", e);
12854            return;
12855        } finally {
12856            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12857        }
12858
12859        /* If the installer passed in a manifest digest, compare it now. */
12860        if (args.manifestDigest != null) {
12861            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12862            try {
12863                pp.collectManifestDigest(pkg);
12864            } catch (PackageParserException e) {
12865                res.setError("Failed collect during installPackageLI", e);
12866                return;
12867            } finally {
12868                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12869            }
12870
12871            if (DEBUG_INSTALL) {
12872                final String parsedManifest = pkg.manifestDigest == null ? "null"
12873                        : pkg.manifestDigest.toString();
12874                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12875                        + parsedManifest);
12876            }
12877
12878            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12879                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12880                return;
12881            }
12882        } else if (DEBUG_INSTALL) {
12883            final String parsedManifest = pkg.manifestDigest == null
12884                    ? "null" : pkg.manifestDigest.toString();
12885            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12886        }
12887
12888        // Get rid of all references to package scan path via parser.
12889        pp = null;
12890        String oldCodePath = null;
12891        boolean systemApp = false;
12892        synchronized (mPackages) {
12893            // Check if installing already existing package
12894            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12895                String oldName = mSettings.mRenamedPackages.get(pkgName);
12896                if (pkg.mOriginalPackages != null
12897                        && pkg.mOriginalPackages.contains(oldName)
12898                        && mPackages.containsKey(oldName)) {
12899                    // This package is derived from an original package,
12900                    // and this device has been updating from that original
12901                    // name.  We must continue using the original name, so
12902                    // rename the new package here.
12903                    pkg.setPackageName(oldName);
12904                    pkgName = pkg.packageName;
12905                    replace = true;
12906                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12907                            + oldName + " pkgName=" + pkgName);
12908                } else if (mPackages.containsKey(pkgName)) {
12909                    // This package, under its official name, already exists
12910                    // on the device; we should replace it.
12911                    replace = true;
12912                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12913                }
12914
12915                // Prevent apps opting out from runtime permissions
12916                if (replace) {
12917                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12918                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12919                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12920                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12921                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12922                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12923                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12924                                        + " doesn't support runtime permissions but the old"
12925                                        + " target SDK " + oldTargetSdk + " does.");
12926                        return;
12927                    }
12928                }
12929            }
12930
12931            PackageSetting ps = mSettings.mPackages.get(pkgName);
12932            if (ps != null) {
12933                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12934
12935                // Quick sanity check that we're signed correctly if updating;
12936                // we'll check this again later when scanning, but we want to
12937                // bail early here before tripping over redefined permissions.
12938                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12939                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12940                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12941                                + pkg.packageName + " upgrade keys do not match the "
12942                                + "previously installed version");
12943                        return;
12944                    }
12945                } else {
12946                    try {
12947                        verifySignaturesLP(ps, pkg);
12948                    } catch (PackageManagerException e) {
12949                        res.setError(e.error, e.getMessage());
12950                        return;
12951                    }
12952                }
12953
12954                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12955                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12956                    systemApp = (ps.pkg.applicationInfo.flags &
12957                            ApplicationInfo.FLAG_SYSTEM) != 0;
12958                }
12959                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12960            }
12961
12962            // Check whether the newly-scanned package wants to define an already-defined perm
12963            int N = pkg.permissions.size();
12964            for (int i = N-1; i >= 0; i--) {
12965                PackageParser.Permission perm = pkg.permissions.get(i);
12966                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12967                if (bp != null) {
12968                    // If the defining package is signed with our cert, it's okay.  This
12969                    // also includes the "updating the same package" case, of course.
12970                    // "updating same package" could also involve key-rotation.
12971                    final boolean sigsOk;
12972                    if (bp.sourcePackage.equals(pkg.packageName)
12973                            && (bp.packageSetting instanceof PackageSetting)
12974                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12975                                    scanFlags))) {
12976                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12977                    } else {
12978                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12979                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12980                    }
12981                    if (!sigsOk) {
12982                        // If the owning package is the system itself, we log but allow
12983                        // install to proceed; we fail the install on all other permission
12984                        // redefinitions.
12985                        if (!bp.sourcePackage.equals("android")) {
12986                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12987                                    + pkg.packageName + " attempting to redeclare permission "
12988                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12989                            res.origPermission = perm.info.name;
12990                            res.origPackage = bp.sourcePackage;
12991                            return;
12992                        } else {
12993                            Slog.w(TAG, "Package " + pkg.packageName
12994                                    + " attempting to redeclare system permission "
12995                                    + perm.info.name + "; ignoring new declaration");
12996                            pkg.permissions.remove(i);
12997                        }
12998                    }
12999                }
13000            }
13001
13002        }
13003
13004        if (systemApp) {
13005            if (onExternal) {
13006                // Abort update; system app can't be replaced with app on sdcard
13007                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13008                        "Cannot install updates to system apps on sdcard");
13009                return;
13010            } else if (ephemeral) {
13011                // Abort update; system app can't be replaced with an ephemeral app
13012                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13013                        "Cannot update a system app with an ephemeral app");
13014                return;
13015            }
13016        }
13017
13018        if (args.move != null) {
13019            // We did an in-place move, so dex is ready to roll
13020            scanFlags |= SCAN_NO_DEX;
13021            scanFlags |= SCAN_MOVE;
13022
13023            synchronized (mPackages) {
13024                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13025                if (ps == null) {
13026                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13027                            "Missing settings for moved package " + pkgName);
13028                }
13029
13030                // We moved the entire application as-is, so bring over the
13031                // previously derived ABI information.
13032                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13033                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13034            }
13035
13036        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13037            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13038            scanFlags |= SCAN_NO_DEX;
13039
13040            try {
13041                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13042                        true /* extract libs */);
13043            } catch (PackageManagerException pme) {
13044                Slog.e(TAG, "Error deriving application ABI", pme);
13045                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13046                return;
13047            }
13048        }
13049
13050        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13051            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13052            return;
13053        }
13054
13055        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13056
13057        if (replace) {
13058            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13059                    installerPackageName, volumeUuid, res);
13060        } else {
13061            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13062                    args.user, installerPackageName, volumeUuid, res);
13063        }
13064        synchronized (mPackages) {
13065            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13066            if (ps != null) {
13067                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13068            }
13069        }
13070    }
13071
13072    private void startIntentFilterVerifications(int userId, boolean replacing,
13073            PackageParser.Package pkg) {
13074        if (mIntentFilterVerifierComponent == null) {
13075            Slog.w(TAG, "No IntentFilter verification will not be done as "
13076                    + "there is no IntentFilterVerifier available!");
13077            return;
13078        }
13079
13080        final int verifierUid = getPackageUid(
13081                mIntentFilterVerifierComponent.getPackageName(),
13082                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13083
13084        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13085        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13086        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13087        mHandler.sendMessage(msg);
13088    }
13089
13090    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13091            PackageParser.Package pkg) {
13092        int size = pkg.activities.size();
13093        if (size == 0) {
13094            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13095                    "No activity, so no need to verify any IntentFilter!");
13096            return;
13097        }
13098
13099        final boolean hasDomainURLs = hasDomainURLs(pkg);
13100        if (!hasDomainURLs) {
13101            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13102                    "No domain URLs, so no need to verify any IntentFilter!");
13103            return;
13104        }
13105
13106        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13107                + " if any IntentFilter from the " + size
13108                + " Activities needs verification ...");
13109
13110        int count = 0;
13111        final String packageName = pkg.packageName;
13112
13113        synchronized (mPackages) {
13114            // If this is a new install and we see that we've already run verification for this
13115            // package, we have nothing to do: it means the state was restored from backup.
13116            if (!replacing) {
13117                IntentFilterVerificationInfo ivi =
13118                        mSettings.getIntentFilterVerificationLPr(packageName);
13119                if (ivi != null) {
13120                    if (DEBUG_DOMAIN_VERIFICATION) {
13121                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13122                                + ivi.getStatusString());
13123                    }
13124                    return;
13125                }
13126            }
13127
13128            // If any filters need to be verified, then all need to be.
13129            boolean needToVerify = false;
13130            for (PackageParser.Activity a : pkg.activities) {
13131                for (ActivityIntentInfo filter : a.intents) {
13132                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13133                        if (DEBUG_DOMAIN_VERIFICATION) {
13134                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13135                        }
13136                        needToVerify = true;
13137                        break;
13138                    }
13139                }
13140            }
13141
13142            if (needToVerify) {
13143                final int verificationId = mIntentFilterVerificationToken++;
13144                for (PackageParser.Activity a : pkg.activities) {
13145                    for (ActivityIntentInfo filter : a.intents) {
13146                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13147                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13148                                    "Verification needed for IntentFilter:" + filter.toString());
13149                            mIntentFilterVerifier.addOneIntentFilterVerification(
13150                                    verifierUid, userId, verificationId, filter, packageName);
13151                            count++;
13152                        }
13153                    }
13154                }
13155            }
13156        }
13157
13158        if (count > 0) {
13159            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13160                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13161                    +  " for userId:" + userId);
13162            mIntentFilterVerifier.startVerifications(userId);
13163        } else {
13164            if (DEBUG_DOMAIN_VERIFICATION) {
13165                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13166            }
13167        }
13168    }
13169
13170    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13171        final ComponentName cn  = filter.activity.getComponentName();
13172        final String packageName = cn.getPackageName();
13173
13174        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13175                packageName);
13176        if (ivi == null) {
13177            return true;
13178        }
13179        int status = ivi.getStatus();
13180        switch (status) {
13181            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13182            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13183                return true;
13184
13185            default:
13186                // Nothing to do
13187                return false;
13188        }
13189    }
13190
13191    private static boolean isMultiArch(ApplicationInfo info) {
13192        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13193    }
13194
13195    private static boolean isExternal(PackageParser.Package pkg) {
13196        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13197    }
13198
13199    private static boolean isExternal(PackageSetting ps) {
13200        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13201    }
13202
13203    private static boolean isEphemeral(PackageParser.Package pkg) {
13204        return pkg.applicationInfo.isEphemeralApp();
13205    }
13206
13207    private static boolean isEphemeral(PackageSetting ps) {
13208        return ps.pkg != null && isEphemeral(ps.pkg);
13209    }
13210
13211    private static boolean isSystemApp(PackageParser.Package pkg) {
13212        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13213    }
13214
13215    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13216        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13217    }
13218
13219    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13220        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13221    }
13222
13223    private static boolean isSystemApp(PackageSetting ps) {
13224        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13225    }
13226
13227    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13228        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13229    }
13230
13231    private int packageFlagsToInstallFlags(PackageSetting ps) {
13232        int installFlags = 0;
13233        if (isEphemeral(ps)) {
13234            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13235        }
13236        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13237            // This existing package was an external ASEC install when we have
13238            // the external flag without a UUID
13239            installFlags |= PackageManager.INSTALL_EXTERNAL;
13240        }
13241        if (ps.isForwardLocked()) {
13242            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13243        }
13244        return installFlags;
13245    }
13246
13247    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13248        if (isExternal(pkg)) {
13249            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13250                return StorageManager.UUID_PRIMARY_PHYSICAL;
13251            } else {
13252                return pkg.volumeUuid;
13253            }
13254        } else {
13255            return StorageManager.UUID_PRIVATE_INTERNAL;
13256        }
13257    }
13258
13259    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13260        if (isExternal(pkg)) {
13261            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13262                return mSettings.getExternalVersion();
13263            } else {
13264                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13265            }
13266        } else {
13267            return mSettings.getInternalVersion();
13268        }
13269    }
13270
13271    private void deleteTempPackageFiles() {
13272        final FilenameFilter filter = new FilenameFilter() {
13273            public boolean accept(File dir, String name) {
13274                return name.startsWith("vmdl") && name.endsWith(".tmp");
13275            }
13276        };
13277        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13278            file.delete();
13279        }
13280    }
13281
13282    @Override
13283    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13284            int flags) {
13285        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13286                flags);
13287    }
13288
13289    @Override
13290    public void deletePackage(final String packageName,
13291            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13292        mContext.enforceCallingOrSelfPermission(
13293                android.Manifest.permission.DELETE_PACKAGES, null);
13294        Preconditions.checkNotNull(packageName);
13295        Preconditions.checkNotNull(observer);
13296        final int uid = Binder.getCallingUid();
13297        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13298        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13299        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13300            mContext.enforceCallingOrSelfPermission(
13301                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13302                    "deletePackage for user " + userId);
13303        }
13304
13305        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13306            try {
13307                observer.onPackageDeleted(packageName,
13308                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13309            } catch (RemoteException re) {
13310            }
13311            return;
13312        }
13313
13314        for (int currentUserId : users) {
13315            if (getBlockUninstallForUser(packageName, currentUserId)) {
13316                try {
13317                    observer.onPackageDeleted(packageName,
13318                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13319                } catch (RemoteException re) {
13320                }
13321                return;
13322            }
13323        }
13324
13325        if (DEBUG_REMOVE) {
13326            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13327        }
13328        // Queue up an async operation since the package deletion may take a little while.
13329        mHandler.post(new Runnable() {
13330            public void run() {
13331                mHandler.removeCallbacks(this);
13332                final int returnCode = deletePackageX(packageName, userId, flags);
13333                try {
13334                    observer.onPackageDeleted(packageName, returnCode, null);
13335                } catch (RemoteException e) {
13336                    Log.i(TAG, "Observer no longer exists.");
13337                } //end catch
13338            } //end run
13339        });
13340    }
13341
13342    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13343        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13344                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13345        try {
13346            if (dpm != null) {
13347                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13348                        /* callingUserOnly =*/ false);
13349                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13350                        : deviceOwnerComponentName.getPackageName();
13351                // Does the package contains the device owner?
13352                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13353                // this check is probably not needed, since DO should be registered as a device
13354                // admin on some user too. (Original bug for this: b/17657954)
13355                if (packageName.equals(deviceOwnerPackageName)) {
13356                    return true;
13357                }
13358                // Does it contain a device admin for any user?
13359                int[] users;
13360                if (userId == UserHandle.USER_ALL) {
13361                    users = sUserManager.getUserIds();
13362                } else {
13363                    users = new int[]{userId};
13364                }
13365                for (int i = 0; i < users.length; ++i) {
13366                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13367                        return true;
13368                    }
13369                }
13370            }
13371        } catch (RemoteException e) {
13372        }
13373        return false;
13374    }
13375
13376    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13377        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13378    }
13379
13380    /**
13381     *  This method is an internal method that could be get invoked either
13382     *  to delete an installed package or to clean up a failed installation.
13383     *  After deleting an installed package, a broadcast is sent to notify any
13384     *  listeners that the package has been installed. For cleaning up a failed
13385     *  installation, the broadcast is not necessary since the package's
13386     *  installation wouldn't have sent the initial broadcast either
13387     *  The key steps in deleting a package are
13388     *  deleting the package information in internal structures like mPackages,
13389     *  deleting the packages base directories through installd
13390     *  updating mSettings to reflect current status
13391     *  persisting settings for later use
13392     *  sending a broadcast if necessary
13393     */
13394    private int deletePackageX(String packageName, int userId, int flags) {
13395        final PackageRemovedInfo info = new PackageRemovedInfo();
13396        final boolean res;
13397
13398        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13399                ? UserHandle.ALL : new UserHandle(userId);
13400
13401        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13402            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13403            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13404        }
13405
13406        boolean removedForAllUsers = false;
13407        boolean systemUpdate = false;
13408
13409        PackageParser.Package uninstalledPkg;
13410
13411        // for the uninstall-updates case and restricted profiles, remember the per-
13412        // userhandle installed state
13413        int[] allUsers;
13414        boolean[] perUserInstalled;
13415        synchronized (mPackages) {
13416            uninstalledPkg = mPackages.get(packageName);
13417            PackageSetting ps = mSettings.mPackages.get(packageName);
13418            allUsers = sUserManager.getUserIds();
13419            perUserInstalled = new boolean[allUsers.length];
13420            for (int i = 0; i < allUsers.length; i++) {
13421                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13422            }
13423        }
13424
13425        synchronized (mInstallLock) {
13426            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13427            res = deletePackageLI(packageName, removeForUser,
13428                    true, allUsers, perUserInstalled,
13429                    flags | REMOVE_CHATTY, info, true);
13430            systemUpdate = info.isRemovedPackageSystemUpdate;
13431            synchronized (mPackages) {
13432                if (res) {
13433                    if (!systemUpdate && mPackages.get(packageName) == null) {
13434                        removedForAllUsers = true;
13435                    }
13436                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13437                }
13438            }
13439            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13440                    + " removedForAllUsers=" + removedForAllUsers);
13441        }
13442
13443        if (res) {
13444            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13445
13446            // If the removed package was a system update, the old system package
13447            // was re-enabled; we need to broadcast this information
13448            if (systemUpdate) {
13449                Bundle extras = new Bundle(1);
13450                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13451                        ? info.removedAppId : info.uid);
13452                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13453
13454                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13455                        extras, 0, null, null, null);
13456                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13457                        extras, 0, null, null, null);
13458                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13459                        null, 0, packageName, null, null);
13460            }
13461        }
13462        // Force a gc here.
13463        Runtime.getRuntime().gc();
13464        // Delete the resources here after sending the broadcast to let
13465        // other processes clean up before deleting resources.
13466        if (info.args != null) {
13467            synchronized (mInstallLock) {
13468                info.args.doPostDeleteLI(true);
13469            }
13470        }
13471
13472        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13473    }
13474
13475    class PackageRemovedInfo {
13476        String removedPackage;
13477        int uid = -1;
13478        int removedAppId = -1;
13479        int[] removedUsers = null;
13480        boolean isRemovedPackageSystemUpdate = false;
13481        // Clean up resources deleted packages.
13482        InstallArgs args = null;
13483
13484        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13485            Bundle extras = new Bundle(1);
13486            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13487            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13488            if (replacing) {
13489                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13490            }
13491            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13492            if (removedPackage != null) {
13493                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13494                        extras, 0, null, null, removedUsers);
13495                if (fullRemove && !replacing) {
13496                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13497                            extras, 0, null, null, removedUsers);
13498                }
13499            }
13500            if (removedAppId >= 0) {
13501                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13502                        removedUsers);
13503            }
13504        }
13505    }
13506
13507    /*
13508     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13509     * flag is not set, the data directory is removed as well.
13510     * make sure this flag is set for partially installed apps. If not its meaningless to
13511     * delete a partially installed application.
13512     */
13513    private void removePackageDataLI(PackageSetting ps,
13514            int[] allUserHandles, boolean[] perUserInstalled,
13515            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13516        String packageName = ps.name;
13517        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13518        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13519        // Retrieve object to delete permissions for shared user later on
13520        final PackageSetting deletedPs;
13521        // reader
13522        synchronized (mPackages) {
13523            deletedPs = mSettings.mPackages.get(packageName);
13524            if (outInfo != null) {
13525                outInfo.removedPackage = packageName;
13526                outInfo.removedUsers = deletedPs != null
13527                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13528                        : null;
13529            }
13530        }
13531        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13532            removeDataDirsLI(ps.volumeUuid, packageName);
13533            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13534        }
13535        // writer
13536        synchronized (mPackages) {
13537            if (deletedPs != null) {
13538                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13539                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13540                    clearDefaultBrowserIfNeeded(packageName);
13541                    if (outInfo != null) {
13542                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13543                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13544                    }
13545                    updatePermissionsLPw(deletedPs.name, null, 0);
13546                    if (deletedPs.sharedUser != null) {
13547                        // Remove permissions associated with package. Since runtime
13548                        // permissions are per user we have to kill the removed package
13549                        // or packages running under the shared user of the removed
13550                        // package if revoking the permissions requested only by the removed
13551                        // package is successful and this causes a change in gids.
13552                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13553                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13554                                    userId);
13555                            if (userIdToKill == UserHandle.USER_ALL
13556                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13557                                // If gids changed for this user, kill all affected packages.
13558                                mHandler.post(new Runnable() {
13559                                    @Override
13560                                    public void run() {
13561                                        // This has to happen with no lock held.
13562                                        killApplication(deletedPs.name, deletedPs.appId,
13563                                                KILL_APP_REASON_GIDS_CHANGED);
13564                                    }
13565                                });
13566                                break;
13567                            }
13568                        }
13569                    }
13570                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13571                }
13572                // make sure to preserve per-user disabled state if this removal was just
13573                // a downgrade of a system app to the factory package
13574                if (allUserHandles != null && perUserInstalled != null) {
13575                    if (DEBUG_REMOVE) {
13576                        Slog.d(TAG, "Propagating install state across downgrade");
13577                    }
13578                    for (int i = 0; i < allUserHandles.length; i++) {
13579                        if (DEBUG_REMOVE) {
13580                            Slog.d(TAG, "    user " + allUserHandles[i]
13581                                    + " => " + perUserInstalled[i]);
13582                        }
13583                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13584                    }
13585                }
13586            }
13587            // can downgrade to reader
13588            if (writeSettings) {
13589                // Save settings now
13590                mSettings.writeLPr();
13591            }
13592        }
13593        if (outInfo != null) {
13594            // A user ID was deleted here. Go through all users and remove it
13595            // from KeyStore.
13596            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13597        }
13598    }
13599
13600    static boolean locationIsPrivileged(File path) {
13601        try {
13602            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13603                    .getCanonicalPath();
13604            return path.getCanonicalPath().startsWith(privilegedAppDir);
13605        } catch (IOException e) {
13606            Slog.e(TAG, "Unable to access code path " + path);
13607        }
13608        return false;
13609    }
13610
13611    /*
13612     * Tries to delete system package.
13613     */
13614    private boolean deleteSystemPackageLI(PackageSetting newPs,
13615            int[] allUserHandles, boolean[] perUserInstalled,
13616            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13617        final boolean applyUserRestrictions
13618                = (allUserHandles != null) && (perUserInstalled != null);
13619        PackageSetting disabledPs = null;
13620        // Confirm if the system package has been updated
13621        // An updated system app can be deleted. This will also have to restore
13622        // the system pkg from system partition
13623        // reader
13624        synchronized (mPackages) {
13625            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13626        }
13627        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13628                + " disabledPs=" + disabledPs);
13629        if (disabledPs == null) {
13630            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13631            return false;
13632        } else if (DEBUG_REMOVE) {
13633            Slog.d(TAG, "Deleting system pkg from data partition");
13634        }
13635        if (DEBUG_REMOVE) {
13636            if (applyUserRestrictions) {
13637                Slog.d(TAG, "Remembering install states:");
13638                for (int i = 0; i < allUserHandles.length; i++) {
13639                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13640                }
13641            }
13642        }
13643        // Delete the updated package
13644        outInfo.isRemovedPackageSystemUpdate = true;
13645        if (disabledPs.versionCode < newPs.versionCode) {
13646            // Delete data for downgrades
13647            flags &= ~PackageManager.DELETE_KEEP_DATA;
13648        } else {
13649            // Preserve data by setting flag
13650            flags |= PackageManager.DELETE_KEEP_DATA;
13651        }
13652        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13653                allUserHandles, perUserInstalled, outInfo, writeSettings);
13654        if (!ret) {
13655            return false;
13656        }
13657        // writer
13658        synchronized (mPackages) {
13659            // Reinstate the old system package
13660            mSettings.enableSystemPackageLPw(newPs.name);
13661            // Remove any native libraries from the upgraded package.
13662            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13663        }
13664        // Install the system package
13665        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13666        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13667        if (locationIsPrivileged(disabledPs.codePath)) {
13668            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13669        }
13670
13671        final PackageParser.Package newPkg;
13672        try {
13673            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13674        } catch (PackageManagerException e) {
13675            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13676            return false;
13677        }
13678
13679        // writer
13680        synchronized (mPackages) {
13681            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13682
13683            // Propagate the permissions state as we do not want to drop on the floor
13684            // runtime permissions. The update permissions method below will take
13685            // care of removing obsolete permissions and grant install permissions.
13686            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13687            updatePermissionsLPw(newPkg.packageName, newPkg,
13688                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13689
13690            if (applyUserRestrictions) {
13691                if (DEBUG_REMOVE) {
13692                    Slog.d(TAG, "Propagating install state across reinstall");
13693                }
13694                for (int i = 0; i < allUserHandles.length; i++) {
13695                    if (DEBUG_REMOVE) {
13696                        Slog.d(TAG, "    user " + allUserHandles[i]
13697                                + " => " + perUserInstalled[i]);
13698                    }
13699                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13700
13701                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13702                }
13703                // Regardless of writeSettings we need to ensure that this restriction
13704                // state propagation is persisted
13705                mSettings.writeAllUsersPackageRestrictionsLPr();
13706            }
13707            // can downgrade to reader here
13708            if (writeSettings) {
13709                mSettings.writeLPr();
13710            }
13711        }
13712        return true;
13713    }
13714
13715    private boolean deleteInstalledPackageLI(PackageSetting ps,
13716            boolean deleteCodeAndResources, int flags,
13717            int[] allUserHandles, boolean[] perUserInstalled,
13718            PackageRemovedInfo outInfo, boolean writeSettings) {
13719        if (outInfo != null) {
13720            outInfo.uid = ps.appId;
13721        }
13722
13723        // Delete package data from internal structures and also remove data if flag is set
13724        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13725
13726        // Delete application code and resources
13727        if (deleteCodeAndResources && (outInfo != null)) {
13728            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13729                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13730            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13731        }
13732        return true;
13733    }
13734
13735    @Override
13736    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13737            int userId) {
13738        mContext.enforceCallingOrSelfPermission(
13739                android.Manifest.permission.DELETE_PACKAGES, null);
13740        synchronized (mPackages) {
13741            PackageSetting ps = mSettings.mPackages.get(packageName);
13742            if (ps == null) {
13743                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13744                return false;
13745            }
13746            if (!ps.getInstalled(userId)) {
13747                // Can't block uninstall for an app that is not installed or enabled.
13748                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13749                return false;
13750            }
13751            ps.setBlockUninstall(blockUninstall, userId);
13752            mSettings.writePackageRestrictionsLPr(userId);
13753        }
13754        return true;
13755    }
13756
13757    @Override
13758    public boolean getBlockUninstallForUser(String packageName, int userId) {
13759        synchronized (mPackages) {
13760            PackageSetting ps = mSettings.mPackages.get(packageName);
13761            if (ps == null) {
13762                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13763                return false;
13764            }
13765            return ps.getBlockUninstall(userId);
13766        }
13767    }
13768
13769    @Override
13770    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13771        int callingUid = Binder.getCallingUid();
13772        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13773            throw new SecurityException(
13774                    "setRequiredForSystemUser can only be run by the system or root");
13775        }
13776        synchronized (mPackages) {
13777            PackageSetting ps = mSettings.mPackages.get(packageName);
13778            if (ps == null) {
13779                Log.w(TAG, "Package doesn't exist: " + packageName);
13780                return false;
13781            }
13782            if (systemUserApp) {
13783                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13784            } else {
13785                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13786            }
13787            mSettings.writeLPr();
13788        }
13789        return true;
13790    }
13791
13792    /*
13793     * This method handles package deletion in general
13794     */
13795    private boolean deletePackageLI(String packageName, UserHandle user,
13796            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13797            int flags, PackageRemovedInfo outInfo,
13798            boolean writeSettings) {
13799        if (packageName == null) {
13800            Slog.w(TAG, "Attempt to delete null packageName.");
13801            return false;
13802        }
13803        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13804        PackageSetting ps;
13805        boolean dataOnly = false;
13806        int removeUser = -1;
13807        int appId = -1;
13808        synchronized (mPackages) {
13809            ps = mSettings.mPackages.get(packageName);
13810            if (ps == null) {
13811                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13812                return false;
13813            }
13814            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13815                    && user.getIdentifier() != UserHandle.USER_ALL) {
13816                // The caller is asking that the package only be deleted for a single
13817                // user.  To do this, we just mark its uninstalled state and delete
13818                // its data.  If this is a system app, we only allow this to happen if
13819                // they have set the special DELETE_SYSTEM_APP which requests different
13820                // semantics than normal for uninstalling system apps.
13821                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13822                final int userId = user.getIdentifier();
13823                ps.setUserState(userId,
13824                        COMPONENT_ENABLED_STATE_DEFAULT,
13825                        false, //installed
13826                        true,  //stopped
13827                        true,  //notLaunched
13828                        false, //hidden
13829                        false, //suspended
13830                        null, null, null,
13831                        false, // blockUninstall
13832                        ps.readUserState(userId).domainVerificationStatus, 0);
13833                if (!isSystemApp(ps)) {
13834                    // Do not uninstall the APK if an app should be cached
13835                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13836                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13837                        // Other user still have this package installed, so all
13838                        // we need to do is clear this user's data and save that
13839                        // it is uninstalled.
13840                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13841                        removeUser = user.getIdentifier();
13842                        appId = ps.appId;
13843                        scheduleWritePackageRestrictionsLocked(removeUser);
13844                    } else {
13845                        // We need to set it back to 'installed' so the uninstall
13846                        // broadcasts will be sent correctly.
13847                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13848                        ps.setInstalled(true, user.getIdentifier());
13849                    }
13850                } else {
13851                    // This is a system app, so we assume that the
13852                    // other users still have this package installed, so all
13853                    // we need to do is clear this user's data and save that
13854                    // it is uninstalled.
13855                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13856                    removeUser = user.getIdentifier();
13857                    appId = ps.appId;
13858                    scheduleWritePackageRestrictionsLocked(removeUser);
13859                }
13860            }
13861        }
13862
13863        if (removeUser >= 0) {
13864            // From above, we determined that we are deleting this only
13865            // for a single user.  Continue the work here.
13866            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13867            if (outInfo != null) {
13868                outInfo.removedPackage = packageName;
13869                outInfo.removedAppId = appId;
13870                outInfo.removedUsers = new int[] {removeUser};
13871            }
13872            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13873            removeKeystoreDataIfNeeded(removeUser, appId);
13874            schedulePackageCleaning(packageName, removeUser, false);
13875            synchronized (mPackages) {
13876                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13877                    scheduleWritePackageRestrictionsLocked(removeUser);
13878                }
13879                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13880            }
13881            return true;
13882        }
13883
13884        if (dataOnly) {
13885            // Delete application data first
13886            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13887            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13888            return true;
13889        }
13890
13891        boolean ret = false;
13892        if (isSystemApp(ps)) {
13893            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13894            // When an updated system application is deleted we delete the existing resources as well and
13895            // fall back to existing code in system partition
13896            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13897                    flags, outInfo, writeSettings);
13898        } else {
13899            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13900            // Kill application pre-emptively especially for apps on sd.
13901            killApplication(packageName, ps.appId, "uninstall pkg");
13902            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13903                    allUserHandles, perUserInstalled,
13904                    outInfo, writeSettings);
13905        }
13906
13907        return ret;
13908    }
13909
13910    private final static class ClearStorageConnection implements ServiceConnection {
13911        IMediaContainerService mContainerService;
13912
13913        @Override
13914        public void onServiceConnected(ComponentName name, IBinder service) {
13915            synchronized (this) {
13916                mContainerService = IMediaContainerService.Stub.asInterface(service);
13917                notifyAll();
13918            }
13919        }
13920
13921        @Override
13922        public void onServiceDisconnected(ComponentName name) {
13923        }
13924    }
13925
13926    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13927        final boolean mounted;
13928        if (Environment.isExternalStorageEmulated()) {
13929            mounted = true;
13930        } else {
13931            final String status = Environment.getExternalStorageState();
13932
13933            mounted = status.equals(Environment.MEDIA_MOUNTED)
13934                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13935        }
13936
13937        if (!mounted) {
13938            return;
13939        }
13940
13941        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13942        int[] users;
13943        if (userId == UserHandle.USER_ALL) {
13944            users = sUserManager.getUserIds();
13945        } else {
13946            users = new int[] { userId };
13947        }
13948        final ClearStorageConnection conn = new ClearStorageConnection();
13949        if (mContext.bindServiceAsUser(
13950                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13951            try {
13952                for (int curUser : users) {
13953                    long timeout = SystemClock.uptimeMillis() + 5000;
13954                    synchronized (conn) {
13955                        long now = SystemClock.uptimeMillis();
13956                        while (conn.mContainerService == null && now < timeout) {
13957                            try {
13958                                conn.wait(timeout - now);
13959                            } catch (InterruptedException e) {
13960                            }
13961                        }
13962                    }
13963                    if (conn.mContainerService == null) {
13964                        return;
13965                    }
13966
13967                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13968                    clearDirectory(conn.mContainerService,
13969                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13970                    if (allData) {
13971                        clearDirectory(conn.mContainerService,
13972                                userEnv.buildExternalStorageAppDataDirs(packageName));
13973                        clearDirectory(conn.mContainerService,
13974                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13975                    }
13976                }
13977            } finally {
13978                mContext.unbindService(conn);
13979            }
13980        }
13981    }
13982
13983    @Override
13984    public void clearApplicationUserData(final String packageName,
13985            final IPackageDataObserver observer, final int userId) {
13986        mContext.enforceCallingOrSelfPermission(
13987                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13988        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13989        // Queue up an async operation since the package deletion may take a little while.
13990        mHandler.post(new Runnable() {
13991            public void run() {
13992                mHandler.removeCallbacks(this);
13993                final boolean succeeded;
13994                synchronized (mInstallLock) {
13995                    succeeded = clearApplicationUserDataLI(packageName, userId);
13996                }
13997                clearExternalStorageDataSync(packageName, userId, true);
13998                if (succeeded) {
13999                    // invoke DeviceStorageMonitor's update method to clear any notifications
14000                    DeviceStorageMonitorInternal
14001                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14002                    if (dsm != null) {
14003                        dsm.checkMemory();
14004                    }
14005                }
14006                if(observer != null) {
14007                    try {
14008                        observer.onRemoveCompleted(packageName, succeeded);
14009                    } catch (RemoteException e) {
14010                        Log.i(TAG, "Observer no longer exists.");
14011                    }
14012                } //end if observer
14013            } //end run
14014        });
14015    }
14016
14017    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14018        if (packageName == null) {
14019            Slog.w(TAG, "Attempt to delete null packageName.");
14020            return false;
14021        }
14022
14023        // Try finding details about the requested package
14024        PackageParser.Package pkg;
14025        synchronized (mPackages) {
14026            pkg = mPackages.get(packageName);
14027            if (pkg == null) {
14028                final PackageSetting ps = mSettings.mPackages.get(packageName);
14029                if (ps != null) {
14030                    pkg = ps.pkg;
14031                }
14032            }
14033
14034            if (pkg == null) {
14035                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14036                return false;
14037            }
14038
14039            PackageSetting ps = (PackageSetting) pkg.mExtras;
14040            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14041        }
14042
14043        // Always delete data directories for package, even if we found no other
14044        // record of app. This helps users recover from UID mismatches without
14045        // resorting to a full data wipe.
14046        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14047        if (retCode < 0) {
14048            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
14049            return false;
14050        }
14051
14052        final int appId = pkg.applicationInfo.uid;
14053        removeKeystoreDataIfNeeded(userId, appId);
14054
14055        // Create a native library symlink only if we have native libraries
14056        // and if the native libraries are 32 bit libraries. We do not provide
14057        // this symlink for 64 bit libraries.
14058        if (pkg.applicationInfo.primaryCpuAbi != null &&
14059                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14060            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14061            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14062                    nativeLibPath, userId) < 0) {
14063                Slog.w(TAG, "Failed linking native library dir");
14064                return false;
14065            }
14066        }
14067
14068        return true;
14069    }
14070
14071    /**
14072     * Reverts user permission state changes (permissions and flags) in
14073     * all packages for a given user.
14074     *
14075     * @param userId The device user for which to do a reset.
14076     */
14077    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14078        final int packageCount = mPackages.size();
14079        for (int i = 0; i < packageCount; i++) {
14080            PackageParser.Package pkg = mPackages.valueAt(i);
14081            PackageSetting ps = (PackageSetting) pkg.mExtras;
14082            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14083        }
14084    }
14085
14086    /**
14087     * Reverts user permission state changes (permissions and flags).
14088     *
14089     * @param ps The package for which to reset.
14090     * @param userId The device user for which to do a reset.
14091     */
14092    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14093            final PackageSetting ps, final int userId) {
14094        if (ps.pkg == null) {
14095            return;
14096        }
14097
14098        // These are flags that can change base on user actions.
14099        final int userSettableMask = FLAG_PERMISSION_USER_SET
14100                | FLAG_PERMISSION_USER_FIXED
14101                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14102                | FLAG_PERMISSION_REVIEW_REQUIRED;
14103
14104        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14105                | FLAG_PERMISSION_POLICY_FIXED;
14106
14107        boolean writeInstallPermissions = false;
14108        boolean writeRuntimePermissions = false;
14109
14110        final int permissionCount = ps.pkg.requestedPermissions.size();
14111        for (int i = 0; i < permissionCount; i++) {
14112            String permission = ps.pkg.requestedPermissions.get(i);
14113
14114            BasePermission bp = mSettings.mPermissions.get(permission);
14115            if (bp == null) {
14116                continue;
14117            }
14118
14119            // If shared user we just reset the state to which only this app contributed.
14120            if (ps.sharedUser != null) {
14121                boolean used = false;
14122                final int packageCount = ps.sharedUser.packages.size();
14123                for (int j = 0; j < packageCount; j++) {
14124                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14125                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14126                            && pkg.pkg.requestedPermissions.contains(permission)) {
14127                        used = true;
14128                        break;
14129                    }
14130                }
14131                if (used) {
14132                    continue;
14133                }
14134            }
14135
14136            PermissionsState permissionsState = ps.getPermissionsState();
14137
14138            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14139
14140            // Always clear the user settable flags.
14141            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14142                    bp.name) != null;
14143            // If permission review is enabled and this is a legacy app, mark the
14144            // permission as requiring a review as this is the initial state.
14145            int flags = 0;
14146            if (Build.PERMISSIONS_REVIEW_REQUIRED
14147                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14148                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14149            }
14150            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14151                if (hasInstallState) {
14152                    writeInstallPermissions = true;
14153                } else {
14154                    writeRuntimePermissions = true;
14155                }
14156            }
14157
14158            // Below is only runtime permission handling.
14159            if (!bp.isRuntime()) {
14160                continue;
14161            }
14162
14163            // Never clobber system or policy.
14164            if ((oldFlags & policyOrSystemFlags) != 0) {
14165                continue;
14166            }
14167
14168            // If this permission was granted by default, make sure it is.
14169            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14170                if (permissionsState.grantRuntimePermission(bp, userId)
14171                        != PERMISSION_OPERATION_FAILURE) {
14172                    writeRuntimePermissions = true;
14173                }
14174            // If permission review is enabled the permissions for a legacy apps
14175            // are represented as constantly granted runtime ones, so don't revoke.
14176            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14177                // Otherwise, reset the permission.
14178                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14179                switch (revokeResult) {
14180                    case PERMISSION_OPERATION_SUCCESS: {
14181                        writeRuntimePermissions = true;
14182                    } break;
14183
14184                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14185                        writeRuntimePermissions = true;
14186                        final int appId = ps.appId;
14187                        mHandler.post(new Runnable() {
14188                            @Override
14189                            public void run() {
14190                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14191                            }
14192                        });
14193                    } break;
14194                }
14195            }
14196        }
14197
14198        // Synchronously write as we are taking permissions away.
14199        if (writeRuntimePermissions) {
14200            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14201        }
14202
14203        // Synchronously write as we are taking permissions away.
14204        if (writeInstallPermissions) {
14205            mSettings.writeLPr();
14206        }
14207    }
14208
14209    /**
14210     * Remove entries from the keystore daemon. Will only remove it if the
14211     * {@code appId} is valid.
14212     */
14213    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14214        if (appId < 0) {
14215            return;
14216        }
14217
14218        final KeyStore keyStore = KeyStore.getInstance();
14219        if (keyStore != null) {
14220            if (userId == UserHandle.USER_ALL) {
14221                for (final int individual : sUserManager.getUserIds()) {
14222                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14223                }
14224            } else {
14225                keyStore.clearUid(UserHandle.getUid(userId, appId));
14226            }
14227        } else {
14228            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14229        }
14230    }
14231
14232    @Override
14233    public void deleteApplicationCacheFiles(final String packageName,
14234            final IPackageDataObserver observer) {
14235        mContext.enforceCallingOrSelfPermission(
14236                android.Manifest.permission.DELETE_CACHE_FILES, null);
14237        // Queue up an async operation since the package deletion may take a little while.
14238        final int userId = UserHandle.getCallingUserId();
14239        mHandler.post(new Runnable() {
14240            public void run() {
14241                mHandler.removeCallbacks(this);
14242                final boolean succeded;
14243                synchronized (mInstallLock) {
14244                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14245                }
14246                clearExternalStorageDataSync(packageName, userId, false);
14247                if (observer != null) {
14248                    try {
14249                        observer.onRemoveCompleted(packageName, succeded);
14250                    } catch (RemoteException e) {
14251                        Log.i(TAG, "Observer no longer exists.");
14252                    }
14253                } //end if observer
14254            } //end run
14255        });
14256    }
14257
14258    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14259        if (packageName == null) {
14260            Slog.w(TAG, "Attempt to delete null packageName.");
14261            return false;
14262        }
14263        PackageParser.Package p;
14264        synchronized (mPackages) {
14265            p = mPackages.get(packageName);
14266        }
14267        if (p == null) {
14268            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14269            return false;
14270        }
14271        final ApplicationInfo applicationInfo = p.applicationInfo;
14272        if (applicationInfo == null) {
14273            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14274            return false;
14275        }
14276        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14277        if (retCode < 0) {
14278            Slog.w(TAG, "Couldn't remove cache files for package: "
14279                       + packageName + " u" + userId);
14280            return false;
14281        }
14282        return true;
14283    }
14284
14285    @Override
14286    public void getPackageSizeInfo(final String packageName, int userHandle,
14287            final IPackageStatsObserver observer) {
14288        mContext.enforceCallingOrSelfPermission(
14289                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14290        if (packageName == null) {
14291            throw new IllegalArgumentException("Attempt to get size of null packageName");
14292        }
14293
14294        PackageStats stats = new PackageStats(packageName, userHandle);
14295
14296        /*
14297         * Queue up an async operation since the package measurement may take a
14298         * little while.
14299         */
14300        Message msg = mHandler.obtainMessage(INIT_COPY);
14301        msg.obj = new MeasureParams(stats, observer);
14302        mHandler.sendMessage(msg);
14303    }
14304
14305    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14306            PackageStats pStats) {
14307        if (packageName == null) {
14308            Slog.w(TAG, "Attempt to get size of null packageName.");
14309            return false;
14310        }
14311        PackageParser.Package p;
14312        boolean dataOnly = false;
14313        String libDirRoot = null;
14314        String asecPath = null;
14315        PackageSetting ps = null;
14316        synchronized (mPackages) {
14317            p = mPackages.get(packageName);
14318            ps = mSettings.mPackages.get(packageName);
14319            if(p == null) {
14320                dataOnly = true;
14321                if((ps == null) || (ps.pkg == null)) {
14322                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14323                    return false;
14324                }
14325                p = ps.pkg;
14326            }
14327            if (ps != null) {
14328                libDirRoot = ps.legacyNativeLibraryPathString;
14329            }
14330            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14331                final long token = Binder.clearCallingIdentity();
14332                try {
14333                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14334                    if (secureContainerId != null) {
14335                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14336                    }
14337                } finally {
14338                    Binder.restoreCallingIdentity(token);
14339                }
14340            }
14341        }
14342        String publicSrcDir = null;
14343        if(!dataOnly) {
14344            final ApplicationInfo applicationInfo = p.applicationInfo;
14345            if (applicationInfo == null) {
14346                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14347                return false;
14348            }
14349            if (p.isForwardLocked()) {
14350                publicSrcDir = applicationInfo.getBaseResourcePath();
14351            }
14352        }
14353        // TODO: extend to measure size of split APKs
14354        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14355        // not just the first level.
14356        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14357        // just the primary.
14358        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14359
14360        String apkPath;
14361        File packageDir = new File(p.codePath);
14362
14363        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14364            apkPath = packageDir.getAbsolutePath();
14365            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14366            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14367                libDirRoot = null;
14368            }
14369        } else {
14370            apkPath = p.baseCodePath;
14371        }
14372
14373        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14374                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14375        if (res < 0) {
14376            return false;
14377        }
14378
14379        // Fix-up for forward-locked applications in ASEC containers.
14380        if (!isExternal(p)) {
14381            pStats.codeSize += pStats.externalCodeSize;
14382            pStats.externalCodeSize = 0L;
14383        }
14384
14385        return true;
14386    }
14387
14388
14389    @Override
14390    public void addPackageToPreferred(String packageName) {
14391        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14392    }
14393
14394    @Override
14395    public void removePackageFromPreferred(String packageName) {
14396        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14397    }
14398
14399    @Override
14400    public List<PackageInfo> getPreferredPackages(int flags) {
14401        return new ArrayList<PackageInfo>();
14402    }
14403
14404    private int getUidTargetSdkVersionLockedLPr(int uid) {
14405        Object obj = mSettings.getUserIdLPr(uid);
14406        if (obj instanceof SharedUserSetting) {
14407            final SharedUserSetting sus = (SharedUserSetting) obj;
14408            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14409            final Iterator<PackageSetting> it = sus.packages.iterator();
14410            while (it.hasNext()) {
14411                final PackageSetting ps = it.next();
14412                if (ps.pkg != null) {
14413                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14414                    if (v < vers) vers = v;
14415                }
14416            }
14417            return vers;
14418        } else if (obj instanceof PackageSetting) {
14419            final PackageSetting ps = (PackageSetting) obj;
14420            if (ps.pkg != null) {
14421                return ps.pkg.applicationInfo.targetSdkVersion;
14422            }
14423        }
14424        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14425    }
14426
14427    @Override
14428    public void addPreferredActivity(IntentFilter filter, int match,
14429            ComponentName[] set, ComponentName activity, int userId) {
14430        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14431                "Adding preferred");
14432    }
14433
14434    private void addPreferredActivityInternal(IntentFilter filter, int match,
14435            ComponentName[] set, ComponentName activity, boolean always, int userId,
14436            String opname) {
14437        // writer
14438        int callingUid = Binder.getCallingUid();
14439        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14440        if (filter.countActions() == 0) {
14441            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14442            return;
14443        }
14444        synchronized (mPackages) {
14445            if (mContext.checkCallingOrSelfPermission(
14446                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14447                    != PackageManager.PERMISSION_GRANTED) {
14448                if (getUidTargetSdkVersionLockedLPr(callingUid)
14449                        < Build.VERSION_CODES.FROYO) {
14450                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14451                            + callingUid);
14452                    return;
14453                }
14454                mContext.enforceCallingOrSelfPermission(
14455                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14456            }
14457
14458            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14459            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14460                    + userId + ":");
14461            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14462            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14463            scheduleWritePackageRestrictionsLocked(userId);
14464        }
14465    }
14466
14467    @Override
14468    public void replacePreferredActivity(IntentFilter filter, int match,
14469            ComponentName[] set, ComponentName activity, int userId) {
14470        if (filter.countActions() != 1) {
14471            throw new IllegalArgumentException(
14472                    "replacePreferredActivity expects filter to have only 1 action.");
14473        }
14474        if (filter.countDataAuthorities() != 0
14475                || filter.countDataPaths() != 0
14476                || filter.countDataSchemes() > 1
14477                || filter.countDataTypes() != 0) {
14478            throw new IllegalArgumentException(
14479                    "replacePreferredActivity expects filter to have no data authorities, " +
14480                    "paths, or types; and at most one scheme.");
14481        }
14482
14483        final int callingUid = Binder.getCallingUid();
14484        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14485        synchronized (mPackages) {
14486            if (mContext.checkCallingOrSelfPermission(
14487                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14488                    != PackageManager.PERMISSION_GRANTED) {
14489                if (getUidTargetSdkVersionLockedLPr(callingUid)
14490                        < Build.VERSION_CODES.FROYO) {
14491                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14492                            + Binder.getCallingUid());
14493                    return;
14494                }
14495                mContext.enforceCallingOrSelfPermission(
14496                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14497            }
14498
14499            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14500            if (pir != null) {
14501                // Get all of the existing entries that exactly match this filter.
14502                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14503                if (existing != null && existing.size() == 1) {
14504                    PreferredActivity cur = existing.get(0);
14505                    if (DEBUG_PREFERRED) {
14506                        Slog.i(TAG, "Checking replace of preferred:");
14507                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14508                        if (!cur.mPref.mAlways) {
14509                            Slog.i(TAG, "  -- CUR; not mAlways!");
14510                        } else {
14511                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14512                            Slog.i(TAG, "  -- CUR: mSet="
14513                                    + Arrays.toString(cur.mPref.mSetComponents));
14514                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14515                            Slog.i(TAG, "  -- NEW: mMatch="
14516                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14517                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14518                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14519                        }
14520                    }
14521                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14522                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14523                            && cur.mPref.sameSet(set)) {
14524                        // Setting the preferred activity to what it happens to be already
14525                        if (DEBUG_PREFERRED) {
14526                            Slog.i(TAG, "Replacing with same preferred activity "
14527                                    + cur.mPref.mShortComponent + " for user "
14528                                    + userId + ":");
14529                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14530                        }
14531                        return;
14532                    }
14533                }
14534
14535                if (existing != null) {
14536                    if (DEBUG_PREFERRED) {
14537                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14538                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14539                    }
14540                    for (int i = 0; i < existing.size(); i++) {
14541                        PreferredActivity pa = existing.get(i);
14542                        if (DEBUG_PREFERRED) {
14543                            Slog.i(TAG, "Removing existing preferred activity "
14544                                    + pa.mPref.mComponent + ":");
14545                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14546                        }
14547                        pir.removeFilter(pa);
14548                    }
14549                }
14550            }
14551            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14552                    "Replacing preferred");
14553        }
14554    }
14555
14556    @Override
14557    public void clearPackagePreferredActivities(String packageName) {
14558        final int uid = Binder.getCallingUid();
14559        // writer
14560        synchronized (mPackages) {
14561            PackageParser.Package pkg = mPackages.get(packageName);
14562            if (pkg == null || pkg.applicationInfo.uid != uid) {
14563                if (mContext.checkCallingOrSelfPermission(
14564                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14565                        != PackageManager.PERMISSION_GRANTED) {
14566                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14567                            < Build.VERSION_CODES.FROYO) {
14568                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14569                                + Binder.getCallingUid());
14570                        return;
14571                    }
14572                    mContext.enforceCallingOrSelfPermission(
14573                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14574                }
14575            }
14576
14577            int user = UserHandle.getCallingUserId();
14578            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14579                scheduleWritePackageRestrictionsLocked(user);
14580            }
14581        }
14582    }
14583
14584    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14585    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14586        ArrayList<PreferredActivity> removed = null;
14587        boolean changed = false;
14588        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14589            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14590            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14591            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14592                continue;
14593            }
14594            Iterator<PreferredActivity> it = pir.filterIterator();
14595            while (it.hasNext()) {
14596                PreferredActivity pa = it.next();
14597                // Mark entry for removal only if it matches the package name
14598                // and the entry is of type "always".
14599                if (packageName == null ||
14600                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14601                                && pa.mPref.mAlways)) {
14602                    if (removed == null) {
14603                        removed = new ArrayList<PreferredActivity>();
14604                    }
14605                    removed.add(pa);
14606                }
14607            }
14608            if (removed != null) {
14609                for (int j=0; j<removed.size(); j++) {
14610                    PreferredActivity pa = removed.get(j);
14611                    pir.removeFilter(pa);
14612                }
14613                changed = true;
14614            }
14615        }
14616        return changed;
14617    }
14618
14619    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14620    private void clearIntentFilterVerificationsLPw(int userId) {
14621        final int packageCount = mPackages.size();
14622        for (int i = 0; i < packageCount; i++) {
14623            PackageParser.Package pkg = mPackages.valueAt(i);
14624            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14625        }
14626    }
14627
14628    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14629    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14630        if (userId == UserHandle.USER_ALL) {
14631            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14632                    sUserManager.getUserIds())) {
14633                for (int oneUserId : sUserManager.getUserIds()) {
14634                    scheduleWritePackageRestrictionsLocked(oneUserId);
14635                }
14636            }
14637        } else {
14638            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14639                scheduleWritePackageRestrictionsLocked(userId);
14640            }
14641        }
14642    }
14643
14644    void clearDefaultBrowserIfNeeded(String packageName) {
14645        for (int oneUserId : sUserManager.getUserIds()) {
14646            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14647            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14648            if (packageName.equals(defaultBrowserPackageName)) {
14649                setDefaultBrowserPackageName(null, oneUserId);
14650            }
14651        }
14652    }
14653
14654    @Override
14655    public void resetApplicationPreferences(int userId) {
14656        mContext.enforceCallingOrSelfPermission(
14657                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14658        // writer
14659        synchronized (mPackages) {
14660            final long identity = Binder.clearCallingIdentity();
14661            try {
14662                clearPackagePreferredActivitiesLPw(null, userId);
14663                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14664                // TODO: We have to reset the default SMS and Phone. This requires
14665                // significant refactoring to keep all default apps in the package
14666                // manager (cleaner but more work) or have the services provide
14667                // callbacks to the package manager to request a default app reset.
14668                applyFactoryDefaultBrowserLPw(userId);
14669                clearIntentFilterVerificationsLPw(userId);
14670                primeDomainVerificationsLPw(userId);
14671                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14672                scheduleWritePackageRestrictionsLocked(userId);
14673            } finally {
14674                Binder.restoreCallingIdentity(identity);
14675            }
14676        }
14677    }
14678
14679    @Override
14680    public int getPreferredActivities(List<IntentFilter> outFilters,
14681            List<ComponentName> outActivities, String packageName) {
14682
14683        int num = 0;
14684        final int userId = UserHandle.getCallingUserId();
14685        // reader
14686        synchronized (mPackages) {
14687            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14688            if (pir != null) {
14689                final Iterator<PreferredActivity> it = pir.filterIterator();
14690                while (it.hasNext()) {
14691                    final PreferredActivity pa = it.next();
14692                    if (packageName == null
14693                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14694                                    && pa.mPref.mAlways)) {
14695                        if (outFilters != null) {
14696                            outFilters.add(new IntentFilter(pa));
14697                        }
14698                        if (outActivities != null) {
14699                            outActivities.add(pa.mPref.mComponent);
14700                        }
14701                    }
14702                }
14703            }
14704        }
14705
14706        return num;
14707    }
14708
14709    @Override
14710    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14711            int userId) {
14712        int callingUid = Binder.getCallingUid();
14713        if (callingUid != Process.SYSTEM_UID) {
14714            throw new SecurityException(
14715                    "addPersistentPreferredActivity can only be run by the system");
14716        }
14717        if (filter.countActions() == 0) {
14718            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14719            return;
14720        }
14721        synchronized (mPackages) {
14722            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14723                    " :");
14724            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14725            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14726                    new PersistentPreferredActivity(filter, activity));
14727            scheduleWritePackageRestrictionsLocked(userId);
14728        }
14729    }
14730
14731    @Override
14732    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14733        int callingUid = Binder.getCallingUid();
14734        if (callingUid != Process.SYSTEM_UID) {
14735            throw new SecurityException(
14736                    "clearPackagePersistentPreferredActivities can only be run by the system");
14737        }
14738        ArrayList<PersistentPreferredActivity> removed = null;
14739        boolean changed = false;
14740        synchronized (mPackages) {
14741            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14742                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14743                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14744                        .valueAt(i);
14745                if (userId != thisUserId) {
14746                    continue;
14747                }
14748                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14749                while (it.hasNext()) {
14750                    PersistentPreferredActivity ppa = it.next();
14751                    // Mark entry for removal only if it matches the package name.
14752                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14753                        if (removed == null) {
14754                            removed = new ArrayList<PersistentPreferredActivity>();
14755                        }
14756                        removed.add(ppa);
14757                    }
14758                }
14759                if (removed != null) {
14760                    for (int j=0; j<removed.size(); j++) {
14761                        PersistentPreferredActivity ppa = removed.get(j);
14762                        ppir.removeFilter(ppa);
14763                    }
14764                    changed = true;
14765                }
14766            }
14767
14768            if (changed) {
14769                scheduleWritePackageRestrictionsLocked(userId);
14770            }
14771        }
14772    }
14773
14774    /**
14775     * Common machinery for picking apart a restored XML blob and passing
14776     * it to a caller-supplied functor to be applied to the running system.
14777     */
14778    private void restoreFromXml(XmlPullParser parser, int userId,
14779            String expectedStartTag, BlobXmlRestorer functor)
14780            throws IOException, XmlPullParserException {
14781        int type;
14782        while ((type = parser.next()) != XmlPullParser.START_TAG
14783                && type != XmlPullParser.END_DOCUMENT) {
14784        }
14785        if (type != XmlPullParser.START_TAG) {
14786            // oops didn't find a start tag?!
14787            if (DEBUG_BACKUP) {
14788                Slog.e(TAG, "Didn't find start tag during restore");
14789            }
14790            return;
14791        }
14792
14793        // this is supposed to be TAG_PREFERRED_BACKUP
14794        if (!expectedStartTag.equals(parser.getName())) {
14795            if (DEBUG_BACKUP) {
14796                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14797            }
14798            return;
14799        }
14800
14801        // skip interfering stuff, then we're aligned with the backing implementation
14802        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14803        functor.apply(parser, userId);
14804    }
14805
14806    private interface BlobXmlRestorer {
14807        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14808    }
14809
14810    /**
14811     * Non-Binder method, support for the backup/restore mechanism: write the
14812     * full set of preferred activities in its canonical XML format.  Returns the
14813     * XML output as a byte array, or null if there is none.
14814     */
14815    @Override
14816    public byte[] getPreferredActivityBackup(int userId) {
14817        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14818            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14819        }
14820
14821        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14822        try {
14823            final XmlSerializer serializer = new FastXmlSerializer();
14824            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14825            serializer.startDocument(null, true);
14826            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14827
14828            synchronized (mPackages) {
14829                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14830            }
14831
14832            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14833            serializer.endDocument();
14834            serializer.flush();
14835        } catch (Exception e) {
14836            if (DEBUG_BACKUP) {
14837                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14838            }
14839            return null;
14840        }
14841
14842        return dataStream.toByteArray();
14843    }
14844
14845    @Override
14846    public void restorePreferredActivities(byte[] backup, int userId) {
14847        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14848            throw new SecurityException("Only the system may call restorePreferredActivities()");
14849        }
14850
14851        try {
14852            final XmlPullParser parser = Xml.newPullParser();
14853            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14854            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14855                    new BlobXmlRestorer() {
14856                        @Override
14857                        public void apply(XmlPullParser parser, int userId)
14858                                throws XmlPullParserException, IOException {
14859                            synchronized (mPackages) {
14860                                mSettings.readPreferredActivitiesLPw(parser, userId);
14861                            }
14862                        }
14863                    } );
14864        } catch (Exception e) {
14865            if (DEBUG_BACKUP) {
14866                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14867            }
14868        }
14869    }
14870
14871    /**
14872     * Non-Binder method, support for the backup/restore mechanism: write the
14873     * default browser (etc) settings in its canonical XML format.  Returns the default
14874     * browser XML representation as a byte array, or null if there is none.
14875     */
14876    @Override
14877    public byte[] getDefaultAppsBackup(int userId) {
14878        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14879            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14880        }
14881
14882        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14883        try {
14884            final XmlSerializer serializer = new FastXmlSerializer();
14885            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14886            serializer.startDocument(null, true);
14887            serializer.startTag(null, TAG_DEFAULT_APPS);
14888
14889            synchronized (mPackages) {
14890                mSettings.writeDefaultAppsLPr(serializer, userId);
14891            }
14892
14893            serializer.endTag(null, TAG_DEFAULT_APPS);
14894            serializer.endDocument();
14895            serializer.flush();
14896        } catch (Exception e) {
14897            if (DEBUG_BACKUP) {
14898                Slog.e(TAG, "Unable to write default apps for backup", e);
14899            }
14900            return null;
14901        }
14902
14903        return dataStream.toByteArray();
14904    }
14905
14906    @Override
14907    public void restoreDefaultApps(byte[] backup, int userId) {
14908        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14909            throw new SecurityException("Only the system may call restoreDefaultApps()");
14910        }
14911
14912        try {
14913            final XmlPullParser parser = Xml.newPullParser();
14914            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14915            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14916                    new BlobXmlRestorer() {
14917                        @Override
14918                        public void apply(XmlPullParser parser, int userId)
14919                                throws XmlPullParserException, IOException {
14920                            synchronized (mPackages) {
14921                                mSettings.readDefaultAppsLPw(parser, userId);
14922                            }
14923                        }
14924                    } );
14925        } catch (Exception e) {
14926            if (DEBUG_BACKUP) {
14927                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14928            }
14929        }
14930    }
14931
14932    @Override
14933    public byte[] getIntentFilterVerificationBackup(int userId) {
14934        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14935            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14936        }
14937
14938        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14939        try {
14940            final XmlSerializer serializer = new FastXmlSerializer();
14941            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14942            serializer.startDocument(null, true);
14943            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14944
14945            synchronized (mPackages) {
14946                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14947            }
14948
14949            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14950            serializer.endDocument();
14951            serializer.flush();
14952        } catch (Exception e) {
14953            if (DEBUG_BACKUP) {
14954                Slog.e(TAG, "Unable to write default apps for backup", e);
14955            }
14956            return null;
14957        }
14958
14959        return dataStream.toByteArray();
14960    }
14961
14962    @Override
14963    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14964        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14965            throw new SecurityException("Only the system may call restorePreferredActivities()");
14966        }
14967
14968        try {
14969            final XmlPullParser parser = Xml.newPullParser();
14970            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14971            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14972                    new BlobXmlRestorer() {
14973                        @Override
14974                        public void apply(XmlPullParser parser, int userId)
14975                                throws XmlPullParserException, IOException {
14976                            synchronized (mPackages) {
14977                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14978                                mSettings.writeLPr();
14979                            }
14980                        }
14981                    } );
14982        } catch (Exception e) {
14983            if (DEBUG_BACKUP) {
14984                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14985            }
14986        }
14987    }
14988
14989    @Override
14990    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14991            int sourceUserId, int targetUserId, int flags) {
14992        mContext.enforceCallingOrSelfPermission(
14993                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14994        int callingUid = Binder.getCallingUid();
14995        enforceOwnerRights(ownerPackage, callingUid);
14996        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14997        if (intentFilter.countActions() == 0) {
14998            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14999            return;
15000        }
15001        synchronized (mPackages) {
15002            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15003                    ownerPackage, targetUserId, flags);
15004            CrossProfileIntentResolver resolver =
15005                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15006            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15007            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15008            if (existing != null) {
15009                int size = existing.size();
15010                for (int i = 0; i < size; i++) {
15011                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15012                        return;
15013                    }
15014                }
15015            }
15016            resolver.addFilter(newFilter);
15017            scheduleWritePackageRestrictionsLocked(sourceUserId);
15018        }
15019    }
15020
15021    @Override
15022    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15023        mContext.enforceCallingOrSelfPermission(
15024                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15025        int callingUid = Binder.getCallingUid();
15026        enforceOwnerRights(ownerPackage, callingUid);
15027        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15028        synchronized (mPackages) {
15029            CrossProfileIntentResolver resolver =
15030                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15031            ArraySet<CrossProfileIntentFilter> set =
15032                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15033            for (CrossProfileIntentFilter filter : set) {
15034                if (filter.getOwnerPackage().equals(ownerPackage)) {
15035                    resolver.removeFilter(filter);
15036                }
15037            }
15038            scheduleWritePackageRestrictionsLocked(sourceUserId);
15039        }
15040    }
15041
15042    // Enforcing that callingUid is owning pkg on userId
15043    private void enforceOwnerRights(String pkg, int callingUid) {
15044        // The system owns everything.
15045        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15046            return;
15047        }
15048        int callingUserId = UserHandle.getUserId(callingUid);
15049        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15050        if (pi == null) {
15051            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15052                    + callingUserId);
15053        }
15054        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15055            throw new SecurityException("Calling uid " + callingUid
15056                    + " does not own package " + pkg);
15057        }
15058    }
15059
15060    @Override
15061    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15062        Intent intent = new Intent(Intent.ACTION_MAIN);
15063        intent.addCategory(Intent.CATEGORY_HOME);
15064
15065        final int callingUserId = UserHandle.getCallingUserId();
15066        List<ResolveInfo> list = queryIntentActivities(intent, null,
15067                PackageManager.GET_META_DATA, callingUserId);
15068        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15069                true, false, false, callingUserId);
15070
15071        allHomeCandidates.clear();
15072        if (list != null) {
15073            for (ResolveInfo ri : list) {
15074                allHomeCandidates.add(ri);
15075            }
15076        }
15077        return (preferred == null || preferred.activityInfo == null)
15078                ? null
15079                : new ComponentName(preferred.activityInfo.packageName,
15080                        preferred.activityInfo.name);
15081    }
15082
15083    @Override
15084    public void setApplicationEnabledSetting(String appPackageName,
15085            int newState, int flags, int userId, String callingPackage) {
15086        if (!sUserManager.exists(userId)) return;
15087        if (callingPackage == null) {
15088            callingPackage = Integer.toString(Binder.getCallingUid());
15089        }
15090        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15091    }
15092
15093    @Override
15094    public void setComponentEnabledSetting(ComponentName componentName,
15095            int newState, int flags, int userId) {
15096        if (!sUserManager.exists(userId)) return;
15097        setEnabledSetting(componentName.getPackageName(),
15098                componentName.getClassName(), newState, flags, userId, null);
15099    }
15100
15101    private void setEnabledSetting(final String packageName, String className, int newState,
15102            final int flags, int userId, String callingPackage) {
15103        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15104              || newState == COMPONENT_ENABLED_STATE_ENABLED
15105              || newState == COMPONENT_ENABLED_STATE_DISABLED
15106              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15107              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15108            throw new IllegalArgumentException("Invalid new component state: "
15109                    + newState);
15110        }
15111        PackageSetting pkgSetting;
15112        final int uid = Binder.getCallingUid();
15113        final int permission = mContext.checkCallingOrSelfPermission(
15114                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15115        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15116        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15117        boolean sendNow = false;
15118        boolean isApp = (className == null);
15119        String componentName = isApp ? packageName : className;
15120        int packageUid = -1;
15121        ArrayList<String> components;
15122
15123        // writer
15124        synchronized (mPackages) {
15125            pkgSetting = mSettings.mPackages.get(packageName);
15126            if (pkgSetting == null) {
15127                if (className == null) {
15128                    throw new IllegalArgumentException(
15129                            "Unknown package: " + packageName);
15130                }
15131                throw new IllegalArgumentException(
15132                        "Unknown component: " + packageName
15133                        + "/" + className);
15134            }
15135            // Allow root and verify that userId is not being specified by a different user
15136            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15137                throw new SecurityException(
15138                        "Permission Denial: attempt to change component state from pid="
15139                        + Binder.getCallingPid()
15140                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15141            }
15142            if (className == null) {
15143                // We're dealing with an application/package level state change
15144                if (pkgSetting.getEnabled(userId) == newState) {
15145                    // Nothing to do
15146                    return;
15147                }
15148                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15149                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15150                    // Don't care about who enables an app.
15151                    callingPackage = null;
15152                }
15153                pkgSetting.setEnabled(newState, userId, callingPackage);
15154                // pkgSetting.pkg.mSetEnabled = newState;
15155            } else {
15156                // We're dealing with a component level state change
15157                // First, verify that this is a valid class name.
15158                PackageParser.Package pkg = pkgSetting.pkg;
15159                if (pkg == null || !pkg.hasComponentClassName(className)) {
15160                    if (pkg != null &&
15161                            pkg.applicationInfo.targetSdkVersion >=
15162                                    Build.VERSION_CODES.JELLY_BEAN) {
15163                        throw new IllegalArgumentException("Component class " + className
15164                                + " does not exist in " + packageName);
15165                    } else {
15166                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15167                                + className + " does not exist in " + packageName);
15168                    }
15169                }
15170                switch (newState) {
15171                case COMPONENT_ENABLED_STATE_ENABLED:
15172                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15173                        return;
15174                    }
15175                    break;
15176                case COMPONENT_ENABLED_STATE_DISABLED:
15177                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15178                        return;
15179                    }
15180                    break;
15181                case COMPONENT_ENABLED_STATE_DEFAULT:
15182                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15183                        return;
15184                    }
15185                    break;
15186                default:
15187                    Slog.e(TAG, "Invalid new component state: " + newState);
15188                    return;
15189                }
15190            }
15191            scheduleWritePackageRestrictionsLocked(userId);
15192            components = mPendingBroadcasts.get(userId, packageName);
15193            final boolean newPackage = components == null;
15194            if (newPackage) {
15195                components = new ArrayList<String>();
15196            }
15197            if (!components.contains(componentName)) {
15198                components.add(componentName);
15199            }
15200            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15201                sendNow = true;
15202                // Purge entry from pending broadcast list if another one exists already
15203                // since we are sending one right away.
15204                mPendingBroadcasts.remove(userId, packageName);
15205            } else {
15206                if (newPackage) {
15207                    mPendingBroadcasts.put(userId, packageName, components);
15208                }
15209                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15210                    // Schedule a message
15211                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15212                }
15213            }
15214        }
15215
15216        long callingId = Binder.clearCallingIdentity();
15217        try {
15218            if (sendNow) {
15219                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15220                sendPackageChangedBroadcast(packageName,
15221                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15222            }
15223        } finally {
15224            Binder.restoreCallingIdentity(callingId);
15225        }
15226    }
15227
15228    private void sendPackageChangedBroadcast(String packageName,
15229            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15230        if (DEBUG_INSTALL)
15231            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15232                    + componentNames);
15233        Bundle extras = new Bundle(4);
15234        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15235        String nameList[] = new String[componentNames.size()];
15236        componentNames.toArray(nameList);
15237        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15238        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15239        extras.putInt(Intent.EXTRA_UID, packageUid);
15240        // If this is not reporting a change of the overall package, then only send it
15241        // to registered receivers.  We don't want to launch a swath of apps for every
15242        // little component state change.
15243        final int flags = !componentNames.contains(packageName)
15244                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15245        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15246                new int[] {UserHandle.getUserId(packageUid)});
15247    }
15248
15249    @Override
15250    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15251        if (!sUserManager.exists(userId)) return;
15252        final int uid = Binder.getCallingUid();
15253        final int permission = mContext.checkCallingOrSelfPermission(
15254                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15255        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15256        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15257        // writer
15258        synchronized (mPackages) {
15259            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15260                    allowedByPermission, uid, userId)) {
15261                scheduleWritePackageRestrictionsLocked(userId);
15262            }
15263        }
15264    }
15265
15266    @Override
15267    public String getInstallerPackageName(String packageName) {
15268        // reader
15269        synchronized (mPackages) {
15270            return mSettings.getInstallerPackageNameLPr(packageName);
15271        }
15272    }
15273
15274    @Override
15275    public int getApplicationEnabledSetting(String packageName, int userId) {
15276        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15277        int uid = Binder.getCallingUid();
15278        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15279        // reader
15280        synchronized (mPackages) {
15281            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15282        }
15283    }
15284
15285    @Override
15286    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15287        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15288        int uid = Binder.getCallingUid();
15289        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15290        // reader
15291        synchronized (mPackages) {
15292            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15293        }
15294    }
15295
15296    @Override
15297    public void enterSafeMode() {
15298        enforceSystemOrRoot("Only the system can request entering safe mode");
15299
15300        if (!mSystemReady) {
15301            mSafeMode = true;
15302        }
15303    }
15304
15305    @Override
15306    public void systemReady() {
15307        mSystemReady = true;
15308
15309        // Read the compatibilty setting when the system is ready.
15310        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15311                mContext.getContentResolver(),
15312                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15313        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15314        if (DEBUG_SETTINGS) {
15315            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15316        }
15317
15318        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15319
15320        synchronized (mPackages) {
15321            // Verify that all of the preferred activity components actually
15322            // exist.  It is possible for applications to be updated and at
15323            // that point remove a previously declared activity component that
15324            // had been set as a preferred activity.  We try to clean this up
15325            // the next time we encounter that preferred activity, but it is
15326            // possible for the user flow to never be able to return to that
15327            // situation so here we do a sanity check to make sure we haven't
15328            // left any junk around.
15329            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15330            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15331                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15332                removed.clear();
15333                for (PreferredActivity pa : pir.filterSet()) {
15334                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15335                        removed.add(pa);
15336                    }
15337                }
15338                if (removed.size() > 0) {
15339                    for (int r=0; r<removed.size(); r++) {
15340                        PreferredActivity pa = removed.get(r);
15341                        Slog.w(TAG, "Removing dangling preferred activity: "
15342                                + pa.mPref.mComponent);
15343                        pir.removeFilter(pa);
15344                    }
15345                    mSettings.writePackageRestrictionsLPr(
15346                            mSettings.mPreferredActivities.keyAt(i));
15347                }
15348            }
15349
15350            for (int userId : UserManagerService.getInstance().getUserIds()) {
15351                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15352                    grantPermissionsUserIds = ArrayUtils.appendInt(
15353                            grantPermissionsUserIds, userId);
15354                }
15355            }
15356        }
15357        sUserManager.systemReady();
15358
15359        // If we upgraded grant all default permissions before kicking off.
15360        for (int userId : grantPermissionsUserIds) {
15361            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15362        }
15363
15364        // Kick off any messages waiting for system ready
15365        if (mPostSystemReadyMessages != null) {
15366            for (Message msg : mPostSystemReadyMessages) {
15367                msg.sendToTarget();
15368            }
15369            mPostSystemReadyMessages = null;
15370        }
15371
15372        // Watch for external volumes that come and go over time
15373        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15374        storage.registerListener(mStorageListener);
15375
15376        mInstallerService.systemReady();
15377        mPackageDexOptimizer.systemReady();
15378
15379        MountServiceInternal mountServiceInternal = LocalServices.getService(
15380                MountServiceInternal.class);
15381        mountServiceInternal.addExternalStoragePolicy(
15382                new MountServiceInternal.ExternalStorageMountPolicy() {
15383            @Override
15384            public int getMountMode(int uid, String packageName) {
15385                if (Process.isIsolated(uid)) {
15386                    return Zygote.MOUNT_EXTERNAL_NONE;
15387                }
15388                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15389                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15390                }
15391                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15392                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15393                }
15394                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15395                    return Zygote.MOUNT_EXTERNAL_READ;
15396                }
15397                return Zygote.MOUNT_EXTERNAL_WRITE;
15398            }
15399
15400            @Override
15401            public boolean hasExternalStorage(int uid, String packageName) {
15402                return true;
15403            }
15404        });
15405    }
15406
15407    @Override
15408    public boolean isSafeMode() {
15409        return mSafeMode;
15410    }
15411
15412    @Override
15413    public boolean hasSystemUidErrors() {
15414        return mHasSystemUidErrors;
15415    }
15416
15417    static String arrayToString(int[] array) {
15418        StringBuffer buf = new StringBuffer(128);
15419        buf.append('[');
15420        if (array != null) {
15421            for (int i=0; i<array.length; i++) {
15422                if (i > 0) buf.append(", ");
15423                buf.append(array[i]);
15424            }
15425        }
15426        buf.append(']');
15427        return buf.toString();
15428    }
15429
15430    static class DumpState {
15431        public static final int DUMP_LIBS = 1 << 0;
15432        public static final int DUMP_FEATURES = 1 << 1;
15433        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15434        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15435        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15436        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15437        public static final int DUMP_PERMISSIONS = 1 << 6;
15438        public static final int DUMP_PACKAGES = 1 << 7;
15439        public static final int DUMP_SHARED_USERS = 1 << 8;
15440        public static final int DUMP_MESSAGES = 1 << 9;
15441        public static final int DUMP_PROVIDERS = 1 << 10;
15442        public static final int DUMP_VERIFIERS = 1 << 11;
15443        public static final int DUMP_PREFERRED = 1 << 12;
15444        public static final int DUMP_PREFERRED_XML = 1 << 13;
15445        public static final int DUMP_KEYSETS = 1 << 14;
15446        public static final int DUMP_VERSION = 1 << 15;
15447        public static final int DUMP_INSTALLS = 1 << 16;
15448        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15449        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15450
15451        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15452
15453        private int mTypes;
15454
15455        private int mOptions;
15456
15457        private boolean mTitlePrinted;
15458
15459        private SharedUserSetting mSharedUser;
15460
15461        public boolean isDumping(int type) {
15462            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15463                return true;
15464            }
15465
15466            return (mTypes & type) != 0;
15467        }
15468
15469        public void setDump(int type) {
15470            mTypes |= type;
15471        }
15472
15473        public boolean isOptionEnabled(int option) {
15474            return (mOptions & option) != 0;
15475        }
15476
15477        public void setOptionEnabled(int option) {
15478            mOptions |= option;
15479        }
15480
15481        public boolean onTitlePrinted() {
15482            final boolean printed = mTitlePrinted;
15483            mTitlePrinted = true;
15484            return printed;
15485        }
15486
15487        public boolean getTitlePrinted() {
15488            return mTitlePrinted;
15489        }
15490
15491        public void setTitlePrinted(boolean enabled) {
15492            mTitlePrinted = enabled;
15493        }
15494
15495        public SharedUserSetting getSharedUser() {
15496            return mSharedUser;
15497        }
15498
15499        public void setSharedUser(SharedUserSetting user) {
15500            mSharedUser = user;
15501        }
15502    }
15503
15504    @Override
15505    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15506            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15507        (new PackageManagerShellCommand(this)).exec(
15508                this, in, out, err, args, resultReceiver);
15509    }
15510
15511    @Override
15512    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15513        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15514                != PackageManager.PERMISSION_GRANTED) {
15515            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15516                    + Binder.getCallingPid()
15517                    + ", uid=" + Binder.getCallingUid()
15518                    + " without permission "
15519                    + android.Manifest.permission.DUMP);
15520            return;
15521        }
15522
15523        DumpState dumpState = new DumpState();
15524        boolean fullPreferred = false;
15525        boolean checkin = false;
15526
15527        String packageName = null;
15528        ArraySet<String> permissionNames = null;
15529
15530        int opti = 0;
15531        while (opti < args.length) {
15532            String opt = args[opti];
15533            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15534                break;
15535            }
15536            opti++;
15537
15538            if ("-a".equals(opt)) {
15539                // Right now we only know how to print all.
15540            } else if ("-h".equals(opt)) {
15541                pw.println("Package manager dump options:");
15542                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15543                pw.println("    --checkin: dump for a checkin");
15544                pw.println("    -f: print details of intent filters");
15545                pw.println("    -h: print this help");
15546                pw.println("  cmd may be one of:");
15547                pw.println("    l[ibraries]: list known shared libraries");
15548                pw.println("    f[eatures]: list device features");
15549                pw.println("    k[eysets]: print known keysets");
15550                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15551                pw.println("    perm[issions]: dump permissions");
15552                pw.println("    permission [name ...]: dump declaration and use of given permission");
15553                pw.println("    pref[erred]: print preferred package settings");
15554                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15555                pw.println("    prov[iders]: dump content providers");
15556                pw.println("    p[ackages]: dump installed packages");
15557                pw.println("    s[hared-users]: dump shared user IDs");
15558                pw.println("    m[essages]: print collected runtime messages");
15559                pw.println("    v[erifiers]: print package verifier info");
15560                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15561                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15562                pw.println("    version: print database version info");
15563                pw.println("    write: write current settings now");
15564                pw.println("    installs: details about install sessions");
15565                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15566                pw.println("    <package.name>: info about given package");
15567                return;
15568            } else if ("--checkin".equals(opt)) {
15569                checkin = true;
15570            } else if ("-f".equals(opt)) {
15571                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15572            } else {
15573                pw.println("Unknown argument: " + opt + "; use -h for help");
15574            }
15575        }
15576
15577        // Is the caller requesting to dump a particular piece of data?
15578        if (opti < args.length) {
15579            String cmd = args[opti];
15580            opti++;
15581            // Is this a package name?
15582            if ("android".equals(cmd) || cmd.contains(".")) {
15583                packageName = cmd;
15584                // When dumping a single package, we always dump all of its
15585                // filter information since the amount of data will be reasonable.
15586                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15587            } else if ("check-permission".equals(cmd)) {
15588                if (opti >= args.length) {
15589                    pw.println("Error: check-permission missing permission argument");
15590                    return;
15591                }
15592                String perm = args[opti];
15593                opti++;
15594                if (opti >= args.length) {
15595                    pw.println("Error: check-permission missing package argument");
15596                    return;
15597                }
15598                String pkg = args[opti];
15599                opti++;
15600                int user = UserHandle.getUserId(Binder.getCallingUid());
15601                if (opti < args.length) {
15602                    try {
15603                        user = Integer.parseInt(args[opti]);
15604                    } catch (NumberFormatException e) {
15605                        pw.println("Error: check-permission user argument is not a number: "
15606                                + args[opti]);
15607                        return;
15608                    }
15609                }
15610                pw.println(checkPermission(perm, pkg, user));
15611                return;
15612            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15613                dumpState.setDump(DumpState.DUMP_LIBS);
15614            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15615                dumpState.setDump(DumpState.DUMP_FEATURES);
15616            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15617                if (opti >= args.length) {
15618                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15619                            | DumpState.DUMP_SERVICE_RESOLVERS
15620                            | DumpState.DUMP_RECEIVER_RESOLVERS
15621                            | DumpState.DUMP_CONTENT_RESOLVERS);
15622                } else {
15623                    while (opti < args.length) {
15624                        String name = args[opti];
15625                        if ("a".equals(name) || "activity".equals(name)) {
15626                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15627                        } else if ("s".equals(name) || "service".equals(name)) {
15628                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15629                        } else if ("r".equals(name) || "receiver".equals(name)) {
15630                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15631                        } else if ("c".equals(name) || "content".equals(name)) {
15632                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15633                        } else {
15634                            pw.println("Error: unknown resolver table type: " + name);
15635                            return;
15636                        }
15637                        opti++;
15638                    }
15639                }
15640            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15641                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15642            } else if ("permission".equals(cmd)) {
15643                if (opti >= args.length) {
15644                    pw.println("Error: permission requires permission name");
15645                    return;
15646                }
15647                permissionNames = new ArraySet<>();
15648                while (opti < args.length) {
15649                    permissionNames.add(args[opti]);
15650                    opti++;
15651                }
15652                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15653                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15654            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15655                dumpState.setDump(DumpState.DUMP_PREFERRED);
15656            } else if ("preferred-xml".equals(cmd)) {
15657                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15658                if (opti < args.length && "--full".equals(args[opti])) {
15659                    fullPreferred = true;
15660                    opti++;
15661                }
15662            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15663                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15664            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15665                dumpState.setDump(DumpState.DUMP_PACKAGES);
15666            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15667                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15668            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15669                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15670            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15671                dumpState.setDump(DumpState.DUMP_MESSAGES);
15672            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15673                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15674            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15675                    || "intent-filter-verifiers".equals(cmd)) {
15676                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15677            } else if ("version".equals(cmd)) {
15678                dumpState.setDump(DumpState.DUMP_VERSION);
15679            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15680                dumpState.setDump(DumpState.DUMP_KEYSETS);
15681            } else if ("installs".equals(cmd)) {
15682                dumpState.setDump(DumpState.DUMP_INSTALLS);
15683            } else if ("write".equals(cmd)) {
15684                synchronized (mPackages) {
15685                    mSettings.writeLPr();
15686                    pw.println("Settings written.");
15687                    return;
15688                }
15689            }
15690        }
15691
15692        if (checkin) {
15693            pw.println("vers,1");
15694        }
15695
15696        // reader
15697        synchronized (mPackages) {
15698            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15699                if (!checkin) {
15700                    if (dumpState.onTitlePrinted())
15701                        pw.println();
15702                    pw.println("Database versions:");
15703                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15704                }
15705            }
15706
15707            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15708                if (!checkin) {
15709                    if (dumpState.onTitlePrinted())
15710                        pw.println();
15711                    pw.println("Verifiers:");
15712                    pw.print("  Required: ");
15713                    pw.print(mRequiredVerifierPackage);
15714                    pw.print(" (uid=");
15715                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15716                    pw.println(")");
15717                } else if (mRequiredVerifierPackage != null) {
15718                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15719                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15720                }
15721            }
15722
15723            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15724                    packageName == null) {
15725                if (mIntentFilterVerifierComponent != null) {
15726                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15727                    if (!checkin) {
15728                        if (dumpState.onTitlePrinted())
15729                            pw.println();
15730                        pw.println("Intent Filter Verifier:");
15731                        pw.print("  Using: ");
15732                        pw.print(verifierPackageName);
15733                        pw.print(" (uid=");
15734                        pw.print(getPackageUid(verifierPackageName, 0));
15735                        pw.println(")");
15736                    } else if (verifierPackageName != null) {
15737                        pw.print("ifv,"); pw.print(verifierPackageName);
15738                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15739                    }
15740                } else {
15741                    pw.println();
15742                    pw.println("No Intent Filter Verifier available!");
15743                }
15744            }
15745
15746            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15747                boolean printedHeader = false;
15748                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15749                while (it.hasNext()) {
15750                    String name = it.next();
15751                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15752                    if (!checkin) {
15753                        if (!printedHeader) {
15754                            if (dumpState.onTitlePrinted())
15755                                pw.println();
15756                            pw.println("Libraries:");
15757                            printedHeader = true;
15758                        }
15759                        pw.print("  ");
15760                    } else {
15761                        pw.print("lib,");
15762                    }
15763                    pw.print(name);
15764                    if (!checkin) {
15765                        pw.print(" -> ");
15766                    }
15767                    if (ent.path != null) {
15768                        if (!checkin) {
15769                            pw.print("(jar) ");
15770                            pw.print(ent.path);
15771                        } else {
15772                            pw.print(",jar,");
15773                            pw.print(ent.path);
15774                        }
15775                    } else {
15776                        if (!checkin) {
15777                            pw.print("(apk) ");
15778                            pw.print(ent.apk);
15779                        } else {
15780                            pw.print(",apk,");
15781                            pw.print(ent.apk);
15782                        }
15783                    }
15784                    pw.println();
15785                }
15786            }
15787
15788            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15789                if (dumpState.onTitlePrinted())
15790                    pw.println();
15791                if (!checkin) {
15792                    pw.println("Features:");
15793                }
15794                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15795                while (it.hasNext()) {
15796                    String name = it.next();
15797                    if (!checkin) {
15798                        pw.print("  ");
15799                    } else {
15800                        pw.print("feat,");
15801                    }
15802                    pw.println(name);
15803                }
15804            }
15805
15806            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15807                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15808                        : "Activity Resolver Table:", "  ", packageName,
15809                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15810                    dumpState.setTitlePrinted(true);
15811                }
15812            }
15813            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15814                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15815                        : "Receiver Resolver Table:", "  ", packageName,
15816                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15817                    dumpState.setTitlePrinted(true);
15818                }
15819            }
15820            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15821                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15822                        : "Service Resolver Table:", "  ", packageName,
15823                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15824                    dumpState.setTitlePrinted(true);
15825                }
15826            }
15827            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15828                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15829                        : "Provider Resolver Table:", "  ", packageName,
15830                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15831                    dumpState.setTitlePrinted(true);
15832                }
15833            }
15834
15835            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15836                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15837                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15838                    int user = mSettings.mPreferredActivities.keyAt(i);
15839                    if (pir.dump(pw,
15840                            dumpState.getTitlePrinted()
15841                                ? "\nPreferred Activities User " + user + ":"
15842                                : "Preferred Activities User " + user + ":", "  ",
15843                            packageName, true, false)) {
15844                        dumpState.setTitlePrinted(true);
15845                    }
15846                }
15847            }
15848
15849            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15850                pw.flush();
15851                FileOutputStream fout = new FileOutputStream(fd);
15852                BufferedOutputStream str = new BufferedOutputStream(fout);
15853                XmlSerializer serializer = new FastXmlSerializer();
15854                try {
15855                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15856                    serializer.startDocument(null, true);
15857                    serializer.setFeature(
15858                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15859                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15860                    serializer.endDocument();
15861                    serializer.flush();
15862                } catch (IllegalArgumentException e) {
15863                    pw.println("Failed writing: " + e);
15864                } catch (IllegalStateException e) {
15865                    pw.println("Failed writing: " + e);
15866                } catch (IOException e) {
15867                    pw.println("Failed writing: " + e);
15868                }
15869            }
15870
15871            if (!checkin
15872                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15873                    && packageName == null) {
15874                pw.println();
15875                int count = mSettings.mPackages.size();
15876                if (count == 0) {
15877                    pw.println("No applications!");
15878                    pw.println();
15879                } else {
15880                    final String prefix = "  ";
15881                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15882                    if (allPackageSettings.size() == 0) {
15883                        pw.println("No domain preferred apps!");
15884                        pw.println();
15885                    } else {
15886                        pw.println("App verification status:");
15887                        pw.println();
15888                        count = 0;
15889                        for (PackageSetting ps : allPackageSettings) {
15890                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15891                            if (ivi == null || ivi.getPackageName() == null) continue;
15892                            pw.println(prefix + "Package: " + ivi.getPackageName());
15893                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15894                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15895                            pw.println();
15896                            count++;
15897                        }
15898                        if (count == 0) {
15899                            pw.println(prefix + "No app verification established.");
15900                            pw.println();
15901                        }
15902                        for (int userId : sUserManager.getUserIds()) {
15903                            pw.println("App linkages for user " + userId + ":");
15904                            pw.println();
15905                            count = 0;
15906                            for (PackageSetting ps : allPackageSettings) {
15907                                final long status = ps.getDomainVerificationStatusForUser(userId);
15908                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15909                                    continue;
15910                                }
15911                                pw.println(prefix + "Package: " + ps.name);
15912                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15913                                String statusStr = IntentFilterVerificationInfo.
15914                                        getStatusStringFromValue(status);
15915                                pw.println(prefix + "Status:  " + statusStr);
15916                                pw.println();
15917                                count++;
15918                            }
15919                            if (count == 0) {
15920                                pw.println(prefix + "No configured app linkages.");
15921                                pw.println();
15922                            }
15923                        }
15924                    }
15925                }
15926            }
15927
15928            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15929                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15930                if (packageName == null && permissionNames == null) {
15931                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15932                        if (iperm == 0) {
15933                            if (dumpState.onTitlePrinted())
15934                                pw.println();
15935                            pw.println("AppOp Permissions:");
15936                        }
15937                        pw.print("  AppOp Permission ");
15938                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15939                        pw.println(":");
15940                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15941                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15942                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15943                        }
15944                    }
15945                }
15946            }
15947
15948            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15949                boolean printedSomething = false;
15950                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15951                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15952                        continue;
15953                    }
15954                    if (!printedSomething) {
15955                        if (dumpState.onTitlePrinted())
15956                            pw.println();
15957                        pw.println("Registered ContentProviders:");
15958                        printedSomething = true;
15959                    }
15960                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15961                    pw.print("    "); pw.println(p.toString());
15962                }
15963                printedSomething = false;
15964                for (Map.Entry<String, PackageParser.Provider> entry :
15965                        mProvidersByAuthority.entrySet()) {
15966                    PackageParser.Provider p = entry.getValue();
15967                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15968                        continue;
15969                    }
15970                    if (!printedSomething) {
15971                        if (dumpState.onTitlePrinted())
15972                            pw.println();
15973                        pw.println("ContentProvider Authorities:");
15974                        printedSomething = true;
15975                    }
15976                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15977                    pw.print("    "); pw.println(p.toString());
15978                    if (p.info != null && p.info.applicationInfo != null) {
15979                        final String appInfo = p.info.applicationInfo.toString();
15980                        pw.print("      applicationInfo="); pw.println(appInfo);
15981                    }
15982                }
15983            }
15984
15985            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15986                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15987            }
15988
15989            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15990                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15991            }
15992
15993            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15994                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15995            }
15996
15997            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15998                // XXX should handle packageName != null by dumping only install data that
15999                // the given package is involved with.
16000                if (dumpState.onTitlePrinted()) pw.println();
16001                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16002            }
16003
16004            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16005                if (dumpState.onTitlePrinted()) pw.println();
16006                mSettings.dumpReadMessagesLPr(pw, dumpState);
16007
16008                pw.println();
16009                pw.println("Package warning messages:");
16010                BufferedReader in = null;
16011                String line = null;
16012                try {
16013                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16014                    while ((line = in.readLine()) != null) {
16015                        if (line.contains("ignored: updated version")) continue;
16016                        pw.println(line);
16017                    }
16018                } catch (IOException ignored) {
16019                } finally {
16020                    IoUtils.closeQuietly(in);
16021                }
16022            }
16023
16024            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16025                BufferedReader in = null;
16026                String line = null;
16027                try {
16028                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16029                    while ((line = in.readLine()) != null) {
16030                        if (line.contains("ignored: updated version")) continue;
16031                        pw.print("msg,");
16032                        pw.println(line);
16033                    }
16034                } catch (IOException ignored) {
16035                } finally {
16036                    IoUtils.closeQuietly(in);
16037                }
16038            }
16039        }
16040    }
16041
16042    private String dumpDomainString(String packageName) {
16043        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16044        List<IntentFilter> filters = getAllIntentFilters(packageName);
16045
16046        ArraySet<String> result = new ArraySet<>();
16047        if (iviList.size() > 0) {
16048            for (IntentFilterVerificationInfo ivi : iviList) {
16049                for (String host : ivi.getDomains()) {
16050                    result.add(host);
16051                }
16052            }
16053        }
16054        if (filters != null && filters.size() > 0) {
16055            for (IntentFilter filter : filters) {
16056                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16057                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16058                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16059                    result.addAll(filter.getHostsList());
16060                }
16061            }
16062        }
16063
16064        StringBuilder sb = new StringBuilder(result.size() * 16);
16065        for (String domain : result) {
16066            if (sb.length() > 0) sb.append(" ");
16067            sb.append(domain);
16068        }
16069        return sb.toString();
16070    }
16071
16072    // ------- apps on sdcard specific code -------
16073    static final boolean DEBUG_SD_INSTALL = false;
16074
16075    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16076
16077    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16078
16079    private boolean mMediaMounted = false;
16080
16081    static String getEncryptKey() {
16082        try {
16083            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16084                    SD_ENCRYPTION_KEYSTORE_NAME);
16085            if (sdEncKey == null) {
16086                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16087                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16088                if (sdEncKey == null) {
16089                    Slog.e(TAG, "Failed to create encryption keys");
16090                    return null;
16091                }
16092            }
16093            return sdEncKey;
16094        } catch (NoSuchAlgorithmException nsae) {
16095            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16096            return null;
16097        } catch (IOException ioe) {
16098            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16099            return null;
16100        }
16101    }
16102
16103    /*
16104     * Update media status on PackageManager.
16105     */
16106    @Override
16107    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16108        int callingUid = Binder.getCallingUid();
16109        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16110            throw new SecurityException("Media status can only be updated by the system");
16111        }
16112        // reader; this apparently protects mMediaMounted, but should probably
16113        // be a different lock in that case.
16114        synchronized (mPackages) {
16115            Log.i(TAG, "Updating external media status from "
16116                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16117                    + (mediaStatus ? "mounted" : "unmounted"));
16118            if (DEBUG_SD_INSTALL)
16119                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16120                        + ", mMediaMounted=" + mMediaMounted);
16121            if (mediaStatus == mMediaMounted) {
16122                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16123                        : 0, -1);
16124                mHandler.sendMessage(msg);
16125                return;
16126            }
16127            mMediaMounted = mediaStatus;
16128        }
16129        // Queue up an async operation since the package installation may take a
16130        // little while.
16131        mHandler.post(new Runnable() {
16132            public void run() {
16133                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16134            }
16135        });
16136    }
16137
16138    /**
16139     * Called by MountService when the initial ASECs to scan are available.
16140     * Should block until all the ASEC containers are finished being scanned.
16141     */
16142    public void scanAvailableAsecs() {
16143        updateExternalMediaStatusInner(true, false, false);
16144        if (mShouldRestoreconData) {
16145            SELinuxMMAC.setRestoreconDone();
16146            mShouldRestoreconData = false;
16147        }
16148    }
16149
16150    /*
16151     * Collect information of applications on external media, map them against
16152     * existing containers and update information based on current mount status.
16153     * Please note that we always have to report status if reportStatus has been
16154     * set to true especially when unloading packages.
16155     */
16156    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16157            boolean externalStorage) {
16158        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16159        int[] uidArr = EmptyArray.INT;
16160
16161        final String[] list = PackageHelper.getSecureContainerList();
16162        if (ArrayUtils.isEmpty(list)) {
16163            Log.i(TAG, "No secure containers found");
16164        } else {
16165            // Process list of secure containers and categorize them
16166            // as active or stale based on their package internal state.
16167
16168            // reader
16169            synchronized (mPackages) {
16170                for (String cid : list) {
16171                    // Leave stages untouched for now; installer service owns them
16172                    if (PackageInstallerService.isStageName(cid)) continue;
16173
16174                    if (DEBUG_SD_INSTALL)
16175                        Log.i(TAG, "Processing container " + cid);
16176                    String pkgName = getAsecPackageName(cid);
16177                    if (pkgName == null) {
16178                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16179                        continue;
16180                    }
16181                    if (DEBUG_SD_INSTALL)
16182                        Log.i(TAG, "Looking for pkg : " + pkgName);
16183
16184                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16185                    if (ps == null) {
16186                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16187                        continue;
16188                    }
16189
16190                    /*
16191                     * Skip packages that are not external if we're unmounting
16192                     * external storage.
16193                     */
16194                    if (externalStorage && !isMounted && !isExternal(ps)) {
16195                        continue;
16196                    }
16197
16198                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16199                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16200                    // The package status is changed only if the code path
16201                    // matches between settings and the container id.
16202                    if (ps.codePathString != null
16203                            && ps.codePathString.startsWith(args.getCodePath())) {
16204                        if (DEBUG_SD_INSTALL) {
16205                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16206                                    + " at code path: " + ps.codePathString);
16207                        }
16208
16209                        // We do have a valid package installed on sdcard
16210                        processCids.put(args, ps.codePathString);
16211                        final int uid = ps.appId;
16212                        if (uid != -1) {
16213                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16214                        }
16215                    } else {
16216                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16217                                + ps.codePathString);
16218                    }
16219                }
16220            }
16221
16222            Arrays.sort(uidArr);
16223        }
16224
16225        // Process packages with valid entries.
16226        if (isMounted) {
16227            if (DEBUG_SD_INSTALL)
16228                Log.i(TAG, "Loading packages");
16229            loadMediaPackages(processCids, uidArr, externalStorage);
16230            startCleaningPackages();
16231            mInstallerService.onSecureContainersAvailable();
16232        } else {
16233            if (DEBUG_SD_INSTALL)
16234                Log.i(TAG, "Unloading packages");
16235            unloadMediaPackages(processCids, uidArr, reportStatus);
16236        }
16237    }
16238
16239    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16240            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16241        final int size = infos.size();
16242        final String[] packageNames = new String[size];
16243        final int[] packageUids = new int[size];
16244        for (int i = 0; i < size; i++) {
16245            final ApplicationInfo info = infos.get(i);
16246            packageNames[i] = info.packageName;
16247            packageUids[i] = info.uid;
16248        }
16249        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16250                finishedReceiver);
16251    }
16252
16253    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16254            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16255        sendResourcesChangedBroadcast(mediaStatus, replacing,
16256                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16257    }
16258
16259    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16260            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16261        int size = pkgList.length;
16262        if (size > 0) {
16263            // Send broadcasts here
16264            Bundle extras = new Bundle();
16265            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16266            if (uidArr != null) {
16267                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16268            }
16269            if (replacing) {
16270                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16271            }
16272            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16273                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16274            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16275        }
16276    }
16277
16278   /*
16279     * Look at potentially valid container ids from processCids If package
16280     * information doesn't match the one on record or package scanning fails,
16281     * the cid is added to list of removeCids. We currently don't delete stale
16282     * containers.
16283     */
16284    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16285            boolean externalStorage) {
16286        ArrayList<String> pkgList = new ArrayList<String>();
16287        Set<AsecInstallArgs> keys = processCids.keySet();
16288
16289        for (AsecInstallArgs args : keys) {
16290            String codePath = processCids.get(args);
16291            if (DEBUG_SD_INSTALL)
16292                Log.i(TAG, "Loading container : " + args.cid);
16293            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16294            try {
16295                // Make sure there are no container errors first.
16296                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16297                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16298                            + " when installing from sdcard");
16299                    continue;
16300                }
16301                // Check code path here.
16302                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16303                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16304                            + " does not match one in settings " + codePath);
16305                    continue;
16306                }
16307                // Parse package
16308                int parseFlags = mDefParseFlags;
16309                if (args.isExternalAsec()) {
16310                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16311                }
16312                if (args.isFwdLocked()) {
16313                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16314                }
16315
16316                synchronized (mInstallLock) {
16317                    PackageParser.Package pkg = null;
16318                    try {
16319                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16320                    } catch (PackageManagerException e) {
16321                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16322                    }
16323                    // Scan the package
16324                    if (pkg != null) {
16325                        /*
16326                         * TODO why is the lock being held? doPostInstall is
16327                         * called in other places without the lock. This needs
16328                         * to be straightened out.
16329                         */
16330                        // writer
16331                        synchronized (mPackages) {
16332                            retCode = PackageManager.INSTALL_SUCCEEDED;
16333                            pkgList.add(pkg.packageName);
16334                            // Post process args
16335                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16336                                    pkg.applicationInfo.uid);
16337                        }
16338                    } else {
16339                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16340                    }
16341                }
16342
16343            } finally {
16344                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16345                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16346                }
16347            }
16348        }
16349        // writer
16350        synchronized (mPackages) {
16351            // If the platform SDK has changed since the last time we booted,
16352            // we need to re-grant app permission to catch any new ones that
16353            // appear. This is really a hack, and means that apps can in some
16354            // cases get permissions that the user didn't initially explicitly
16355            // allow... it would be nice to have some better way to handle
16356            // this situation.
16357            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16358                    : mSettings.getInternalVersion();
16359            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16360                    : StorageManager.UUID_PRIVATE_INTERNAL;
16361
16362            int updateFlags = UPDATE_PERMISSIONS_ALL;
16363            if (ver.sdkVersion != mSdkVersion) {
16364                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16365                        + mSdkVersion + "; regranting permissions for external");
16366                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16367            }
16368            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16369
16370            // Yay, everything is now upgraded
16371            ver.forceCurrent();
16372
16373            // can downgrade to reader
16374            // Persist settings
16375            mSettings.writeLPr();
16376        }
16377        // Send a broadcast to let everyone know we are done processing
16378        if (pkgList.size() > 0) {
16379            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16380        }
16381    }
16382
16383   /*
16384     * Utility method to unload a list of specified containers
16385     */
16386    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16387        // Just unmount all valid containers.
16388        for (AsecInstallArgs arg : cidArgs) {
16389            synchronized (mInstallLock) {
16390                arg.doPostDeleteLI(false);
16391           }
16392       }
16393   }
16394
16395    /*
16396     * Unload packages mounted on external media. This involves deleting package
16397     * data from internal structures, sending broadcasts about diabled packages,
16398     * gc'ing to free up references, unmounting all secure containers
16399     * corresponding to packages on external media, and posting a
16400     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16401     * that we always have to post this message if status has been requested no
16402     * matter what.
16403     */
16404    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16405            final boolean reportStatus) {
16406        if (DEBUG_SD_INSTALL)
16407            Log.i(TAG, "unloading media packages");
16408        ArrayList<String> pkgList = new ArrayList<String>();
16409        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16410        final Set<AsecInstallArgs> keys = processCids.keySet();
16411        for (AsecInstallArgs args : keys) {
16412            String pkgName = args.getPackageName();
16413            if (DEBUG_SD_INSTALL)
16414                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16415            // Delete package internally
16416            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16417            synchronized (mInstallLock) {
16418                boolean res = deletePackageLI(pkgName, null, false, null, null,
16419                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16420                if (res) {
16421                    pkgList.add(pkgName);
16422                } else {
16423                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16424                    failedList.add(args);
16425                }
16426            }
16427        }
16428
16429        // reader
16430        synchronized (mPackages) {
16431            // We didn't update the settings after removing each package;
16432            // write them now for all packages.
16433            mSettings.writeLPr();
16434        }
16435
16436        // We have to absolutely send UPDATED_MEDIA_STATUS only
16437        // after confirming that all the receivers processed the ordered
16438        // broadcast when packages get disabled, force a gc to clean things up.
16439        // and unload all the containers.
16440        if (pkgList.size() > 0) {
16441            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16442                    new IIntentReceiver.Stub() {
16443                public void performReceive(Intent intent, int resultCode, String data,
16444                        Bundle extras, boolean ordered, boolean sticky,
16445                        int sendingUser) throws RemoteException {
16446                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16447                            reportStatus ? 1 : 0, 1, keys);
16448                    mHandler.sendMessage(msg);
16449                }
16450            });
16451        } else {
16452            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16453                    keys);
16454            mHandler.sendMessage(msg);
16455        }
16456    }
16457
16458    private void loadPrivatePackages(final VolumeInfo vol) {
16459        mHandler.post(new Runnable() {
16460            @Override
16461            public void run() {
16462                loadPrivatePackagesInner(vol);
16463            }
16464        });
16465    }
16466
16467    private void loadPrivatePackagesInner(VolumeInfo vol) {
16468        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16469        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16470
16471        final VersionInfo ver;
16472        final List<PackageSetting> packages;
16473        synchronized (mPackages) {
16474            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16475            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16476        }
16477
16478        for (PackageSetting ps : packages) {
16479            synchronized (mInstallLock) {
16480                final PackageParser.Package pkg;
16481                try {
16482                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16483                    loaded.add(pkg.applicationInfo);
16484                } catch (PackageManagerException e) {
16485                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16486                }
16487
16488                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16489                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16490                }
16491            }
16492        }
16493
16494        synchronized (mPackages) {
16495            int updateFlags = UPDATE_PERMISSIONS_ALL;
16496            if (ver.sdkVersion != mSdkVersion) {
16497                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16498                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16499                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16500            }
16501            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16502
16503            // Yay, everything is now upgraded
16504            ver.forceCurrent();
16505
16506            mSettings.writeLPr();
16507        }
16508
16509        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16510        sendResourcesChangedBroadcast(true, false, loaded, null);
16511    }
16512
16513    private void unloadPrivatePackages(final VolumeInfo vol) {
16514        mHandler.post(new Runnable() {
16515            @Override
16516            public void run() {
16517                unloadPrivatePackagesInner(vol);
16518            }
16519        });
16520    }
16521
16522    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16523        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16524        synchronized (mInstallLock) {
16525        synchronized (mPackages) {
16526            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16527            for (PackageSetting ps : packages) {
16528                if (ps.pkg == null) continue;
16529
16530                final ApplicationInfo info = ps.pkg.applicationInfo;
16531                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16532                if (deletePackageLI(ps.name, null, false, null, null,
16533                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16534                    unloaded.add(info);
16535                } else {
16536                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16537                }
16538            }
16539
16540            mSettings.writeLPr();
16541        }
16542        }
16543
16544        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16545        sendResourcesChangedBroadcast(false, false, unloaded, null);
16546    }
16547
16548    /**
16549     * Examine all users present on given mounted volume, and destroy data
16550     * belonging to users that are no longer valid, or whose user ID has been
16551     * recycled.
16552     */
16553    private void reconcileUsers(String volumeUuid) {
16554        final File[] files = FileUtils
16555                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16556        for (File file : files) {
16557            if (!file.isDirectory()) continue;
16558
16559            final int userId;
16560            final UserInfo info;
16561            try {
16562                userId = Integer.parseInt(file.getName());
16563                info = sUserManager.getUserInfo(userId);
16564            } catch (NumberFormatException e) {
16565                Slog.w(TAG, "Invalid user directory " + file);
16566                continue;
16567            }
16568
16569            boolean destroyUser = false;
16570            if (info == null) {
16571                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16572                        + " because no matching user was found");
16573                destroyUser = true;
16574            } else {
16575                try {
16576                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16577                } catch (IOException e) {
16578                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16579                            + " because we failed to enforce serial number: " + e);
16580                    destroyUser = true;
16581                }
16582            }
16583
16584            if (destroyUser) {
16585                synchronized (mInstallLock) {
16586                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16587                }
16588            }
16589        }
16590
16591        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16592        final UserManager um = mContext.getSystemService(UserManager.class);
16593        for (UserInfo user : um.getUsers()) {
16594            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16595            if (userDir.exists()) continue;
16596
16597            try {
16598                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16599                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16600            } catch (IOException e) {
16601                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16602            }
16603        }
16604    }
16605
16606    /**
16607     * Examine all apps present on given mounted volume, and destroy apps that
16608     * aren't expected, either due to uninstallation or reinstallation on
16609     * another volume.
16610     */
16611    private void reconcileApps(String volumeUuid) {
16612        final File[] files = FileUtils
16613                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16614        for (File file : files) {
16615            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16616                    && !PackageInstallerService.isStageName(file.getName());
16617            if (!isPackage) {
16618                // Ignore entries which are not packages
16619                continue;
16620            }
16621
16622            boolean destroyApp = false;
16623            String packageName = null;
16624            try {
16625                final PackageLite pkg = PackageParser.parsePackageLite(file,
16626                        PackageParser.PARSE_MUST_BE_APK);
16627                packageName = pkg.packageName;
16628
16629                synchronized (mPackages) {
16630                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16631                    if (ps == null) {
16632                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16633                                + volumeUuid + " because we found no install record");
16634                        destroyApp = true;
16635                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16636                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16637                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16638                        destroyApp = true;
16639                    }
16640                }
16641
16642            } catch (PackageParserException e) {
16643                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16644                destroyApp = true;
16645            }
16646
16647            if (destroyApp) {
16648                synchronized (mInstallLock) {
16649                    if (packageName != null) {
16650                        removeDataDirsLI(volumeUuid, packageName);
16651                    }
16652                    if (file.isDirectory()) {
16653                        mInstaller.rmPackageDir(file.getAbsolutePath());
16654                    } else {
16655                        file.delete();
16656                    }
16657                }
16658            }
16659        }
16660    }
16661
16662    private void unfreezePackage(String packageName) {
16663        synchronized (mPackages) {
16664            final PackageSetting ps = mSettings.mPackages.get(packageName);
16665            if (ps != null) {
16666                ps.frozen = false;
16667            }
16668        }
16669    }
16670
16671    @Override
16672    public int movePackage(final String packageName, final String volumeUuid) {
16673        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16674
16675        final int moveId = mNextMoveId.getAndIncrement();
16676        mHandler.post(new Runnable() {
16677            @Override
16678            public void run() {
16679                try {
16680                    movePackageInternal(packageName, volumeUuid, moveId);
16681                } catch (PackageManagerException e) {
16682                    Slog.w(TAG, "Failed to move " + packageName, e);
16683                    mMoveCallbacks.notifyStatusChanged(moveId,
16684                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16685                }
16686            }
16687        });
16688        return moveId;
16689    }
16690
16691    private void movePackageInternal(final String packageName, final String volumeUuid,
16692            final int moveId) throws PackageManagerException {
16693        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16694        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16695        final PackageManager pm = mContext.getPackageManager();
16696
16697        final boolean currentAsec;
16698        final String currentVolumeUuid;
16699        final File codeFile;
16700        final String installerPackageName;
16701        final String packageAbiOverride;
16702        final int appId;
16703        final String seinfo;
16704        final String label;
16705
16706        // reader
16707        synchronized (mPackages) {
16708            final PackageParser.Package pkg = mPackages.get(packageName);
16709            final PackageSetting ps = mSettings.mPackages.get(packageName);
16710            if (pkg == null || ps == null) {
16711                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16712            }
16713
16714            if (pkg.applicationInfo.isSystemApp()) {
16715                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16716                        "Cannot move system application");
16717            }
16718
16719            if (pkg.applicationInfo.isExternalAsec()) {
16720                currentAsec = true;
16721                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16722            } else if (pkg.applicationInfo.isForwardLocked()) {
16723                currentAsec = true;
16724                currentVolumeUuid = "forward_locked";
16725            } else {
16726                currentAsec = false;
16727                currentVolumeUuid = ps.volumeUuid;
16728
16729                final File probe = new File(pkg.codePath);
16730                final File probeOat = new File(probe, "oat");
16731                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16732                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16733                            "Move only supported for modern cluster style installs");
16734                }
16735            }
16736
16737            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16738                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16739                        "Package already moved to " + volumeUuid);
16740            }
16741
16742            if (ps.frozen) {
16743                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16744                        "Failed to move already frozen package");
16745            }
16746            ps.frozen = true;
16747
16748            codeFile = new File(pkg.codePath);
16749            installerPackageName = ps.installerPackageName;
16750            packageAbiOverride = ps.cpuAbiOverrideString;
16751            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16752            seinfo = pkg.applicationInfo.seinfo;
16753            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16754        }
16755
16756        // Now that we're guarded by frozen state, kill app during move
16757        final long token = Binder.clearCallingIdentity();
16758        try {
16759            killApplication(packageName, appId, "move pkg");
16760        } finally {
16761            Binder.restoreCallingIdentity(token);
16762        }
16763
16764        final Bundle extras = new Bundle();
16765        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16766        extras.putString(Intent.EXTRA_TITLE, label);
16767        mMoveCallbacks.notifyCreated(moveId, extras);
16768
16769        int installFlags;
16770        final boolean moveCompleteApp;
16771        final File measurePath;
16772
16773        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16774            installFlags = INSTALL_INTERNAL;
16775            moveCompleteApp = !currentAsec;
16776            measurePath = Environment.getDataAppDirectory(volumeUuid);
16777        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16778            installFlags = INSTALL_EXTERNAL;
16779            moveCompleteApp = false;
16780            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16781        } else {
16782            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16783            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16784                    || !volume.isMountedWritable()) {
16785                unfreezePackage(packageName);
16786                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16787                        "Move location not mounted private volume");
16788            }
16789
16790            Preconditions.checkState(!currentAsec);
16791
16792            installFlags = INSTALL_INTERNAL;
16793            moveCompleteApp = true;
16794            measurePath = Environment.getDataAppDirectory(volumeUuid);
16795        }
16796
16797        final PackageStats stats = new PackageStats(null, -1);
16798        synchronized (mInstaller) {
16799            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16800                unfreezePackage(packageName);
16801                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16802                        "Failed to measure package size");
16803            }
16804        }
16805
16806        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16807                + stats.dataSize);
16808
16809        final long startFreeBytes = measurePath.getFreeSpace();
16810        final long sizeBytes;
16811        if (moveCompleteApp) {
16812            sizeBytes = stats.codeSize + stats.dataSize;
16813        } else {
16814            sizeBytes = stats.codeSize;
16815        }
16816
16817        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16818            unfreezePackage(packageName);
16819            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16820                    "Not enough free space to move");
16821        }
16822
16823        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16824
16825        final CountDownLatch installedLatch = new CountDownLatch(1);
16826        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16827            @Override
16828            public void onUserActionRequired(Intent intent) throws RemoteException {
16829                throw new IllegalStateException();
16830            }
16831
16832            @Override
16833            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16834                    Bundle extras) throws RemoteException {
16835                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16836                        + PackageManager.installStatusToString(returnCode, msg));
16837
16838                installedLatch.countDown();
16839
16840                // Regardless of success or failure of the move operation,
16841                // always unfreeze the package
16842                unfreezePackage(packageName);
16843
16844                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16845                switch (status) {
16846                    case PackageInstaller.STATUS_SUCCESS:
16847                        mMoveCallbacks.notifyStatusChanged(moveId,
16848                                PackageManager.MOVE_SUCCEEDED);
16849                        break;
16850                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16851                        mMoveCallbacks.notifyStatusChanged(moveId,
16852                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16853                        break;
16854                    default:
16855                        mMoveCallbacks.notifyStatusChanged(moveId,
16856                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16857                        break;
16858                }
16859            }
16860        };
16861
16862        final MoveInfo move;
16863        if (moveCompleteApp) {
16864            // Kick off a thread to report progress estimates
16865            new Thread() {
16866                @Override
16867                public void run() {
16868                    while (true) {
16869                        try {
16870                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16871                                break;
16872                            }
16873                        } catch (InterruptedException ignored) {
16874                        }
16875
16876                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16877                        final int progress = 10 + (int) MathUtils.constrain(
16878                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16879                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16880                    }
16881                }
16882            }.start();
16883
16884            final String dataAppName = codeFile.getName();
16885            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16886                    dataAppName, appId, seinfo);
16887        } else {
16888            move = null;
16889        }
16890
16891        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16892
16893        final Message msg = mHandler.obtainMessage(INIT_COPY);
16894        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16895        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16896                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16897        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16898        msg.obj = params;
16899
16900        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16901                System.identityHashCode(msg.obj));
16902        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16903                System.identityHashCode(msg.obj));
16904
16905        mHandler.sendMessage(msg);
16906    }
16907
16908    @Override
16909    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16910        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16911
16912        final int realMoveId = mNextMoveId.getAndIncrement();
16913        final Bundle extras = new Bundle();
16914        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16915        mMoveCallbacks.notifyCreated(realMoveId, extras);
16916
16917        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16918            @Override
16919            public void onCreated(int moveId, Bundle extras) {
16920                // Ignored
16921            }
16922
16923            @Override
16924            public void onStatusChanged(int moveId, int status, long estMillis) {
16925                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16926            }
16927        };
16928
16929        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16930        storage.setPrimaryStorageUuid(volumeUuid, callback);
16931        return realMoveId;
16932    }
16933
16934    @Override
16935    public int getMoveStatus(int moveId) {
16936        mContext.enforceCallingOrSelfPermission(
16937                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16938        return mMoveCallbacks.mLastStatus.get(moveId);
16939    }
16940
16941    @Override
16942    public void registerMoveCallback(IPackageMoveObserver callback) {
16943        mContext.enforceCallingOrSelfPermission(
16944                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16945        mMoveCallbacks.register(callback);
16946    }
16947
16948    @Override
16949    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16950        mContext.enforceCallingOrSelfPermission(
16951                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16952        mMoveCallbacks.unregister(callback);
16953    }
16954
16955    @Override
16956    public boolean setInstallLocation(int loc) {
16957        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16958                null);
16959        if (getInstallLocation() == loc) {
16960            return true;
16961        }
16962        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16963                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16964            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16965                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16966            return true;
16967        }
16968        return false;
16969   }
16970
16971    @Override
16972    public int getInstallLocation() {
16973        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16974                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16975                PackageHelper.APP_INSTALL_AUTO);
16976    }
16977
16978    /** Called by UserManagerService */
16979    void cleanUpUser(UserManagerService userManager, int userHandle) {
16980        synchronized (mPackages) {
16981            mDirtyUsers.remove(userHandle);
16982            mUserNeedsBadging.delete(userHandle);
16983            mSettings.removeUserLPw(userHandle);
16984            mPendingBroadcasts.remove(userHandle);
16985            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16986        }
16987        synchronized (mInstallLock) {
16988            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16989            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16990                final String volumeUuid = vol.getFsUuid();
16991                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16992                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16993            }
16994            synchronized (mPackages) {
16995                removeUnusedPackagesLILPw(userManager, userHandle);
16996            }
16997        }
16998    }
16999
17000    /**
17001     * We're removing userHandle and would like to remove any downloaded packages
17002     * that are no longer in use by any other user.
17003     * @param userHandle the user being removed
17004     */
17005    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17006        final boolean DEBUG_CLEAN_APKS = false;
17007        int [] users = userManager.getUserIds();
17008        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17009        while (psit.hasNext()) {
17010            PackageSetting ps = psit.next();
17011            if (ps.pkg == null) {
17012                continue;
17013            }
17014            final String packageName = ps.pkg.packageName;
17015            // Skip over if system app
17016            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17017                continue;
17018            }
17019            if (DEBUG_CLEAN_APKS) {
17020                Slog.i(TAG, "Checking package " + packageName);
17021            }
17022            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17023            if (keep) {
17024                if (DEBUG_CLEAN_APKS) {
17025                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17026                }
17027            } else {
17028                for (int i = 0; i < users.length; i++) {
17029                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17030                        keep = true;
17031                        if (DEBUG_CLEAN_APKS) {
17032                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17033                                    + users[i]);
17034                        }
17035                        break;
17036                    }
17037                }
17038            }
17039            if (!keep) {
17040                if (DEBUG_CLEAN_APKS) {
17041                    Slog.i(TAG, "  Removing package " + packageName);
17042                }
17043                mHandler.post(new Runnable() {
17044                    public void run() {
17045                        deletePackageX(packageName, userHandle, 0);
17046                    } //end run
17047                });
17048            }
17049        }
17050    }
17051
17052    /** Called by UserManagerService */
17053    void createNewUser(int userHandle) {
17054        synchronized (mInstallLock) {
17055            mInstaller.createUserConfig(userHandle);
17056            mSettings.createNewUserLI(this, mInstaller, userHandle);
17057        }
17058        synchronized (mPackages) {
17059            applyFactoryDefaultBrowserLPw(userHandle);
17060            primeDomainVerificationsLPw(userHandle);
17061        }
17062    }
17063
17064    void newUserCreated(final int userHandle) {
17065        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17066        // If permission review for legacy apps is required, we represent
17067        // dagerous permissions for such apps as always granted runtime
17068        // permissions to keep per user flag state whether review is needed.
17069        // Hence, if a new user is added we have to propagate dangerous
17070        // permission grants for these legacy apps.
17071        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17072            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17073                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17074        }
17075    }
17076
17077    @Override
17078    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17079        mContext.enforceCallingOrSelfPermission(
17080                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17081                "Only package verification agents can read the verifier device identity");
17082
17083        synchronized (mPackages) {
17084            return mSettings.getVerifierDeviceIdentityLPw();
17085        }
17086    }
17087
17088    @Override
17089    public void setPermissionEnforced(String permission, boolean enforced) {
17090        // TODO: Now that we no longer change GID for storage, this should to away.
17091        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17092                "setPermissionEnforced");
17093        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17094            synchronized (mPackages) {
17095                if (mSettings.mReadExternalStorageEnforced == null
17096                        || mSettings.mReadExternalStorageEnforced != enforced) {
17097                    mSettings.mReadExternalStorageEnforced = enforced;
17098                    mSettings.writeLPr();
17099                }
17100            }
17101            // kill any non-foreground processes so we restart them and
17102            // grant/revoke the GID.
17103            final IActivityManager am = ActivityManagerNative.getDefault();
17104            if (am != null) {
17105                final long token = Binder.clearCallingIdentity();
17106                try {
17107                    am.killProcessesBelowForeground("setPermissionEnforcement");
17108                } catch (RemoteException e) {
17109                } finally {
17110                    Binder.restoreCallingIdentity(token);
17111                }
17112            }
17113        } else {
17114            throw new IllegalArgumentException("No selective enforcement for " + permission);
17115        }
17116    }
17117
17118    @Override
17119    @Deprecated
17120    public boolean isPermissionEnforced(String permission) {
17121        return true;
17122    }
17123
17124    @Override
17125    public boolean isStorageLow() {
17126        final long token = Binder.clearCallingIdentity();
17127        try {
17128            final DeviceStorageMonitorInternal
17129                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17130            if (dsm != null) {
17131                return dsm.isMemoryLow();
17132            } else {
17133                return false;
17134            }
17135        } finally {
17136            Binder.restoreCallingIdentity(token);
17137        }
17138    }
17139
17140    @Override
17141    public IPackageInstaller getPackageInstaller() {
17142        return mInstallerService;
17143    }
17144
17145    private boolean userNeedsBadging(int userId) {
17146        int index = mUserNeedsBadging.indexOfKey(userId);
17147        if (index < 0) {
17148            final UserInfo userInfo;
17149            final long token = Binder.clearCallingIdentity();
17150            try {
17151                userInfo = sUserManager.getUserInfo(userId);
17152            } finally {
17153                Binder.restoreCallingIdentity(token);
17154            }
17155            final boolean b;
17156            if (userInfo != null && userInfo.isManagedProfile()) {
17157                b = true;
17158            } else {
17159                b = false;
17160            }
17161            mUserNeedsBadging.put(userId, b);
17162            return b;
17163        }
17164        return mUserNeedsBadging.valueAt(index);
17165    }
17166
17167    @Override
17168    public KeySet getKeySetByAlias(String packageName, String alias) {
17169        if (packageName == null || alias == null) {
17170            return null;
17171        }
17172        synchronized(mPackages) {
17173            final PackageParser.Package pkg = mPackages.get(packageName);
17174            if (pkg == null) {
17175                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17176                throw new IllegalArgumentException("Unknown package: " + packageName);
17177            }
17178            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17179            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17180        }
17181    }
17182
17183    @Override
17184    public KeySet getSigningKeySet(String packageName) {
17185        if (packageName == null) {
17186            return null;
17187        }
17188        synchronized(mPackages) {
17189            final PackageParser.Package pkg = mPackages.get(packageName);
17190            if (pkg == null) {
17191                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17192                throw new IllegalArgumentException("Unknown package: " + packageName);
17193            }
17194            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17195                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17196                throw new SecurityException("May not access signing KeySet of other apps.");
17197            }
17198            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17199            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17200        }
17201    }
17202
17203    @Override
17204    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17205        if (packageName == null || ks == null) {
17206            return false;
17207        }
17208        synchronized(mPackages) {
17209            final PackageParser.Package pkg = mPackages.get(packageName);
17210            if (pkg == null) {
17211                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17212                throw new IllegalArgumentException("Unknown package: " + packageName);
17213            }
17214            IBinder ksh = ks.getToken();
17215            if (ksh instanceof KeySetHandle) {
17216                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17217                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17218            }
17219            return false;
17220        }
17221    }
17222
17223    @Override
17224    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17225        if (packageName == null || ks == null) {
17226            return false;
17227        }
17228        synchronized(mPackages) {
17229            final PackageParser.Package pkg = mPackages.get(packageName);
17230            if (pkg == null) {
17231                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17232                throw new IllegalArgumentException("Unknown package: " + packageName);
17233            }
17234            IBinder ksh = ks.getToken();
17235            if (ksh instanceof KeySetHandle) {
17236                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17237                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17238            }
17239            return false;
17240        }
17241    }
17242
17243    private void deletePackageIfUnusedLPr(final String packageName) {
17244        PackageSetting ps = mSettings.mPackages.get(packageName);
17245        if (ps == null) {
17246            return;
17247        }
17248        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17249            // TODO Implement atomic delete if package is unused
17250            // It is currently possible that the package will be deleted even if it is installed
17251            // after this method returns.
17252            mHandler.post(new Runnable() {
17253                public void run() {
17254                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17255                }
17256            });
17257        }
17258    }
17259
17260    /**
17261     * Check and throw if the given before/after packages would be considered a
17262     * downgrade.
17263     */
17264    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17265            throws PackageManagerException {
17266        if (after.versionCode < before.mVersionCode) {
17267            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17268                    "Update version code " + after.versionCode + " is older than current "
17269                    + before.mVersionCode);
17270        } else if (after.versionCode == before.mVersionCode) {
17271            if (after.baseRevisionCode < before.baseRevisionCode) {
17272                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17273                        "Update base revision code " + after.baseRevisionCode
17274                        + " is older than current " + before.baseRevisionCode);
17275            }
17276
17277            if (!ArrayUtils.isEmpty(after.splitNames)) {
17278                for (int i = 0; i < after.splitNames.length; i++) {
17279                    final String splitName = after.splitNames[i];
17280                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17281                    if (j != -1) {
17282                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17283                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17284                                    "Update split " + splitName + " revision code "
17285                                    + after.splitRevisionCodes[i] + " is older than current "
17286                                    + before.splitRevisionCodes[j]);
17287                        }
17288                    }
17289                }
17290            }
17291        }
17292    }
17293
17294    private static class MoveCallbacks extends Handler {
17295        private static final int MSG_CREATED = 1;
17296        private static final int MSG_STATUS_CHANGED = 2;
17297
17298        private final RemoteCallbackList<IPackageMoveObserver>
17299                mCallbacks = new RemoteCallbackList<>();
17300
17301        private final SparseIntArray mLastStatus = new SparseIntArray();
17302
17303        public MoveCallbacks(Looper looper) {
17304            super(looper);
17305        }
17306
17307        public void register(IPackageMoveObserver callback) {
17308            mCallbacks.register(callback);
17309        }
17310
17311        public void unregister(IPackageMoveObserver callback) {
17312            mCallbacks.unregister(callback);
17313        }
17314
17315        @Override
17316        public void handleMessage(Message msg) {
17317            final SomeArgs args = (SomeArgs) msg.obj;
17318            final int n = mCallbacks.beginBroadcast();
17319            for (int i = 0; i < n; i++) {
17320                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17321                try {
17322                    invokeCallback(callback, msg.what, args);
17323                } catch (RemoteException ignored) {
17324                }
17325            }
17326            mCallbacks.finishBroadcast();
17327            args.recycle();
17328        }
17329
17330        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17331                throws RemoteException {
17332            switch (what) {
17333                case MSG_CREATED: {
17334                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17335                    break;
17336                }
17337                case MSG_STATUS_CHANGED: {
17338                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17339                    break;
17340                }
17341            }
17342        }
17343
17344        private void notifyCreated(int moveId, Bundle extras) {
17345            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17346
17347            final SomeArgs args = SomeArgs.obtain();
17348            args.argi1 = moveId;
17349            args.arg2 = extras;
17350            obtainMessage(MSG_CREATED, args).sendToTarget();
17351        }
17352
17353        private void notifyStatusChanged(int moveId, int status) {
17354            notifyStatusChanged(moveId, status, -1);
17355        }
17356
17357        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17358            Slog.v(TAG, "Move " + moveId + " status " + status);
17359
17360            final SomeArgs args = SomeArgs.obtain();
17361            args.argi1 = moveId;
17362            args.argi2 = status;
17363            args.arg3 = estMillis;
17364            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17365
17366            synchronized (mLastStatus) {
17367                mLastStatus.put(moveId, status);
17368            }
17369        }
17370    }
17371
17372    private final static class OnPermissionChangeListeners extends Handler {
17373        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17374
17375        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17376                new RemoteCallbackList<>();
17377
17378        public OnPermissionChangeListeners(Looper looper) {
17379            super(looper);
17380        }
17381
17382        @Override
17383        public void handleMessage(Message msg) {
17384            switch (msg.what) {
17385                case MSG_ON_PERMISSIONS_CHANGED: {
17386                    final int uid = msg.arg1;
17387                    handleOnPermissionsChanged(uid);
17388                } break;
17389            }
17390        }
17391
17392        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17393            mPermissionListeners.register(listener);
17394
17395        }
17396
17397        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17398            mPermissionListeners.unregister(listener);
17399        }
17400
17401        public void onPermissionsChanged(int uid) {
17402            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17403                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17404            }
17405        }
17406
17407        private void handleOnPermissionsChanged(int uid) {
17408            final int count = mPermissionListeners.beginBroadcast();
17409            try {
17410                for (int i = 0; i < count; i++) {
17411                    IOnPermissionsChangeListener callback = mPermissionListeners
17412                            .getBroadcastItem(i);
17413                    try {
17414                        callback.onPermissionsChanged(uid);
17415                    } catch (RemoteException e) {
17416                        Log.e(TAG, "Permission listener is dead", e);
17417                    }
17418                }
17419            } finally {
17420                mPermissionListeners.finishBroadcast();
17421            }
17422        }
17423    }
17424
17425    private class PackageManagerInternalImpl extends PackageManagerInternal {
17426        @Override
17427        public void setLocationPackagesProvider(PackagesProvider provider) {
17428            synchronized (mPackages) {
17429                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17430            }
17431        }
17432
17433        @Override
17434        public void setImePackagesProvider(PackagesProvider provider) {
17435            synchronized (mPackages) {
17436                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17437            }
17438        }
17439
17440        @Override
17441        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17442            synchronized (mPackages) {
17443                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17444            }
17445        }
17446
17447        @Override
17448        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17449            synchronized (mPackages) {
17450                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17451            }
17452        }
17453
17454        @Override
17455        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17456            synchronized (mPackages) {
17457                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17458            }
17459        }
17460
17461        @Override
17462        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17463            synchronized (mPackages) {
17464                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17465            }
17466        }
17467
17468        @Override
17469        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17470            synchronized (mPackages) {
17471                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17472            }
17473        }
17474
17475        @Override
17476        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17477            synchronized (mPackages) {
17478                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17479                        packageName, userId);
17480            }
17481        }
17482
17483        @Override
17484        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17485            synchronized (mPackages) {
17486                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17487                        packageName, userId);
17488            }
17489        }
17490
17491        @Override
17492        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17493            synchronized (mPackages) {
17494                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17495                        packageName, userId);
17496            }
17497        }
17498
17499        @Override
17500        public void setKeepUninstalledPackages(final List<String> packageList) {
17501            Preconditions.checkNotNull(packageList);
17502            List<String> removedFromList = null;
17503            synchronized (mPackages) {
17504                if (mKeepUninstalledPackages != null) {
17505                    final int packagesCount = mKeepUninstalledPackages.size();
17506                    for (int i = 0; i < packagesCount; i++) {
17507                        String oldPackage = mKeepUninstalledPackages.get(i);
17508                        if (packageList != null && packageList.contains(oldPackage)) {
17509                            continue;
17510                        }
17511                        if (removedFromList == null) {
17512                            removedFromList = new ArrayList<>();
17513                        }
17514                        removedFromList.add(oldPackage);
17515                    }
17516                }
17517                mKeepUninstalledPackages = new ArrayList<>(packageList);
17518                if (removedFromList != null) {
17519                    final int removedCount = removedFromList.size();
17520                    for (int i = 0; i < removedCount; i++) {
17521                        deletePackageIfUnusedLPr(removedFromList.get(i));
17522                    }
17523                }
17524            }
17525        }
17526
17527        @Override
17528        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17529            synchronized (mPackages) {
17530                // If we do not support permission review, done.
17531                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17532                    return false;
17533                }
17534
17535                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17536                if (packageSetting == null) {
17537                    return false;
17538                }
17539
17540                // Permission review applies only to apps not supporting the new permission model.
17541                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17542                    return false;
17543                }
17544
17545                // Legacy apps have the permission and get user consent on launch.
17546                PermissionsState permissionsState = packageSetting.getPermissionsState();
17547                return permissionsState.isPermissionReviewRequired(userId);
17548            }
17549        }
17550    }
17551
17552    @Override
17553    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17554        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17555        synchronized (mPackages) {
17556            final long identity = Binder.clearCallingIdentity();
17557            try {
17558                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17559                        packageNames, userId);
17560            } finally {
17561                Binder.restoreCallingIdentity(identity);
17562            }
17563        }
17564    }
17565
17566    private static void enforceSystemOrPhoneCaller(String tag) {
17567        int callingUid = Binder.getCallingUid();
17568        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17569            throw new SecurityException(
17570                    "Cannot call " + tag + " from UID " + callingUid);
17571        }
17572    }
17573}
17574