PackageManagerService.java revision 36a832dd128c18628783cc629b89b2ae399db4f8
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        // Ephemeral apps don't get the full verification treatment
10430        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10431            if (DEBUG_EPHEMERAL) {
10432                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10433            }
10434            return false;
10435        }
10436
10437        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10438
10439        // Check if installing from ADB
10440        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10441            // Do not run verification in a test harness environment
10442            if (ActivityManager.isRunningInTestHarness()) {
10443                return false;
10444            }
10445            if (ensureVerifyAppsEnabled) {
10446                return true;
10447            }
10448            // Check if the developer does not want package verification for ADB installs
10449            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10450                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10451                return false;
10452            }
10453        }
10454
10455        if (ensureVerifyAppsEnabled) {
10456            return true;
10457        }
10458
10459        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10460                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10461    }
10462
10463    @Override
10464    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10465            throws RemoteException {
10466        mContext.enforceCallingOrSelfPermission(
10467                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10468                "Only intentfilter verification agents can verify applications");
10469
10470        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10471        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10472                Binder.getCallingUid(), verificationCode, failedDomains);
10473        msg.arg1 = id;
10474        msg.obj = response;
10475        mHandler.sendMessage(msg);
10476    }
10477
10478    @Override
10479    public int getIntentVerificationStatus(String packageName, int userId) {
10480        synchronized (mPackages) {
10481            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10482        }
10483    }
10484
10485    @Override
10486    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10487        mContext.enforceCallingOrSelfPermission(
10488                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10489
10490        boolean result = false;
10491        synchronized (mPackages) {
10492            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10493        }
10494        if (result) {
10495            scheduleWritePackageRestrictionsLocked(userId);
10496        }
10497        return result;
10498    }
10499
10500    @Override
10501    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10502        synchronized (mPackages) {
10503            return mSettings.getIntentFilterVerificationsLPr(packageName);
10504        }
10505    }
10506
10507    @Override
10508    public List<IntentFilter> getAllIntentFilters(String packageName) {
10509        if (TextUtils.isEmpty(packageName)) {
10510            return Collections.<IntentFilter>emptyList();
10511        }
10512        synchronized (mPackages) {
10513            PackageParser.Package pkg = mPackages.get(packageName);
10514            if (pkg == null || pkg.activities == null) {
10515                return Collections.<IntentFilter>emptyList();
10516            }
10517            final int count = pkg.activities.size();
10518            ArrayList<IntentFilter> result = new ArrayList<>();
10519            for (int n=0; n<count; n++) {
10520                PackageParser.Activity activity = pkg.activities.get(n);
10521                if (activity.intents != null && activity.intents.size() > 0) {
10522                    result.addAll(activity.intents);
10523                }
10524            }
10525            return result;
10526        }
10527    }
10528
10529    @Override
10530    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10531        mContext.enforceCallingOrSelfPermission(
10532                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10533
10534        synchronized (mPackages) {
10535            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10536            if (packageName != null) {
10537                result |= updateIntentVerificationStatus(packageName,
10538                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10539                        userId);
10540                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10541                        packageName, userId);
10542            }
10543            return result;
10544        }
10545    }
10546
10547    @Override
10548    public String getDefaultBrowserPackageName(int userId) {
10549        synchronized (mPackages) {
10550            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10551        }
10552    }
10553
10554    /**
10555     * Get the "allow unknown sources" setting.
10556     *
10557     * @return the current "allow unknown sources" setting
10558     */
10559    private int getUnknownSourcesSettings() {
10560        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10561                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10562                -1);
10563    }
10564
10565    @Override
10566    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10567        final int uid = Binder.getCallingUid();
10568        // writer
10569        synchronized (mPackages) {
10570            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10571            if (targetPackageSetting == null) {
10572                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10573            }
10574
10575            PackageSetting installerPackageSetting;
10576            if (installerPackageName != null) {
10577                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10578                if (installerPackageSetting == null) {
10579                    throw new IllegalArgumentException("Unknown installer package: "
10580                            + installerPackageName);
10581                }
10582            } else {
10583                installerPackageSetting = null;
10584            }
10585
10586            Signature[] callerSignature;
10587            Object obj = mSettings.getUserIdLPr(uid);
10588            if (obj != null) {
10589                if (obj instanceof SharedUserSetting) {
10590                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10591                } else if (obj instanceof PackageSetting) {
10592                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10593                } else {
10594                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10595                }
10596            } else {
10597                throw new SecurityException("Unknown calling uid " + uid);
10598            }
10599
10600            // Verify: can't set installerPackageName to a package that is
10601            // not signed with the same cert as the caller.
10602            if (installerPackageSetting != null) {
10603                if (compareSignatures(callerSignature,
10604                        installerPackageSetting.signatures.mSignatures)
10605                        != PackageManager.SIGNATURE_MATCH) {
10606                    throw new SecurityException(
10607                            "Caller does not have same cert as new installer package "
10608                            + installerPackageName);
10609                }
10610            }
10611
10612            // Verify: if target already has an installer package, it must
10613            // be signed with the same cert as the caller.
10614            if (targetPackageSetting.installerPackageName != null) {
10615                PackageSetting setting = mSettings.mPackages.get(
10616                        targetPackageSetting.installerPackageName);
10617                // If the currently set package isn't valid, then it's always
10618                // okay to change it.
10619                if (setting != null) {
10620                    if (compareSignatures(callerSignature,
10621                            setting.signatures.mSignatures)
10622                            != PackageManager.SIGNATURE_MATCH) {
10623                        throw new SecurityException(
10624                                "Caller does not have same cert as old installer package "
10625                                + targetPackageSetting.installerPackageName);
10626                    }
10627                }
10628            }
10629
10630            // Okay!
10631            targetPackageSetting.installerPackageName = installerPackageName;
10632            scheduleWriteSettingsLocked();
10633        }
10634    }
10635
10636    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10637        // Queue up an async operation since the package installation may take a little while.
10638        mHandler.post(new Runnable() {
10639            public void run() {
10640                mHandler.removeCallbacks(this);
10641                 // Result object to be returned
10642                PackageInstalledInfo res = new PackageInstalledInfo();
10643                res.returnCode = currentStatus;
10644                res.uid = -1;
10645                res.pkg = null;
10646                res.removedInfo = new PackageRemovedInfo();
10647                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10648                    args.doPreInstall(res.returnCode);
10649                    synchronized (mInstallLock) {
10650                        installPackageTracedLI(args, res);
10651                    }
10652                    args.doPostInstall(res.returnCode, res.uid);
10653                }
10654
10655                // A restore should be performed at this point if (a) the install
10656                // succeeded, (b) the operation is not an update, and (c) the new
10657                // package has not opted out of backup participation.
10658                final boolean update = res.removedInfo.removedPackage != null;
10659                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10660                boolean doRestore = !update
10661                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10662
10663                // Set up the post-install work request bookkeeping.  This will be used
10664                // and cleaned up by the post-install event handling regardless of whether
10665                // there's a restore pass performed.  Token values are >= 1.
10666                int token;
10667                if (mNextInstallToken < 0) mNextInstallToken = 1;
10668                token = mNextInstallToken++;
10669
10670                PostInstallData data = new PostInstallData(args, res);
10671                mRunningInstalls.put(token, data);
10672                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10673
10674                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10675                    // Pass responsibility to the Backup Manager.  It will perform a
10676                    // restore if appropriate, then pass responsibility back to the
10677                    // Package Manager to run the post-install observer callbacks
10678                    // and broadcasts.
10679                    IBackupManager bm = IBackupManager.Stub.asInterface(
10680                            ServiceManager.getService(Context.BACKUP_SERVICE));
10681                    if (bm != null) {
10682                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10683                                + " to BM for possible restore");
10684                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10685                        try {
10686                            // TODO: http://b/22388012
10687                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10688                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10689                            } else {
10690                                doRestore = false;
10691                            }
10692                        } catch (RemoteException e) {
10693                            // can't happen; the backup manager is local
10694                        } catch (Exception e) {
10695                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10696                            doRestore = false;
10697                        }
10698                    } else {
10699                        Slog.e(TAG, "Backup Manager not found!");
10700                        doRestore = false;
10701                    }
10702                }
10703
10704                if (!doRestore) {
10705                    // No restore possible, or the Backup Manager was mysteriously not
10706                    // available -- just fire the post-install work request directly.
10707                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10708
10709                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10710
10711                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10712                    mHandler.sendMessage(msg);
10713                }
10714            }
10715        });
10716    }
10717
10718    private abstract class HandlerParams {
10719        private static final int MAX_RETRIES = 4;
10720
10721        /**
10722         * Number of times startCopy() has been attempted and had a non-fatal
10723         * error.
10724         */
10725        private int mRetries = 0;
10726
10727        /** User handle for the user requesting the information or installation. */
10728        private final UserHandle mUser;
10729        String traceMethod;
10730        int traceCookie;
10731
10732        HandlerParams(UserHandle user) {
10733            mUser = user;
10734        }
10735
10736        UserHandle getUser() {
10737            return mUser;
10738        }
10739
10740        HandlerParams setTraceMethod(String traceMethod) {
10741            this.traceMethod = traceMethod;
10742            return this;
10743        }
10744
10745        HandlerParams setTraceCookie(int traceCookie) {
10746            this.traceCookie = traceCookie;
10747            return this;
10748        }
10749
10750        final boolean startCopy() {
10751            boolean res;
10752            try {
10753                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10754
10755                if (++mRetries > MAX_RETRIES) {
10756                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10757                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10758                    handleServiceError();
10759                    return false;
10760                } else {
10761                    handleStartCopy();
10762                    res = true;
10763                }
10764            } catch (RemoteException e) {
10765                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10766                mHandler.sendEmptyMessage(MCS_RECONNECT);
10767                res = false;
10768            }
10769            handleReturnCode();
10770            return res;
10771        }
10772
10773        final void serviceError() {
10774            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10775            handleServiceError();
10776            handleReturnCode();
10777        }
10778
10779        abstract void handleStartCopy() throws RemoteException;
10780        abstract void handleServiceError();
10781        abstract void handleReturnCode();
10782    }
10783
10784    class MeasureParams extends HandlerParams {
10785        private final PackageStats mStats;
10786        private boolean mSuccess;
10787
10788        private final IPackageStatsObserver mObserver;
10789
10790        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10791            super(new UserHandle(stats.userHandle));
10792            mObserver = observer;
10793            mStats = stats;
10794        }
10795
10796        @Override
10797        public String toString() {
10798            return "MeasureParams{"
10799                + Integer.toHexString(System.identityHashCode(this))
10800                + " " + mStats.packageName + "}";
10801        }
10802
10803        @Override
10804        void handleStartCopy() throws RemoteException {
10805            synchronized (mInstallLock) {
10806                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10807            }
10808
10809            if (mSuccess) {
10810                final boolean mounted;
10811                if (Environment.isExternalStorageEmulated()) {
10812                    mounted = true;
10813                } else {
10814                    final String status = Environment.getExternalStorageState();
10815                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10816                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10817                }
10818
10819                if (mounted) {
10820                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10821
10822                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10823                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10824
10825                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10826                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10827
10828                    // Always subtract cache size, since it's a subdirectory
10829                    mStats.externalDataSize -= mStats.externalCacheSize;
10830
10831                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10832                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10833
10834                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10835                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10836                }
10837            }
10838        }
10839
10840        @Override
10841        void handleReturnCode() {
10842            if (mObserver != null) {
10843                try {
10844                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10845                } catch (RemoteException e) {
10846                    Slog.i(TAG, "Observer no longer exists.");
10847                }
10848            }
10849        }
10850
10851        @Override
10852        void handleServiceError() {
10853            Slog.e(TAG, "Could not measure application " + mStats.packageName
10854                            + " external storage");
10855        }
10856    }
10857
10858    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10859            throws RemoteException {
10860        long result = 0;
10861        for (File path : paths) {
10862            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10863        }
10864        return result;
10865    }
10866
10867    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10868        for (File path : paths) {
10869            try {
10870                mcs.clearDirectory(path.getAbsolutePath());
10871            } catch (RemoteException e) {
10872            }
10873        }
10874    }
10875
10876    static class OriginInfo {
10877        /**
10878         * Location where install is coming from, before it has been
10879         * copied/renamed into place. This could be a single monolithic APK
10880         * file, or a cluster directory. This location may be untrusted.
10881         */
10882        final File file;
10883        final String cid;
10884
10885        /**
10886         * Flag indicating that {@link #file} or {@link #cid} has already been
10887         * staged, meaning downstream users don't need to defensively copy the
10888         * contents.
10889         */
10890        final boolean staged;
10891
10892        /**
10893         * Flag indicating that {@link #file} or {@link #cid} is an already
10894         * installed app that is being moved.
10895         */
10896        final boolean existing;
10897
10898        final String resolvedPath;
10899        final File resolvedFile;
10900
10901        static OriginInfo fromNothing() {
10902            return new OriginInfo(null, null, false, false);
10903        }
10904
10905        static OriginInfo fromUntrustedFile(File file) {
10906            return new OriginInfo(file, null, false, false);
10907        }
10908
10909        static OriginInfo fromExistingFile(File file) {
10910            return new OriginInfo(file, null, false, true);
10911        }
10912
10913        static OriginInfo fromStagedFile(File file) {
10914            return new OriginInfo(file, null, true, false);
10915        }
10916
10917        static OriginInfo fromStagedContainer(String cid) {
10918            return new OriginInfo(null, cid, true, false);
10919        }
10920
10921        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10922            this.file = file;
10923            this.cid = cid;
10924            this.staged = staged;
10925            this.existing = existing;
10926
10927            if (cid != null) {
10928                resolvedPath = PackageHelper.getSdDir(cid);
10929                resolvedFile = new File(resolvedPath);
10930            } else if (file != null) {
10931                resolvedPath = file.getAbsolutePath();
10932                resolvedFile = file;
10933            } else {
10934                resolvedPath = null;
10935                resolvedFile = null;
10936            }
10937        }
10938    }
10939
10940    static class MoveInfo {
10941        final int moveId;
10942        final String fromUuid;
10943        final String toUuid;
10944        final String packageName;
10945        final String dataAppName;
10946        final int appId;
10947        final String seinfo;
10948
10949        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10950                String dataAppName, int appId, String seinfo) {
10951            this.moveId = moveId;
10952            this.fromUuid = fromUuid;
10953            this.toUuid = toUuid;
10954            this.packageName = packageName;
10955            this.dataAppName = dataAppName;
10956            this.appId = appId;
10957            this.seinfo = seinfo;
10958        }
10959    }
10960
10961    class InstallParams extends HandlerParams {
10962        final OriginInfo origin;
10963        final MoveInfo move;
10964        final IPackageInstallObserver2 observer;
10965        int installFlags;
10966        final String installerPackageName;
10967        final String volumeUuid;
10968        final VerificationParams verificationParams;
10969        private InstallArgs mArgs;
10970        private int mRet;
10971        final String packageAbiOverride;
10972        final String[] grantedRuntimePermissions;
10973
10974        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10975                int installFlags, String installerPackageName, String volumeUuid,
10976                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10977                String[] grantedPermissions) {
10978            super(user);
10979            this.origin = origin;
10980            this.move = move;
10981            this.observer = observer;
10982            this.installFlags = installFlags;
10983            this.installerPackageName = installerPackageName;
10984            this.volumeUuid = volumeUuid;
10985            this.verificationParams = verificationParams;
10986            this.packageAbiOverride = packageAbiOverride;
10987            this.grantedRuntimePermissions = grantedPermissions;
10988        }
10989
10990        @Override
10991        public String toString() {
10992            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10993                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10994        }
10995
10996        public ManifestDigest getManifestDigest() {
10997            if (verificationParams == null) {
10998                return null;
10999            }
11000            return verificationParams.getManifestDigest();
11001        }
11002
11003        private int installLocationPolicy(PackageInfoLite pkgLite) {
11004            String packageName = pkgLite.packageName;
11005            int installLocation = pkgLite.installLocation;
11006            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11007            // reader
11008            synchronized (mPackages) {
11009                PackageParser.Package pkg = mPackages.get(packageName);
11010                if (pkg != null) {
11011                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11012                        // Check for downgrading.
11013                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11014                            try {
11015                                checkDowngrade(pkg, pkgLite);
11016                            } catch (PackageManagerException e) {
11017                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11018                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11019                            }
11020                        }
11021                        // Check for updated system application.
11022                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11023                            if (onSd) {
11024                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11025                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11026                            }
11027                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11028                        } else {
11029                            if (onSd) {
11030                                // Install flag overrides everything.
11031                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11032                            }
11033                            // If current upgrade specifies particular preference
11034                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11035                                // Application explicitly specified internal.
11036                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11037                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11038                                // App explictly prefers external. Let policy decide
11039                            } else {
11040                                // Prefer previous location
11041                                if (isExternal(pkg)) {
11042                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11043                                }
11044                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11045                            }
11046                        }
11047                    } else {
11048                        // Invalid install. Return error code
11049                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11050                    }
11051                }
11052            }
11053            // All the special cases have been taken care of.
11054            // Return result based on recommended install location.
11055            if (onSd) {
11056                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11057            }
11058            return pkgLite.recommendedInstallLocation;
11059        }
11060
11061        /*
11062         * Invoke remote method to get package information and install
11063         * location values. Override install location based on default
11064         * policy if needed and then create install arguments based
11065         * on the install location.
11066         */
11067        public void handleStartCopy() throws RemoteException {
11068            int ret = PackageManager.INSTALL_SUCCEEDED;
11069
11070            // If we're already staged, we've firmly committed to an install location
11071            if (origin.staged) {
11072                if (origin.file != null) {
11073                    installFlags |= PackageManager.INSTALL_INTERNAL;
11074                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11075                } else if (origin.cid != null) {
11076                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11077                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11078                } else {
11079                    throw new IllegalStateException("Invalid stage location");
11080                }
11081            }
11082
11083            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11084            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11085            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11086            PackageInfoLite pkgLite = null;
11087
11088            if (onInt && onSd) {
11089                // Check if both bits are set.
11090                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11091                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11092            } else if (onSd && ephemeral) {
11093                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11094                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11095            } else {
11096                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11097                        packageAbiOverride);
11098
11099                if (DEBUG_EPHEMERAL && ephemeral) {
11100                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11101                }
11102
11103                /*
11104                 * If we have too little free space, try to free cache
11105                 * before giving up.
11106                 */
11107                if (!origin.staged && pkgLite.recommendedInstallLocation
11108                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11109                    // TODO: focus freeing disk space on the target device
11110                    final StorageManager storage = StorageManager.from(mContext);
11111                    final long lowThreshold = storage.getStorageLowBytes(
11112                            Environment.getDataDirectory());
11113
11114                    final long sizeBytes = mContainerService.calculateInstalledSize(
11115                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11116
11117                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11118                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11119                                installFlags, packageAbiOverride);
11120                    }
11121
11122                    /*
11123                     * The cache free must have deleted the file we
11124                     * downloaded to install.
11125                     *
11126                     * TODO: fix the "freeCache" call to not delete
11127                     *       the file we care about.
11128                     */
11129                    if (pkgLite.recommendedInstallLocation
11130                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11131                        pkgLite.recommendedInstallLocation
11132                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11133                    }
11134                }
11135            }
11136
11137            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11138                int loc = pkgLite.recommendedInstallLocation;
11139                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11140                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11141                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11142                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11143                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11144                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11145                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11146                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11147                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11148                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11149                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11150                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11151                } else {
11152                    // Override with defaults if needed.
11153                    loc = installLocationPolicy(pkgLite);
11154                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11155                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11156                    } else if (!onSd && !onInt) {
11157                        // Override install location with flags
11158                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11159                            // Set the flag to install on external media.
11160                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11161                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11162                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11163                            if (DEBUG_EPHEMERAL) {
11164                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11165                            }
11166                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11167                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11168                                    |PackageManager.INSTALL_INTERNAL);
11169                        } else {
11170                            // Make sure the flag for installing on external
11171                            // media is unset
11172                            installFlags |= PackageManager.INSTALL_INTERNAL;
11173                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11174                        }
11175                    }
11176                }
11177            }
11178
11179            final InstallArgs args = createInstallArgs(this);
11180            mArgs = args;
11181
11182            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11183                // TODO: http://b/22976637
11184                // Apps installed for "all" users use the device owner to verify the app
11185                UserHandle verifierUser = getUser();
11186                if (verifierUser == UserHandle.ALL) {
11187                    verifierUser = UserHandle.SYSTEM;
11188                }
11189
11190                /*
11191                 * Determine if we have any installed package verifiers. If we
11192                 * do, then we'll defer to them to verify the packages.
11193                 */
11194                final int requiredUid = mRequiredVerifierPackage == null ? -1
11195                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11196                if (!origin.existing && requiredUid != -1
11197                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11198                    final Intent verification = new Intent(
11199                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11200                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11201                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11202                            PACKAGE_MIME_TYPE);
11203                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11204
11205                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11206                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11207                            verifierUser.getIdentifier());
11208
11209                    if (DEBUG_VERIFY) {
11210                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11211                                + verification.toString() + " with " + pkgLite.verifiers.length
11212                                + " optional verifiers");
11213                    }
11214
11215                    final int verificationId = mPendingVerificationToken++;
11216
11217                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11218
11219                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11220                            installerPackageName);
11221
11222                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11223                            installFlags);
11224
11225                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11226                            pkgLite.packageName);
11227
11228                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11229                            pkgLite.versionCode);
11230
11231                    if (verificationParams != null) {
11232                        if (verificationParams.getVerificationURI() != null) {
11233                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11234                                 verificationParams.getVerificationURI());
11235                        }
11236                        if (verificationParams.getOriginatingURI() != null) {
11237                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11238                                  verificationParams.getOriginatingURI());
11239                        }
11240                        if (verificationParams.getReferrer() != null) {
11241                            verification.putExtra(Intent.EXTRA_REFERRER,
11242                                  verificationParams.getReferrer());
11243                        }
11244                        if (verificationParams.getOriginatingUid() >= 0) {
11245                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11246                                  verificationParams.getOriginatingUid());
11247                        }
11248                        if (verificationParams.getInstallerUid() >= 0) {
11249                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11250                                  verificationParams.getInstallerUid());
11251                        }
11252                    }
11253
11254                    final PackageVerificationState verificationState = new PackageVerificationState(
11255                            requiredUid, args);
11256
11257                    mPendingVerification.append(verificationId, verificationState);
11258
11259                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11260                            receivers, verificationState);
11261
11262                    /*
11263                     * If any sufficient verifiers were listed in the package
11264                     * manifest, attempt to ask them.
11265                     */
11266                    if (sufficientVerifiers != null) {
11267                        final int N = sufficientVerifiers.size();
11268                        if (N == 0) {
11269                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11270                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11271                        } else {
11272                            for (int i = 0; i < N; i++) {
11273                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11274
11275                                final Intent sufficientIntent = new Intent(verification);
11276                                sufficientIntent.setComponent(verifierComponent);
11277                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11278                            }
11279                        }
11280                    }
11281
11282                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11283                            mRequiredVerifierPackage, receivers);
11284                    if (ret == PackageManager.INSTALL_SUCCEEDED
11285                            && mRequiredVerifierPackage != null) {
11286                        Trace.asyncTraceBegin(
11287                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11288                        /*
11289                         * Send the intent to the required verification agent,
11290                         * but only start the verification timeout after the
11291                         * target BroadcastReceivers have run.
11292                         */
11293                        verification.setComponent(requiredVerifierComponent);
11294                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11295                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11296                                new BroadcastReceiver() {
11297                                    @Override
11298                                    public void onReceive(Context context, Intent intent) {
11299                                        final Message msg = mHandler
11300                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11301                                        msg.arg1 = verificationId;
11302                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11303                                    }
11304                                }, null, 0, null, null);
11305
11306                        /*
11307                         * We don't want the copy to proceed until verification
11308                         * succeeds, so null out this field.
11309                         */
11310                        mArgs = null;
11311                    }
11312                } else {
11313                    /*
11314                     * No package verification is enabled, so immediately start
11315                     * the remote call to initiate copy using temporary file.
11316                     */
11317                    ret = args.copyApk(mContainerService, true);
11318                }
11319            }
11320
11321            mRet = ret;
11322        }
11323
11324        @Override
11325        void handleReturnCode() {
11326            // If mArgs is null, then MCS couldn't be reached. When it
11327            // reconnects, it will try again to install. At that point, this
11328            // will succeed.
11329            if (mArgs != null) {
11330                processPendingInstall(mArgs, mRet);
11331            }
11332        }
11333
11334        @Override
11335        void handleServiceError() {
11336            mArgs = createInstallArgs(this);
11337            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11338        }
11339
11340        public boolean isForwardLocked() {
11341            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11342        }
11343    }
11344
11345    /**
11346     * Used during creation of InstallArgs
11347     *
11348     * @param installFlags package installation flags
11349     * @return true if should be installed on external storage
11350     */
11351    private static boolean installOnExternalAsec(int installFlags) {
11352        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11353            return false;
11354        }
11355        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11356            return true;
11357        }
11358        return false;
11359    }
11360
11361    /**
11362     * Used during creation of InstallArgs
11363     *
11364     * @param installFlags package installation flags
11365     * @return true if should be installed as forward locked
11366     */
11367    private static boolean installForwardLocked(int installFlags) {
11368        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11369    }
11370
11371    private InstallArgs createInstallArgs(InstallParams params) {
11372        if (params.move != null) {
11373            return new MoveInstallArgs(params);
11374        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11375            return new AsecInstallArgs(params);
11376        } else {
11377            return new FileInstallArgs(params);
11378        }
11379    }
11380
11381    /**
11382     * Create args that describe an existing installed package. Typically used
11383     * when cleaning up old installs, or used as a move source.
11384     */
11385    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11386            String resourcePath, String[] instructionSets) {
11387        final boolean isInAsec;
11388        if (installOnExternalAsec(installFlags)) {
11389            /* Apps on SD card are always in ASEC containers. */
11390            isInAsec = true;
11391        } else if (installForwardLocked(installFlags)
11392                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11393            /*
11394             * Forward-locked apps are only in ASEC containers if they're the
11395             * new style
11396             */
11397            isInAsec = true;
11398        } else {
11399            isInAsec = false;
11400        }
11401
11402        if (isInAsec) {
11403            return new AsecInstallArgs(codePath, instructionSets,
11404                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11405        } else {
11406            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11407        }
11408    }
11409
11410    static abstract class InstallArgs {
11411        /** @see InstallParams#origin */
11412        final OriginInfo origin;
11413        /** @see InstallParams#move */
11414        final MoveInfo move;
11415
11416        final IPackageInstallObserver2 observer;
11417        // Always refers to PackageManager flags only
11418        final int installFlags;
11419        final String installerPackageName;
11420        final String volumeUuid;
11421        final ManifestDigest manifestDigest;
11422        final UserHandle user;
11423        final String abiOverride;
11424        final String[] installGrantPermissions;
11425        /** If non-null, drop an async trace when the install completes */
11426        final String traceMethod;
11427        final int traceCookie;
11428
11429        // The list of instruction sets supported by this app. This is currently
11430        // only used during the rmdex() phase to clean up resources. We can get rid of this
11431        // if we move dex files under the common app path.
11432        /* nullable */ String[] instructionSets;
11433
11434        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11435                int installFlags, String installerPackageName, String volumeUuid,
11436                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11437                String abiOverride, String[] installGrantPermissions,
11438                String traceMethod, int traceCookie) {
11439            this.origin = origin;
11440            this.move = move;
11441            this.installFlags = installFlags;
11442            this.observer = observer;
11443            this.installerPackageName = installerPackageName;
11444            this.volumeUuid = volumeUuid;
11445            this.manifestDigest = manifestDigest;
11446            this.user = user;
11447            this.instructionSets = instructionSets;
11448            this.abiOverride = abiOverride;
11449            this.installGrantPermissions = installGrantPermissions;
11450            this.traceMethod = traceMethod;
11451            this.traceCookie = traceCookie;
11452        }
11453
11454        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11455        abstract int doPreInstall(int status);
11456
11457        /**
11458         * Rename package into final resting place. All paths on the given
11459         * scanned package should be updated to reflect the rename.
11460         */
11461        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11462        abstract int doPostInstall(int status, int uid);
11463
11464        /** @see PackageSettingBase#codePathString */
11465        abstract String getCodePath();
11466        /** @see PackageSettingBase#resourcePathString */
11467        abstract String getResourcePath();
11468
11469        // Need installer lock especially for dex file removal.
11470        abstract void cleanUpResourcesLI();
11471        abstract boolean doPostDeleteLI(boolean delete);
11472
11473        /**
11474         * Called before the source arguments are copied. This is used mostly
11475         * for MoveParams when it needs to read the source file to put it in the
11476         * destination.
11477         */
11478        int doPreCopy() {
11479            return PackageManager.INSTALL_SUCCEEDED;
11480        }
11481
11482        /**
11483         * Called after the source arguments are copied. This is used mostly for
11484         * MoveParams when it needs to read the source file to put it in the
11485         * destination.
11486         *
11487         * @return
11488         */
11489        int doPostCopy(int uid) {
11490            return PackageManager.INSTALL_SUCCEEDED;
11491        }
11492
11493        protected boolean isFwdLocked() {
11494            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11495        }
11496
11497        protected boolean isExternalAsec() {
11498            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11499        }
11500
11501        protected boolean isEphemeral() {
11502            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11503        }
11504
11505        UserHandle getUser() {
11506            return user;
11507        }
11508    }
11509
11510    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11511        if (!allCodePaths.isEmpty()) {
11512            if (instructionSets == null) {
11513                throw new IllegalStateException("instructionSet == null");
11514            }
11515            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11516            for (String codePath : allCodePaths) {
11517                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11518                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11519                    if (retCode < 0) {
11520                        Slog.w(TAG, "Couldn't remove dex file for package: "
11521                                + " at location " + codePath + ", retcode=" + retCode);
11522                        // we don't consider this to be a failure of the core package deletion
11523                    }
11524                }
11525            }
11526        }
11527    }
11528
11529    /**
11530     * Logic to handle installation of non-ASEC applications, including copying
11531     * and renaming logic.
11532     */
11533    class FileInstallArgs extends InstallArgs {
11534        private File codeFile;
11535        private File resourceFile;
11536
11537        // Example topology:
11538        // /data/app/com.example/base.apk
11539        // /data/app/com.example/split_foo.apk
11540        // /data/app/com.example/lib/arm/libfoo.so
11541        // /data/app/com.example/lib/arm64/libfoo.so
11542        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11543
11544        /** New install */
11545        FileInstallArgs(InstallParams params) {
11546            super(params.origin, params.move, params.observer, params.installFlags,
11547                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11548                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11549                    params.grantedRuntimePermissions,
11550                    params.traceMethod, params.traceCookie);
11551            if (isFwdLocked()) {
11552                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11553            }
11554        }
11555
11556        /** Existing install */
11557        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11558            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11559                    null, null, null, 0);
11560            this.codeFile = (codePath != null) ? new File(codePath) : null;
11561            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11562        }
11563
11564        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11565            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11566            try {
11567                return doCopyApk(imcs, temp);
11568            } finally {
11569                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11570            }
11571        }
11572
11573        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11574            if (origin.staged) {
11575                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11576                codeFile = origin.file;
11577                resourceFile = origin.file;
11578                return PackageManager.INSTALL_SUCCEEDED;
11579            }
11580
11581            try {
11582                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11583                final File tempDir =
11584                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11585                codeFile = tempDir;
11586                resourceFile = tempDir;
11587            } catch (IOException e) {
11588                Slog.w(TAG, "Failed to create copy file: " + e);
11589                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11590            }
11591
11592            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11593                @Override
11594                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11595                    if (!FileUtils.isValidExtFilename(name)) {
11596                        throw new IllegalArgumentException("Invalid filename: " + name);
11597                    }
11598                    try {
11599                        final File file = new File(codeFile, name);
11600                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11601                                O_RDWR | O_CREAT, 0644);
11602                        Os.chmod(file.getAbsolutePath(), 0644);
11603                        return new ParcelFileDescriptor(fd);
11604                    } catch (ErrnoException e) {
11605                        throw new RemoteException("Failed to open: " + e.getMessage());
11606                    }
11607                }
11608            };
11609
11610            int ret = PackageManager.INSTALL_SUCCEEDED;
11611            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11612            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11613                Slog.e(TAG, "Failed to copy package");
11614                return ret;
11615            }
11616
11617            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11618            NativeLibraryHelper.Handle handle = null;
11619            try {
11620                handle = NativeLibraryHelper.Handle.create(codeFile);
11621                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11622                        abiOverride);
11623            } catch (IOException e) {
11624                Slog.e(TAG, "Copying native libraries failed", e);
11625                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11626            } finally {
11627                IoUtils.closeQuietly(handle);
11628            }
11629
11630            return ret;
11631        }
11632
11633        int doPreInstall(int status) {
11634            if (status != PackageManager.INSTALL_SUCCEEDED) {
11635                cleanUp();
11636            }
11637            return status;
11638        }
11639
11640        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11641            if (status != PackageManager.INSTALL_SUCCEEDED) {
11642                cleanUp();
11643                return false;
11644            }
11645
11646            final File targetDir = codeFile.getParentFile();
11647            final File beforeCodeFile = codeFile;
11648            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11649
11650            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11651            try {
11652                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11653            } catch (ErrnoException e) {
11654                Slog.w(TAG, "Failed to rename", e);
11655                return false;
11656            }
11657
11658            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11659                Slog.w(TAG, "Failed to restorecon");
11660                return false;
11661            }
11662
11663            // Reflect the rename internally
11664            codeFile = afterCodeFile;
11665            resourceFile = afterCodeFile;
11666
11667            // Reflect the rename in scanned details
11668            pkg.codePath = afterCodeFile.getAbsolutePath();
11669            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11670                    pkg.baseCodePath);
11671            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11672                    pkg.splitCodePaths);
11673
11674            // Reflect the rename in app info
11675            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11676            pkg.applicationInfo.setCodePath(pkg.codePath);
11677            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11678            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11679            pkg.applicationInfo.setResourcePath(pkg.codePath);
11680            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11681            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11682
11683            return true;
11684        }
11685
11686        int doPostInstall(int status, int uid) {
11687            if (status != PackageManager.INSTALL_SUCCEEDED) {
11688                cleanUp();
11689            }
11690            return status;
11691        }
11692
11693        @Override
11694        String getCodePath() {
11695            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11696        }
11697
11698        @Override
11699        String getResourcePath() {
11700            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11701        }
11702
11703        private boolean cleanUp() {
11704            if (codeFile == null || !codeFile.exists()) {
11705                return false;
11706            }
11707
11708            if (codeFile.isDirectory()) {
11709                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11710            } else {
11711                codeFile.delete();
11712            }
11713
11714            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11715                resourceFile.delete();
11716            }
11717
11718            return true;
11719        }
11720
11721        void cleanUpResourcesLI() {
11722            // Try enumerating all code paths before deleting
11723            List<String> allCodePaths = Collections.EMPTY_LIST;
11724            if (codeFile != null && codeFile.exists()) {
11725                try {
11726                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11727                    allCodePaths = pkg.getAllCodePaths();
11728                } catch (PackageParserException e) {
11729                    // Ignored; we tried our best
11730                }
11731            }
11732
11733            cleanUp();
11734            removeDexFiles(allCodePaths, instructionSets);
11735        }
11736
11737        boolean doPostDeleteLI(boolean delete) {
11738            // XXX err, shouldn't we respect the delete flag?
11739            cleanUpResourcesLI();
11740            return true;
11741        }
11742    }
11743
11744    private boolean isAsecExternal(String cid) {
11745        final String asecPath = PackageHelper.getSdFilesystem(cid);
11746        return !asecPath.startsWith(mAsecInternalPath);
11747    }
11748
11749    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11750            PackageManagerException {
11751        if (copyRet < 0) {
11752            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11753                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11754                throw new PackageManagerException(copyRet, message);
11755            }
11756        }
11757    }
11758
11759    /**
11760     * Extract the MountService "container ID" from the full code path of an
11761     * .apk.
11762     */
11763    static String cidFromCodePath(String fullCodePath) {
11764        int eidx = fullCodePath.lastIndexOf("/");
11765        String subStr1 = fullCodePath.substring(0, eidx);
11766        int sidx = subStr1.lastIndexOf("/");
11767        return subStr1.substring(sidx+1, eidx);
11768    }
11769
11770    /**
11771     * Logic to handle installation of ASEC applications, including copying and
11772     * renaming logic.
11773     */
11774    class AsecInstallArgs extends InstallArgs {
11775        static final String RES_FILE_NAME = "pkg.apk";
11776        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11777
11778        String cid;
11779        String packagePath;
11780        String resourcePath;
11781
11782        /** New install */
11783        AsecInstallArgs(InstallParams params) {
11784            super(params.origin, params.move, params.observer, params.installFlags,
11785                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11786                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11787                    params.grantedRuntimePermissions,
11788                    params.traceMethod, params.traceCookie);
11789        }
11790
11791        /** Existing install */
11792        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11793                        boolean isExternal, boolean isForwardLocked) {
11794            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11795                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11796                    instructionSets, null, null, null, 0);
11797            // Hackily pretend we're still looking at a full code path
11798            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11799                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11800            }
11801
11802            // Extract cid from fullCodePath
11803            int eidx = fullCodePath.lastIndexOf("/");
11804            String subStr1 = fullCodePath.substring(0, eidx);
11805            int sidx = subStr1.lastIndexOf("/");
11806            cid = subStr1.substring(sidx+1, eidx);
11807            setMountPath(subStr1);
11808        }
11809
11810        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11811            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11812                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11813                    instructionSets, null, null, null, 0);
11814            this.cid = cid;
11815            setMountPath(PackageHelper.getSdDir(cid));
11816        }
11817
11818        void createCopyFile() {
11819            cid = mInstallerService.allocateExternalStageCidLegacy();
11820        }
11821
11822        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11823            if (origin.staged && origin.cid != null) {
11824                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11825                cid = origin.cid;
11826                setMountPath(PackageHelper.getSdDir(cid));
11827                return PackageManager.INSTALL_SUCCEEDED;
11828            }
11829
11830            if (temp) {
11831                createCopyFile();
11832            } else {
11833                /*
11834                 * Pre-emptively destroy the container since it's destroyed if
11835                 * copying fails due to it existing anyway.
11836                 */
11837                PackageHelper.destroySdDir(cid);
11838            }
11839
11840            final String newMountPath = imcs.copyPackageToContainer(
11841                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11842                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11843
11844            if (newMountPath != null) {
11845                setMountPath(newMountPath);
11846                return PackageManager.INSTALL_SUCCEEDED;
11847            } else {
11848                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11849            }
11850        }
11851
11852        @Override
11853        String getCodePath() {
11854            return packagePath;
11855        }
11856
11857        @Override
11858        String getResourcePath() {
11859            return resourcePath;
11860        }
11861
11862        int doPreInstall(int status) {
11863            if (status != PackageManager.INSTALL_SUCCEEDED) {
11864                // Destroy container
11865                PackageHelper.destroySdDir(cid);
11866            } else {
11867                boolean mounted = PackageHelper.isContainerMounted(cid);
11868                if (!mounted) {
11869                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11870                            Process.SYSTEM_UID);
11871                    if (newMountPath != null) {
11872                        setMountPath(newMountPath);
11873                    } else {
11874                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11875                    }
11876                }
11877            }
11878            return status;
11879        }
11880
11881        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11882            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11883            String newMountPath = null;
11884            if (PackageHelper.isContainerMounted(cid)) {
11885                // Unmount the container
11886                if (!PackageHelper.unMountSdDir(cid)) {
11887                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11888                    return false;
11889                }
11890            }
11891            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11892                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11893                        " which might be stale. Will try to clean up.");
11894                // Clean up the stale container and proceed to recreate.
11895                if (!PackageHelper.destroySdDir(newCacheId)) {
11896                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11897                    return false;
11898                }
11899                // Successfully cleaned up stale container. Try to rename again.
11900                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11901                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11902                            + " inspite of cleaning it up.");
11903                    return false;
11904                }
11905            }
11906            if (!PackageHelper.isContainerMounted(newCacheId)) {
11907                Slog.w(TAG, "Mounting container " + newCacheId);
11908                newMountPath = PackageHelper.mountSdDir(newCacheId,
11909                        getEncryptKey(), Process.SYSTEM_UID);
11910            } else {
11911                newMountPath = PackageHelper.getSdDir(newCacheId);
11912            }
11913            if (newMountPath == null) {
11914                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11915                return false;
11916            }
11917            Log.i(TAG, "Succesfully renamed " + cid +
11918                    " to " + newCacheId +
11919                    " at new path: " + newMountPath);
11920            cid = newCacheId;
11921
11922            final File beforeCodeFile = new File(packagePath);
11923            setMountPath(newMountPath);
11924            final File afterCodeFile = new File(packagePath);
11925
11926            // Reflect the rename in scanned details
11927            pkg.codePath = afterCodeFile.getAbsolutePath();
11928            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11929                    pkg.baseCodePath);
11930            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11931                    pkg.splitCodePaths);
11932
11933            // Reflect the rename in app info
11934            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11935            pkg.applicationInfo.setCodePath(pkg.codePath);
11936            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11937            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11938            pkg.applicationInfo.setResourcePath(pkg.codePath);
11939            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11940            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11941
11942            return true;
11943        }
11944
11945        private void setMountPath(String mountPath) {
11946            final File mountFile = new File(mountPath);
11947
11948            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11949            if (monolithicFile.exists()) {
11950                packagePath = monolithicFile.getAbsolutePath();
11951                if (isFwdLocked()) {
11952                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11953                } else {
11954                    resourcePath = packagePath;
11955                }
11956            } else {
11957                packagePath = mountFile.getAbsolutePath();
11958                resourcePath = packagePath;
11959            }
11960        }
11961
11962        int doPostInstall(int status, int uid) {
11963            if (status != PackageManager.INSTALL_SUCCEEDED) {
11964                cleanUp();
11965            } else {
11966                final int groupOwner;
11967                final String protectedFile;
11968                if (isFwdLocked()) {
11969                    groupOwner = UserHandle.getSharedAppGid(uid);
11970                    protectedFile = RES_FILE_NAME;
11971                } else {
11972                    groupOwner = -1;
11973                    protectedFile = null;
11974                }
11975
11976                if (uid < Process.FIRST_APPLICATION_UID
11977                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11978                    Slog.e(TAG, "Failed to finalize " + cid);
11979                    PackageHelper.destroySdDir(cid);
11980                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11981                }
11982
11983                boolean mounted = PackageHelper.isContainerMounted(cid);
11984                if (!mounted) {
11985                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11986                }
11987            }
11988            return status;
11989        }
11990
11991        private void cleanUp() {
11992            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11993
11994            // Destroy secure container
11995            PackageHelper.destroySdDir(cid);
11996        }
11997
11998        private List<String> getAllCodePaths() {
11999            final File codeFile = new File(getCodePath());
12000            if (codeFile != null && codeFile.exists()) {
12001                try {
12002                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12003                    return pkg.getAllCodePaths();
12004                } catch (PackageParserException e) {
12005                    // Ignored; we tried our best
12006                }
12007            }
12008            return Collections.EMPTY_LIST;
12009        }
12010
12011        void cleanUpResourcesLI() {
12012            // Enumerate all code paths before deleting
12013            cleanUpResourcesLI(getAllCodePaths());
12014        }
12015
12016        private void cleanUpResourcesLI(List<String> allCodePaths) {
12017            cleanUp();
12018            removeDexFiles(allCodePaths, instructionSets);
12019        }
12020
12021        String getPackageName() {
12022            return getAsecPackageName(cid);
12023        }
12024
12025        boolean doPostDeleteLI(boolean delete) {
12026            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12027            final List<String> allCodePaths = getAllCodePaths();
12028            boolean mounted = PackageHelper.isContainerMounted(cid);
12029            if (mounted) {
12030                // Unmount first
12031                if (PackageHelper.unMountSdDir(cid)) {
12032                    mounted = false;
12033                }
12034            }
12035            if (!mounted && delete) {
12036                cleanUpResourcesLI(allCodePaths);
12037            }
12038            return !mounted;
12039        }
12040
12041        @Override
12042        int doPreCopy() {
12043            if (isFwdLocked()) {
12044                if (!PackageHelper.fixSdPermissions(cid,
12045                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12046                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12047                }
12048            }
12049
12050            return PackageManager.INSTALL_SUCCEEDED;
12051        }
12052
12053        @Override
12054        int doPostCopy(int uid) {
12055            if (isFwdLocked()) {
12056                if (uid < Process.FIRST_APPLICATION_UID
12057                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12058                                RES_FILE_NAME)) {
12059                    Slog.e(TAG, "Failed to finalize " + cid);
12060                    PackageHelper.destroySdDir(cid);
12061                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12062                }
12063            }
12064
12065            return PackageManager.INSTALL_SUCCEEDED;
12066        }
12067    }
12068
12069    /**
12070     * Logic to handle movement of existing installed applications.
12071     */
12072    class MoveInstallArgs extends InstallArgs {
12073        private File codeFile;
12074        private File resourceFile;
12075
12076        /** New install */
12077        MoveInstallArgs(InstallParams params) {
12078            super(params.origin, params.move, params.observer, params.installFlags,
12079                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
12080                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12081                    params.grantedRuntimePermissions,
12082                    params.traceMethod, params.traceCookie);
12083        }
12084
12085        int copyApk(IMediaContainerService imcs, boolean temp) {
12086            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12087                    + move.fromUuid + " to " + move.toUuid);
12088            synchronized (mInstaller) {
12089                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12090                        move.dataAppName, move.appId, move.seinfo) != 0) {
12091                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12092                }
12093            }
12094
12095            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12096            resourceFile = codeFile;
12097            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12098
12099            return PackageManager.INSTALL_SUCCEEDED;
12100        }
12101
12102        int doPreInstall(int status) {
12103            if (status != PackageManager.INSTALL_SUCCEEDED) {
12104                cleanUp(move.toUuid);
12105            }
12106            return status;
12107        }
12108
12109        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12110            if (status != PackageManager.INSTALL_SUCCEEDED) {
12111                cleanUp(move.toUuid);
12112                return false;
12113            }
12114
12115            // Reflect the move in app info
12116            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12117            pkg.applicationInfo.setCodePath(pkg.codePath);
12118            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12119            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12120            pkg.applicationInfo.setResourcePath(pkg.codePath);
12121            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12122            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12123
12124            return true;
12125        }
12126
12127        int doPostInstall(int status, int uid) {
12128            if (status == PackageManager.INSTALL_SUCCEEDED) {
12129                cleanUp(move.fromUuid);
12130            } else {
12131                cleanUp(move.toUuid);
12132            }
12133            return status;
12134        }
12135
12136        @Override
12137        String getCodePath() {
12138            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12139        }
12140
12141        @Override
12142        String getResourcePath() {
12143            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12144        }
12145
12146        private boolean cleanUp(String volumeUuid) {
12147            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12148                    move.dataAppName);
12149            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12150            synchronized (mInstallLock) {
12151                // Clean up both app data and code
12152                removeDataDirsLI(volumeUuid, move.packageName);
12153                if (codeFile.isDirectory()) {
12154                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12155                } else {
12156                    codeFile.delete();
12157                }
12158            }
12159            return true;
12160        }
12161
12162        void cleanUpResourcesLI() {
12163            throw new UnsupportedOperationException();
12164        }
12165
12166        boolean doPostDeleteLI(boolean delete) {
12167            throw new UnsupportedOperationException();
12168        }
12169    }
12170
12171    static String getAsecPackageName(String packageCid) {
12172        int idx = packageCid.lastIndexOf("-");
12173        if (idx == -1) {
12174            return packageCid;
12175        }
12176        return packageCid.substring(0, idx);
12177    }
12178
12179    // Utility method used to create code paths based on package name and available index.
12180    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12181        String idxStr = "";
12182        int idx = 1;
12183        // Fall back to default value of idx=1 if prefix is not
12184        // part of oldCodePath
12185        if (oldCodePath != null) {
12186            String subStr = oldCodePath;
12187            // Drop the suffix right away
12188            if (suffix != null && subStr.endsWith(suffix)) {
12189                subStr = subStr.substring(0, subStr.length() - suffix.length());
12190            }
12191            // If oldCodePath already contains prefix find out the
12192            // ending index to either increment or decrement.
12193            int sidx = subStr.lastIndexOf(prefix);
12194            if (sidx != -1) {
12195                subStr = subStr.substring(sidx + prefix.length());
12196                if (subStr != null) {
12197                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12198                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12199                    }
12200                    try {
12201                        idx = Integer.parseInt(subStr);
12202                        if (idx <= 1) {
12203                            idx++;
12204                        } else {
12205                            idx--;
12206                        }
12207                    } catch(NumberFormatException e) {
12208                    }
12209                }
12210            }
12211        }
12212        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12213        return prefix + idxStr;
12214    }
12215
12216    private File getNextCodePath(File targetDir, String packageName) {
12217        int suffix = 1;
12218        File result;
12219        do {
12220            result = new File(targetDir, packageName + "-" + suffix);
12221            suffix++;
12222        } while (result.exists());
12223        return result;
12224    }
12225
12226    // Utility method that returns the relative package path with respect
12227    // to the installation directory. Like say for /data/data/com.test-1.apk
12228    // string com.test-1 is returned.
12229    static String deriveCodePathName(String codePath) {
12230        if (codePath == null) {
12231            return null;
12232        }
12233        final File codeFile = new File(codePath);
12234        final String name = codeFile.getName();
12235        if (codeFile.isDirectory()) {
12236            return name;
12237        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12238            final int lastDot = name.lastIndexOf('.');
12239            return name.substring(0, lastDot);
12240        } else {
12241            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12242            return null;
12243        }
12244    }
12245
12246    static class PackageInstalledInfo {
12247        String name;
12248        int uid;
12249        // The set of users that originally had this package installed.
12250        int[] origUsers;
12251        // The set of users that now have this package installed.
12252        int[] newUsers;
12253        PackageParser.Package pkg;
12254        int returnCode;
12255        String returnMsg;
12256        PackageRemovedInfo removedInfo;
12257
12258        public void setError(int code, String msg) {
12259            returnCode = code;
12260            returnMsg = msg;
12261            Slog.w(TAG, msg);
12262        }
12263
12264        public void setError(String msg, PackageParserException e) {
12265            returnCode = e.error;
12266            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12267            Slog.w(TAG, msg, e);
12268        }
12269
12270        public void setError(String msg, PackageManagerException e) {
12271            returnCode = e.error;
12272            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12273            Slog.w(TAG, msg, e);
12274        }
12275
12276        // In some error cases we want to convey more info back to the observer
12277        String origPackage;
12278        String origPermission;
12279    }
12280
12281    /*
12282     * Install a non-existing package.
12283     */
12284    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12285            UserHandle user, String installerPackageName, String volumeUuid,
12286            PackageInstalledInfo res) {
12287        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12288
12289        // Remember this for later, in case we need to rollback this install
12290        String pkgName = pkg.packageName;
12291
12292        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12293        // TODO: b/23350563
12294        final boolean dataDirExists = Environment
12295                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12296
12297        synchronized(mPackages) {
12298            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12299                // A package with the same name is already installed, though
12300                // it has been renamed to an older name.  The package we
12301                // are trying to install should be installed as an update to
12302                // the existing one, but that has not been requested, so bail.
12303                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12304                        + " without first uninstalling package running as "
12305                        + mSettings.mRenamedPackages.get(pkgName));
12306                return;
12307            }
12308            if (mPackages.containsKey(pkgName)) {
12309                // Don't allow installation over an existing package with the same name.
12310                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12311                        + " without first uninstalling.");
12312                return;
12313            }
12314        }
12315
12316        try {
12317            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12318                    System.currentTimeMillis(), user);
12319
12320            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12321            // delete the partially installed application. the data directory will have to be
12322            // restored if it was already existing
12323            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12324                // remove package from internal structures.  Note that we want deletePackageX to
12325                // delete the package data and cache directories that it created in
12326                // scanPackageLocked, unless those directories existed before we even tried to
12327                // install.
12328                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12329                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12330                                res.removedInfo, true);
12331            }
12332
12333        } catch (PackageManagerException e) {
12334            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12335        }
12336
12337        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12338    }
12339
12340    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12341        // Can't rotate keys during boot or if sharedUser.
12342        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12343                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12344            return false;
12345        }
12346        // app is using upgradeKeySets; make sure all are valid
12347        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12348        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12349        for (int i = 0; i < upgradeKeySets.length; i++) {
12350            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12351                Slog.wtf(TAG, "Package "
12352                         + (oldPs.name != null ? oldPs.name : "<null>")
12353                         + " contains upgrade-key-set reference to unknown key-set: "
12354                         + upgradeKeySets[i]
12355                         + " reverting to signatures check.");
12356                return false;
12357            }
12358        }
12359        return true;
12360    }
12361
12362    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12363        // Upgrade keysets are being used.  Determine if new package has a superset of the
12364        // required keys.
12365        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12366        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12367        for (int i = 0; i < upgradeKeySets.length; i++) {
12368            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12369            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12370                return true;
12371            }
12372        }
12373        return false;
12374    }
12375
12376    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12377            UserHandle user, String installerPackageName, String volumeUuid,
12378            PackageInstalledInfo res) {
12379        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12380
12381        final PackageParser.Package oldPackage;
12382        final String pkgName = pkg.packageName;
12383        final int[] allUsers;
12384        final boolean[] perUserInstalled;
12385
12386        // First find the old package info and check signatures
12387        synchronized(mPackages) {
12388            oldPackage = mPackages.get(pkgName);
12389            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12390            if (isEphemeral && !oldIsEphemeral) {
12391                // can't downgrade from full to ephemeral
12392                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12393                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12394                return;
12395            }
12396            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12397            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12398            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12399                if(!checkUpgradeKeySetLP(ps, pkg)) {
12400                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12401                            "New package not signed by keys specified by upgrade-keysets: "
12402                            + pkgName);
12403                    return;
12404                }
12405            } else {
12406                // default to original signature matching
12407                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12408                    != PackageManager.SIGNATURE_MATCH) {
12409                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12410                            "New package has a different signature: " + pkgName);
12411                    return;
12412                }
12413            }
12414
12415            // In case of rollback, remember per-user/profile install state
12416            allUsers = sUserManager.getUserIds();
12417            perUserInstalled = new boolean[allUsers.length];
12418            for (int i = 0; i < allUsers.length; i++) {
12419                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12420            }
12421        }
12422
12423        boolean sysPkg = (isSystemApp(oldPackage));
12424        if (sysPkg) {
12425            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12426                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12427        } else {
12428            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12429                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12430        }
12431    }
12432
12433    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12434            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12435            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12436            String volumeUuid, PackageInstalledInfo res) {
12437        String pkgName = deletedPackage.packageName;
12438        boolean deletedPkg = true;
12439        boolean updatedSettings = false;
12440
12441        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12442                + deletedPackage);
12443        long origUpdateTime;
12444        if (pkg.mExtras != null) {
12445            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12446        } else {
12447            origUpdateTime = 0;
12448        }
12449
12450        // First delete the existing package while retaining the data directory
12451        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12452                res.removedInfo, true)) {
12453            // If the existing package wasn't successfully deleted
12454            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12455            deletedPkg = false;
12456        } else {
12457            // Successfully deleted the old package; proceed with replace.
12458
12459            // If deleted package lived in a container, give users a chance to
12460            // relinquish resources before killing.
12461            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12462                if (DEBUG_INSTALL) {
12463                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12464                }
12465                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12466                final ArrayList<String> pkgList = new ArrayList<String>(1);
12467                pkgList.add(deletedPackage.applicationInfo.packageName);
12468                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12469            }
12470
12471            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12472            try {
12473                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12474                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12475                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12476                        perUserInstalled, res, user);
12477                updatedSettings = true;
12478            } catch (PackageManagerException e) {
12479                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12480            }
12481        }
12482
12483        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12484            // remove package from internal structures.  Note that we want deletePackageX to
12485            // delete the package data and cache directories that it created in
12486            // scanPackageLocked, unless those directories existed before we even tried to
12487            // install.
12488            if(updatedSettings) {
12489                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12490                deletePackageLI(
12491                        pkgName, null, true, allUsers, perUserInstalled,
12492                        PackageManager.DELETE_KEEP_DATA,
12493                                res.removedInfo, true);
12494            }
12495            // Since we failed to install the new package we need to restore the old
12496            // package that we deleted.
12497            if (deletedPkg) {
12498                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12499                File restoreFile = new File(deletedPackage.codePath);
12500                // Parse old package
12501                boolean oldExternal = isExternal(deletedPackage);
12502                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12503                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12504                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12505                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12506                try {
12507                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12508                            null);
12509                } catch (PackageManagerException e) {
12510                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12511                            + e.getMessage());
12512                    return;
12513                }
12514                // Restore of old package succeeded. Update permissions.
12515                // writer
12516                synchronized (mPackages) {
12517                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12518                            UPDATE_PERMISSIONS_ALL);
12519                    // can downgrade to reader
12520                    mSettings.writeLPr();
12521                }
12522                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12523            }
12524        }
12525    }
12526
12527    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12528            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12529            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12530            String volumeUuid, PackageInstalledInfo res) {
12531        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12532                + ", old=" + deletedPackage);
12533        boolean disabledSystem = false;
12534        boolean updatedSettings = false;
12535        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12536        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12537                != 0) {
12538            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12539        }
12540        String packageName = deletedPackage.packageName;
12541        if (packageName == null) {
12542            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12543                    "Attempt to delete null packageName.");
12544            return;
12545        }
12546        PackageParser.Package oldPkg;
12547        PackageSetting oldPkgSetting;
12548        // reader
12549        synchronized (mPackages) {
12550            oldPkg = mPackages.get(packageName);
12551            oldPkgSetting = mSettings.mPackages.get(packageName);
12552            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12553                    (oldPkgSetting == null)) {
12554                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12555                        "Couldn't find package:" + packageName + " information");
12556                return;
12557            }
12558        }
12559
12560        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12561
12562        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12563        res.removedInfo.removedPackage = packageName;
12564        // Remove existing system package
12565        removePackageLI(oldPkgSetting, true);
12566        // writer
12567        synchronized (mPackages) {
12568            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12569            if (!disabledSystem && deletedPackage != null) {
12570                // We didn't need to disable the .apk as a current system package,
12571                // which means we are replacing another update that is already
12572                // installed.  We need to make sure to delete the older one's .apk.
12573                res.removedInfo.args = createInstallArgsForExisting(0,
12574                        deletedPackage.applicationInfo.getCodePath(),
12575                        deletedPackage.applicationInfo.getResourcePath(),
12576                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12577            } else {
12578                res.removedInfo.args = null;
12579            }
12580        }
12581
12582        // Successfully disabled the old package. Now proceed with re-installation
12583        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12584
12585        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12586        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12587
12588        PackageParser.Package newPackage = null;
12589        try {
12590            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12591            if (newPackage.mExtras != null) {
12592                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12593                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12594                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12595
12596                // is the update attempting to change shared user? that isn't going to work...
12597                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12598                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12599                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12600                            + " to " + newPkgSetting.sharedUser);
12601                    updatedSettings = true;
12602                }
12603            }
12604
12605            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12606                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12607                        perUserInstalled, res, user);
12608                updatedSettings = true;
12609            }
12610
12611        } catch (PackageManagerException e) {
12612            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12613        }
12614
12615        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12616            // Re installation failed. Restore old information
12617            // Remove new pkg information
12618            if (newPackage != null) {
12619                removeInstalledPackageLI(newPackage, true);
12620            }
12621            // Add back the old system package
12622            try {
12623                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12624            } catch (PackageManagerException e) {
12625                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12626            }
12627            // Restore the old system information in Settings
12628            synchronized (mPackages) {
12629                if (disabledSystem) {
12630                    mSettings.enableSystemPackageLPw(packageName);
12631                }
12632                if (updatedSettings) {
12633                    mSettings.setInstallerPackageName(packageName,
12634                            oldPkgSetting.installerPackageName);
12635                }
12636                mSettings.writeLPr();
12637            }
12638        }
12639    }
12640
12641    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12642        // Collect all used permissions in the UID
12643        ArraySet<String> usedPermissions = new ArraySet<>();
12644        final int packageCount = su.packages.size();
12645        for (int i = 0; i < packageCount; i++) {
12646            PackageSetting ps = su.packages.valueAt(i);
12647            if (ps.pkg == null) {
12648                continue;
12649            }
12650            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12651            for (int j = 0; j < requestedPermCount; j++) {
12652                String permission = ps.pkg.requestedPermissions.get(j);
12653                BasePermission bp = mSettings.mPermissions.get(permission);
12654                if (bp != null) {
12655                    usedPermissions.add(permission);
12656                }
12657            }
12658        }
12659
12660        PermissionsState permissionsState = su.getPermissionsState();
12661        // Prune install permissions
12662        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12663        final int installPermCount = installPermStates.size();
12664        for (int i = installPermCount - 1; i >= 0;  i--) {
12665            PermissionState permissionState = installPermStates.get(i);
12666            if (!usedPermissions.contains(permissionState.getName())) {
12667                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12668                if (bp != null) {
12669                    permissionsState.revokeInstallPermission(bp);
12670                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12671                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12672                }
12673            }
12674        }
12675
12676        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12677
12678        // Prune runtime permissions
12679        for (int userId : allUserIds) {
12680            List<PermissionState> runtimePermStates = permissionsState
12681                    .getRuntimePermissionStates(userId);
12682            final int runtimePermCount = runtimePermStates.size();
12683            for (int i = runtimePermCount - 1; i >= 0; i--) {
12684                PermissionState permissionState = runtimePermStates.get(i);
12685                if (!usedPermissions.contains(permissionState.getName())) {
12686                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12687                    if (bp != null) {
12688                        permissionsState.revokeRuntimePermission(bp, userId);
12689                        permissionsState.updatePermissionFlags(bp, userId,
12690                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12691                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12692                                runtimePermissionChangedUserIds, userId);
12693                    }
12694                }
12695            }
12696        }
12697
12698        return runtimePermissionChangedUserIds;
12699    }
12700
12701    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12702            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12703            UserHandle user) {
12704        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12705
12706        String pkgName = newPackage.packageName;
12707        synchronized (mPackages) {
12708            //write settings. the installStatus will be incomplete at this stage.
12709            //note that the new package setting would have already been
12710            //added to mPackages. It hasn't been persisted yet.
12711            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12712            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12713            mSettings.writeLPr();
12714            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12715        }
12716
12717        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12718        synchronized (mPackages) {
12719            updatePermissionsLPw(newPackage.packageName, newPackage,
12720                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12721                            ? UPDATE_PERMISSIONS_ALL : 0));
12722            // For system-bundled packages, we assume that installing an upgraded version
12723            // of the package implies that the user actually wants to run that new code,
12724            // so we enable the package.
12725            PackageSetting ps = mSettings.mPackages.get(pkgName);
12726            if (ps != null) {
12727                if (isSystemApp(newPackage)) {
12728                    // NB: implicit assumption that system package upgrades apply to all users
12729                    if (DEBUG_INSTALL) {
12730                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12731                    }
12732                    if (res.origUsers != null) {
12733                        for (int userHandle : res.origUsers) {
12734                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12735                                    userHandle, installerPackageName);
12736                        }
12737                    }
12738                    // Also convey the prior install/uninstall state
12739                    if (allUsers != null && perUserInstalled != null) {
12740                        for (int i = 0; i < allUsers.length; i++) {
12741                            if (DEBUG_INSTALL) {
12742                                Slog.d(TAG, "    user " + allUsers[i]
12743                                        + " => " + perUserInstalled[i]);
12744                            }
12745                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12746                        }
12747                        // these install state changes will be persisted in the
12748                        // upcoming call to mSettings.writeLPr().
12749                    }
12750                }
12751                // It's implied that when a user requests installation, they want the app to be
12752                // installed and enabled.
12753                int userId = user.getIdentifier();
12754                if (userId != UserHandle.USER_ALL) {
12755                    ps.setInstalled(true, userId);
12756                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12757                }
12758            }
12759            res.name = pkgName;
12760            res.uid = newPackage.applicationInfo.uid;
12761            res.pkg = newPackage;
12762            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12763            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12764            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12765            //to update install status
12766            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12767            mSettings.writeLPr();
12768            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12769        }
12770
12771        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12772    }
12773
12774    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12775        try {
12776            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12777            installPackageLI(args, res);
12778        } finally {
12779            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12780        }
12781    }
12782
12783    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12784        final int installFlags = args.installFlags;
12785        final String installerPackageName = args.installerPackageName;
12786        final String volumeUuid = args.volumeUuid;
12787        final File tmpPackageFile = new File(args.getCodePath());
12788        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12789        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12790                || (args.volumeUuid != null));
12791        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12792        boolean replace = false;
12793        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12794        if (args.move != null) {
12795            // moving a complete application; perfom an initial scan on the new install location
12796            scanFlags |= SCAN_INITIAL;
12797        }
12798        // Result object to be returned
12799        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12800
12801        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12802
12803        // Sanity check
12804        if (ephemeral && (forwardLocked || onExternal)) {
12805            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12806                    + " external=" + onExternal);
12807            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12808            return;
12809        }
12810
12811        // Retrieve PackageSettings and parse package
12812        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12813                | PackageParser.PARSE_ENFORCE_CODE
12814                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12815                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12816                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12817        PackageParser pp = new PackageParser();
12818        pp.setSeparateProcesses(mSeparateProcesses);
12819        pp.setDisplayMetrics(mMetrics);
12820
12821        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12822        final PackageParser.Package pkg;
12823        try {
12824            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12825        } catch (PackageParserException e) {
12826            res.setError("Failed parse during installPackageLI", e);
12827            return;
12828        } finally {
12829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12830        }
12831
12832        // Mark that we have an install time CPU ABI override.
12833        pkg.cpuAbiOverride = args.abiOverride;
12834
12835        String pkgName = res.name = pkg.packageName;
12836        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12837            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12838                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12839                return;
12840            }
12841        }
12842
12843        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12844        try {
12845            pp.collectCertificates(pkg, parseFlags);
12846        } catch (PackageParserException e) {
12847            res.setError("Failed collect during installPackageLI", e);
12848            return;
12849        } finally {
12850            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12851        }
12852
12853        /* If the installer passed in a manifest digest, compare it now. */
12854        if (args.manifestDigest != null) {
12855            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12856            try {
12857                pp.collectManifestDigest(pkg);
12858            } catch (PackageParserException e) {
12859                res.setError("Failed collect during installPackageLI", e);
12860                return;
12861            } finally {
12862                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12863            }
12864
12865            if (DEBUG_INSTALL) {
12866                final String parsedManifest = pkg.manifestDigest == null ? "null"
12867                        : pkg.manifestDigest.toString();
12868                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12869                        + parsedManifest);
12870            }
12871
12872            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12873                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12874                return;
12875            }
12876        } else if (DEBUG_INSTALL) {
12877            final String parsedManifest = pkg.manifestDigest == null
12878                    ? "null" : pkg.manifestDigest.toString();
12879            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12880        }
12881
12882        // Get rid of all references to package scan path via parser.
12883        pp = null;
12884        String oldCodePath = null;
12885        boolean systemApp = false;
12886        synchronized (mPackages) {
12887            // Check if installing already existing package
12888            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12889                String oldName = mSettings.mRenamedPackages.get(pkgName);
12890                if (pkg.mOriginalPackages != null
12891                        && pkg.mOriginalPackages.contains(oldName)
12892                        && mPackages.containsKey(oldName)) {
12893                    // This package is derived from an original package,
12894                    // and this device has been updating from that original
12895                    // name.  We must continue using the original name, so
12896                    // rename the new package here.
12897                    pkg.setPackageName(oldName);
12898                    pkgName = pkg.packageName;
12899                    replace = true;
12900                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12901                            + oldName + " pkgName=" + pkgName);
12902                } else if (mPackages.containsKey(pkgName)) {
12903                    // This package, under its official name, already exists
12904                    // on the device; we should replace it.
12905                    replace = true;
12906                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12907                }
12908
12909                // Prevent apps opting out from runtime permissions
12910                if (replace) {
12911                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12912                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12913                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12914                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12915                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12916                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12917                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12918                                        + " doesn't support runtime permissions but the old"
12919                                        + " target SDK " + oldTargetSdk + " does.");
12920                        return;
12921                    }
12922                }
12923            }
12924
12925            PackageSetting ps = mSettings.mPackages.get(pkgName);
12926            if (ps != null) {
12927                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12928
12929                // Quick sanity check that we're signed correctly if updating;
12930                // we'll check this again later when scanning, but we want to
12931                // bail early here before tripping over redefined permissions.
12932                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12933                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12934                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12935                                + pkg.packageName + " upgrade keys do not match the "
12936                                + "previously installed version");
12937                        return;
12938                    }
12939                } else {
12940                    try {
12941                        verifySignaturesLP(ps, pkg);
12942                    } catch (PackageManagerException e) {
12943                        res.setError(e.error, e.getMessage());
12944                        return;
12945                    }
12946                }
12947
12948                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12949                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12950                    systemApp = (ps.pkg.applicationInfo.flags &
12951                            ApplicationInfo.FLAG_SYSTEM) != 0;
12952                }
12953                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12954            }
12955
12956            // Check whether the newly-scanned package wants to define an already-defined perm
12957            int N = pkg.permissions.size();
12958            for (int i = N-1; i >= 0; i--) {
12959                PackageParser.Permission perm = pkg.permissions.get(i);
12960                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12961                if (bp != null) {
12962                    // If the defining package is signed with our cert, it's okay.  This
12963                    // also includes the "updating the same package" case, of course.
12964                    // "updating same package" could also involve key-rotation.
12965                    final boolean sigsOk;
12966                    if (bp.sourcePackage.equals(pkg.packageName)
12967                            && (bp.packageSetting instanceof PackageSetting)
12968                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12969                                    scanFlags))) {
12970                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12971                    } else {
12972                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12973                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12974                    }
12975                    if (!sigsOk) {
12976                        // If the owning package is the system itself, we log but allow
12977                        // install to proceed; we fail the install on all other permission
12978                        // redefinitions.
12979                        if (!bp.sourcePackage.equals("android")) {
12980                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12981                                    + pkg.packageName + " attempting to redeclare permission "
12982                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12983                            res.origPermission = perm.info.name;
12984                            res.origPackage = bp.sourcePackage;
12985                            return;
12986                        } else {
12987                            Slog.w(TAG, "Package " + pkg.packageName
12988                                    + " attempting to redeclare system permission "
12989                                    + perm.info.name + "; ignoring new declaration");
12990                            pkg.permissions.remove(i);
12991                        }
12992                    }
12993                }
12994            }
12995
12996        }
12997
12998        if (systemApp) {
12999            if (onExternal) {
13000                // Abort update; system app can't be replaced with app on sdcard
13001                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13002                        "Cannot install updates to system apps on sdcard");
13003                return;
13004            } else if (ephemeral) {
13005                // Abort update; system app can't be replaced with an ephemeral app
13006                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13007                        "Cannot update a system app with an ephemeral app");
13008                return;
13009            }
13010        }
13011
13012        if (args.move != null) {
13013            // We did an in-place move, so dex is ready to roll
13014            scanFlags |= SCAN_NO_DEX;
13015            scanFlags |= SCAN_MOVE;
13016
13017            synchronized (mPackages) {
13018                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13019                if (ps == null) {
13020                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13021                            "Missing settings for moved package " + pkgName);
13022                }
13023
13024                // We moved the entire application as-is, so bring over the
13025                // previously derived ABI information.
13026                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13027                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13028            }
13029
13030        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13031            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13032            scanFlags |= SCAN_NO_DEX;
13033
13034            try {
13035                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13036                        true /* extract libs */);
13037            } catch (PackageManagerException pme) {
13038                Slog.e(TAG, "Error deriving application ABI", pme);
13039                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13040                return;
13041            }
13042        }
13043
13044        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13045            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13046            return;
13047        }
13048
13049        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13050
13051        if (replace) {
13052            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13053                    installerPackageName, volumeUuid, res);
13054        } else {
13055            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13056                    args.user, installerPackageName, volumeUuid, res);
13057        }
13058        synchronized (mPackages) {
13059            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13060            if (ps != null) {
13061                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13062            }
13063        }
13064    }
13065
13066    private void startIntentFilterVerifications(int userId, boolean replacing,
13067            PackageParser.Package pkg) {
13068        if (mIntentFilterVerifierComponent == null) {
13069            Slog.w(TAG, "No IntentFilter verification will not be done as "
13070                    + "there is no IntentFilterVerifier available!");
13071            return;
13072        }
13073
13074        final int verifierUid = getPackageUid(
13075                mIntentFilterVerifierComponent.getPackageName(),
13076                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13077
13078        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13079        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13080        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13081        mHandler.sendMessage(msg);
13082    }
13083
13084    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13085            PackageParser.Package pkg) {
13086        int size = pkg.activities.size();
13087        if (size == 0) {
13088            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13089                    "No activity, so no need to verify any IntentFilter!");
13090            return;
13091        }
13092
13093        final boolean hasDomainURLs = hasDomainURLs(pkg);
13094        if (!hasDomainURLs) {
13095            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13096                    "No domain URLs, so no need to verify any IntentFilter!");
13097            return;
13098        }
13099
13100        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13101                + " if any IntentFilter from the " + size
13102                + " Activities needs verification ...");
13103
13104        int count = 0;
13105        final String packageName = pkg.packageName;
13106
13107        synchronized (mPackages) {
13108            // If this is a new install and we see that we've already run verification for this
13109            // package, we have nothing to do: it means the state was restored from backup.
13110            if (!replacing) {
13111                IntentFilterVerificationInfo ivi =
13112                        mSettings.getIntentFilterVerificationLPr(packageName);
13113                if (ivi != null) {
13114                    if (DEBUG_DOMAIN_VERIFICATION) {
13115                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13116                                + ivi.getStatusString());
13117                    }
13118                    return;
13119                }
13120            }
13121
13122            // If any filters need to be verified, then all need to be.
13123            boolean needToVerify = false;
13124            for (PackageParser.Activity a : pkg.activities) {
13125                for (ActivityIntentInfo filter : a.intents) {
13126                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13127                        if (DEBUG_DOMAIN_VERIFICATION) {
13128                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13129                        }
13130                        needToVerify = true;
13131                        break;
13132                    }
13133                }
13134            }
13135
13136            if (needToVerify) {
13137                final int verificationId = mIntentFilterVerificationToken++;
13138                for (PackageParser.Activity a : pkg.activities) {
13139                    for (ActivityIntentInfo filter : a.intents) {
13140                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13141                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13142                                    "Verification needed for IntentFilter:" + filter.toString());
13143                            mIntentFilterVerifier.addOneIntentFilterVerification(
13144                                    verifierUid, userId, verificationId, filter, packageName);
13145                            count++;
13146                        }
13147                    }
13148                }
13149            }
13150        }
13151
13152        if (count > 0) {
13153            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13154                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13155                    +  " for userId:" + userId);
13156            mIntentFilterVerifier.startVerifications(userId);
13157        } else {
13158            if (DEBUG_DOMAIN_VERIFICATION) {
13159                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13160            }
13161        }
13162    }
13163
13164    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13165        final ComponentName cn  = filter.activity.getComponentName();
13166        final String packageName = cn.getPackageName();
13167
13168        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13169                packageName);
13170        if (ivi == null) {
13171            return true;
13172        }
13173        int status = ivi.getStatus();
13174        switch (status) {
13175            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13176            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13177                return true;
13178
13179            default:
13180                // Nothing to do
13181                return false;
13182        }
13183    }
13184
13185    private static boolean isMultiArch(ApplicationInfo info) {
13186        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13187    }
13188
13189    private static boolean isExternal(PackageParser.Package pkg) {
13190        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13191    }
13192
13193    private static boolean isExternal(PackageSetting ps) {
13194        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13195    }
13196
13197    private static boolean isEphemeral(PackageParser.Package pkg) {
13198        return pkg.applicationInfo.isEphemeralApp();
13199    }
13200
13201    private static boolean isEphemeral(PackageSetting ps) {
13202        return ps.pkg != null && isEphemeral(ps.pkg);
13203    }
13204
13205    private static boolean isSystemApp(PackageParser.Package pkg) {
13206        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13207    }
13208
13209    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13210        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13211    }
13212
13213    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13214        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13215    }
13216
13217    private static boolean isSystemApp(PackageSetting ps) {
13218        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13219    }
13220
13221    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13222        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13223    }
13224
13225    private int packageFlagsToInstallFlags(PackageSetting ps) {
13226        int installFlags = 0;
13227        if (isEphemeral(ps)) {
13228            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13229        }
13230        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13231            // This existing package was an external ASEC install when we have
13232            // the external flag without a UUID
13233            installFlags |= PackageManager.INSTALL_EXTERNAL;
13234        }
13235        if (ps.isForwardLocked()) {
13236            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13237        }
13238        return installFlags;
13239    }
13240
13241    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13242        if (isExternal(pkg)) {
13243            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13244                return StorageManager.UUID_PRIMARY_PHYSICAL;
13245            } else {
13246                return pkg.volumeUuid;
13247            }
13248        } else {
13249            return StorageManager.UUID_PRIVATE_INTERNAL;
13250        }
13251    }
13252
13253    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13254        if (isExternal(pkg)) {
13255            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13256                return mSettings.getExternalVersion();
13257            } else {
13258                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13259            }
13260        } else {
13261            return mSettings.getInternalVersion();
13262        }
13263    }
13264
13265    private void deleteTempPackageFiles() {
13266        final FilenameFilter filter = new FilenameFilter() {
13267            public boolean accept(File dir, String name) {
13268                return name.startsWith("vmdl") && name.endsWith(".tmp");
13269            }
13270        };
13271        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13272            file.delete();
13273        }
13274    }
13275
13276    @Override
13277    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13278            int flags) {
13279        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13280                flags);
13281    }
13282
13283    @Override
13284    public void deletePackage(final String packageName,
13285            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13286        mContext.enforceCallingOrSelfPermission(
13287                android.Manifest.permission.DELETE_PACKAGES, null);
13288        Preconditions.checkNotNull(packageName);
13289        Preconditions.checkNotNull(observer);
13290        final int uid = Binder.getCallingUid();
13291        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13292        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13293        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13294            mContext.enforceCallingOrSelfPermission(
13295                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13296                    "deletePackage for user " + userId);
13297        }
13298
13299        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13300            try {
13301                observer.onPackageDeleted(packageName,
13302                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13303            } catch (RemoteException re) {
13304            }
13305            return;
13306        }
13307
13308        for (int currentUserId : users) {
13309            if (getBlockUninstallForUser(packageName, currentUserId)) {
13310                try {
13311                    observer.onPackageDeleted(packageName,
13312                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13313                } catch (RemoteException re) {
13314                }
13315                return;
13316            }
13317        }
13318
13319        if (DEBUG_REMOVE) {
13320            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13321        }
13322        // Queue up an async operation since the package deletion may take a little while.
13323        mHandler.post(new Runnable() {
13324            public void run() {
13325                mHandler.removeCallbacks(this);
13326                final int returnCode = deletePackageX(packageName, userId, flags);
13327                try {
13328                    observer.onPackageDeleted(packageName, returnCode, null);
13329                } catch (RemoteException e) {
13330                    Log.i(TAG, "Observer no longer exists.");
13331                } //end catch
13332            } //end run
13333        });
13334    }
13335
13336    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13337        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13338                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13339        try {
13340            if (dpm != null) {
13341                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13342                        /* callingUserOnly =*/ false);
13343                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13344                        : deviceOwnerComponentName.getPackageName();
13345                // Does the package contains the device owner?
13346                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13347                // this check is probably not needed, since DO should be registered as a device
13348                // admin on some user too. (Original bug for this: b/17657954)
13349                if (packageName.equals(deviceOwnerPackageName)) {
13350                    return true;
13351                }
13352                // Does it contain a device admin for any user?
13353                int[] users;
13354                if (userId == UserHandle.USER_ALL) {
13355                    users = sUserManager.getUserIds();
13356                } else {
13357                    users = new int[]{userId};
13358                }
13359                for (int i = 0; i < users.length; ++i) {
13360                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13361                        return true;
13362                    }
13363                }
13364            }
13365        } catch (RemoteException e) {
13366        }
13367        return false;
13368    }
13369
13370    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13371        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13372    }
13373
13374    /**
13375     *  This method is an internal method that could be get invoked either
13376     *  to delete an installed package or to clean up a failed installation.
13377     *  After deleting an installed package, a broadcast is sent to notify any
13378     *  listeners that the package has been installed. For cleaning up a failed
13379     *  installation, the broadcast is not necessary since the package's
13380     *  installation wouldn't have sent the initial broadcast either
13381     *  The key steps in deleting a package are
13382     *  deleting the package information in internal structures like mPackages,
13383     *  deleting the packages base directories through installd
13384     *  updating mSettings to reflect current status
13385     *  persisting settings for later use
13386     *  sending a broadcast if necessary
13387     */
13388    private int deletePackageX(String packageName, int userId, int flags) {
13389        final PackageRemovedInfo info = new PackageRemovedInfo();
13390        final boolean res;
13391
13392        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13393                ? UserHandle.ALL : new UserHandle(userId);
13394
13395        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13396            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13397            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13398        }
13399
13400        boolean removedForAllUsers = false;
13401        boolean systemUpdate = false;
13402
13403        PackageParser.Package uninstalledPkg;
13404
13405        // for the uninstall-updates case and restricted profiles, remember the per-
13406        // userhandle installed state
13407        int[] allUsers;
13408        boolean[] perUserInstalled;
13409        synchronized (mPackages) {
13410            uninstalledPkg = mPackages.get(packageName);
13411            PackageSetting ps = mSettings.mPackages.get(packageName);
13412            allUsers = sUserManager.getUserIds();
13413            perUserInstalled = new boolean[allUsers.length];
13414            for (int i = 0; i < allUsers.length; i++) {
13415                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13416            }
13417        }
13418
13419        synchronized (mInstallLock) {
13420            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13421            res = deletePackageLI(packageName, removeForUser,
13422                    true, allUsers, perUserInstalled,
13423                    flags | REMOVE_CHATTY, info, true);
13424            systemUpdate = info.isRemovedPackageSystemUpdate;
13425            synchronized (mPackages) {
13426                if (res) {
13427                    if (!systemUpdate && mPackages.get(packageName) == null) {
13428                        removedForAllUsers = true;
13429                    }
13430                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13431                }
13432            }
13433            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13434                    + " removedForAllUsers=" + removedForAllUsers);
13435        }
13436
13437        if (res) {
13438            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13439
13440            // If the removed package was a system update, the old system package
13441            // was re-enabled; we need to broadcast this information
13442            if (systemUpdate) {
13443                Bundle extras = new Bundle(1);
13444                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13445                        ? info.removedAppId : info.uid);
13446                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13447
13448                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13449                        extras, 0, null, null, null);
13450                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13451                        extras, 0, null, null, null);
13452                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13453                        null, 0, packageName, null, null);
13454            }
13455        }
13456        // Force a gc here.
13457        Runtime.getRuntime().gc();
13458        // Delete the resources here after sending the broadcast to let
13459        // other processes clean up before deleting resources.
13460        if (info.args != null) {
13461            synchronized (mInstallLock) {
13462                info.args.doPostDeleteLI(true);
13463            }
13464        }
13465
13466        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13467    }
13468
13469    class PackageRemovedInfo {
13470        String removedPackage;
13471        int uid = -1;
13472        int removedAppId = -1;
13473        int[] removedUsers = null;
13474        boolean isRemovedPackageSystemUpdate = false;
13475        // Clean up resources deleted packages.
13476        InstallArgs args = null;
13477
13478        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13479            Bundle extras = new Bundle(1);
13480            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13481            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13482            if (replacing) {
13483                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13484            }
13485            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13486            if (removedPackage != null) {
13487                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13488                        extras, 0, null, null, removedUsers);
13489                if (fullRemove && !replacing) {
13490                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13491                            extras, 0, null, null, removedUsers);
13492                }
13493            }
13494            if (removedAppId >= 0) {
13495                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13496                        removedUsers);
13497            }
13498        }
13499    }
13500
13501    /*
13502     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13503     * flag is not set, the data directory is removed as well.
13504     * make sure this flag is set for partially installed apps. If not its meaningless to
13505     * delete a partially installed application.
13506     */
13507    private void removePackageDataLI(PackageSetting ps,
13508            int[] allUserHandles, boolean[] perUserInstalled,
13509            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13510        String packageName = ps.name;
13511        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13512        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13513        // Retrieve object to delete permissions for shared user later on
13514        final PackageSetting deletedPs;
13515        // reader
13516        synchronized (mPackages) {
13517            deletedPs = mSettings.mPackages.get(packageName);
13518            if (outInfo != null) {
13519                outInfo.removedPackage = packageName;
13520                outInfo.removedUsers = deletedPs != null
13521                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13522                        : null;
13523            }
13524        }
13525        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13526            removeDataDirsLI(ps.volumeUuid, packageName);
13527            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13528        }
13529        // writer
13530        synchronized (mPackages) {
13531            if (deletedPs != null) {
13532                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13533                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13534                    clearDefaultBrowserIfNeeded(packageName);
13535                    if (outInfo != null) {
13536                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13537                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13538                    }
13539                    updatePermissionsLPw(deletedPs.name, null, 0);
13540                    if (deletedPs.sharedUser != null) {
13541                        // Remove permissions associated with package. Since runtime
13542                        // permissions are per user we have to kill the removed package
13543                        // or packages running under the shared user of the removed
13544                        // package if revoking the permissions requested only by the removed
13545                        // package is successful and this causes a change in gids.
13546                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13547                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13548                                    userId);
13549                            if (userIdToKill == UserHandle.USER_ALL
13550                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13551                                // If gids changed for this user, kill all affected packages.
13552                                mHandler.post(new Runnable() {
13553                                    @Override
13554                                    public void run() {
13555                                        // This has to happen with no lock held.
13556                                        killApplication(deletedPs.name, deletedPs.appId,
13557                                                KILL_APP_REASON_GIDS_CHANGED);
13558                                    }
13559                                });
13560                                break;
13561                            }
13562                        }
13563                    }
13564                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13565                }
13566                // make sure to preserve per-user disabled state if this removal was just
13567                // a downgrade of a system app to the factory package
13568                if (allUserHandles != null && perUserInstalled != null) {
13569                    if (DEBUG_REMOVE) {
13570                        Slog.d(TAG, "Propagating install state across downgrade");
13571                    }
13572                    for (int i = 0; i < allUserHandles.length; i++) {
13573                        if (DEBUG_REMOVE) {
13574                            Slog.d(TAG, "    user " + allUserHandles[i]
13575                                    + " => " + perUserInstalled[i]);
13576                        }
13577                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13578                    }
13579                }
13580            }
13581            // can downgrade to reader
13582            if (writeSettings) {
13583                // Save settings now
13584                mSettings.writeLPr();
13585            }
13586        }
13587        if (outInfo != null) {
13588            // A user ID was deleted here. Go through all users and remove it
13589            // from KeyStore.
13590            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13591        }
13592    }
13593
13594    static boolean locationIsPrivileged(File path) {
13595        try {
13596            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13597                    .getCanonicalPath();
13598            return path.getCanonicalPath().startsWith(privilegedAppDir);
13599        } catch (IOException e) {
13600            Slog.e(TAG, "Unable to access code path " + path);
13601        }
13602        return false;
13603    }
13604
13605    /*
13606     * Tries to delete system package.
13607     */
13608    private boolean deleteSystemPackageLI(PackageSetting newPs,
13609            int[] allUserHandles, boolean[] perUserInstalled,
13610            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13611        final boolean applyUserRestrictions
13612                = (allUserHandles != null) && (perUserInstalled != null);
13613        PackageSetting disabledPs = null;
13614        // Confirm if the system package has been updated
13615        // An updated system app can be deleted. This will also have to restore
13616        // the system pkg from system partition
13617        // reader
13618        synchronized (mPackages) {
13619            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13620        }
13621        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13622                + " disabledPs=" + disabledPs);
13623        if (disabledPs == null) {
13624            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13625            return false;
13626        } else if (DEBUG_REMOVE) {
13627            Slog.d(TAG, "Deleting system pkg from data partition");
13628        }
13629        if (DEBUG_REMOVE) {
13630            if (applyUserRestrictions) {
13631                Slog.d(TAG, "Remembering install states:");
13632                for (int i = 0; i < allUserHandles.length; i++) {
13633                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13634                }
13635            }
13636        }
13637        // Delete the updated package
13638        outInfo.isRemovedPackageSystemUpdate = true;
13639        if (disabledPs.versionCode < newPs.versionCode) {
13640            // Delete data for downgrades
13641            flags &= ~PackageManager.DELETE_KEEP_DATA;
13642        } else {
13643            // Preserve data by setting flag
13644            flags |= PackageManager.DELETE_KEEP_DATA;
13645        }
13646        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13647                allUserHandles, perUserInstalled, outInfo, writeSettings);
13648        if (!ret) {
13649            return false;
13650        }
13651        // writer
13652        synchronized (mPackages) {
13653            // Reinstate the old system package
13654            mSettings.enableSystemPackageLPw(newPs.name);
13655            // Remove any native libraries from the upgraded package.
13656            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13657        }
13658        // Install the system package
13659        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13660        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13661        if (locationIsPrivileged(disabledPs.codePath)) {
13662            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13663        }
13664
13665        final PackageParser.Package newPkg;
13666        try {
13667            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13668        } catch (PackageManagerException e) {
13669            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13670            return false;
13671        }
13672
13673        // writer
13674        synchronized (mPackages) {
13675            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13676
13677            // Propagate the permissions state as we do not want to drop on the floor
13678            // runtime permissions. The update permissions method below will take
13679            // care of removing obsolete permissions and grant install permissions.
13680            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13681            updatePermissionsLPw(newPkg.packageName, newPkg,
13682                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13683
13684            if (applyUserRestrictions) {
13685                if (DEBUG_REMOVE) {
13686                    Slog.d(TAG, "Propagating install state across reinstall");
13687                }
13688                for (int i = 0; i < allUserHandles.length; i++) {
13689                    if (DEBUG_REMOVE) {
13690                        Slog.d(TAG, "    user " + allUserHandles[i]
13691                                + " => " + perUserInstalled[i]);
13692                    }
13693                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13694
13695                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13696                }
13697                // Regardless of writeSettings we need to ensure that this restriction
13698                // state propagation is persisted
13699                mSettings.writeAllUsersPackageRestrictionsLPr();
13700            }
13701            // can downgrade to reader here
13702            if (writeSettings) {
13703                mSettings.writeLPr();
13704            }
13705        }
13706        return true;
13707    }
13708
13709    private boolean deleteInstalledPackageLI(PackageSetting ps,
13710            boolean deleteCodeAndResources, int flags,
13711            int[] allUserHandles, boolean[] perUserInstalled,
13712            PackageRemovedInfo outInfo, boolean writeSettings) {
13713        if (outInfo != null) {
13714            outInfo.uid = ps.appId;
13715        }
13716
13717        // Delete package data from internal structures and also remove data if flag is set
13718        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13719
13720        // Delete application code and resources
13721        if (deleteCodeAndResources && (outInfo != null)) {
13722            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13723                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13724            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13725        }
13726        return true;
13727    }
13728
13729    @Override
13730    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13731            int userId) {
13732        mContext.enforceCallingOrSelfPermission(
13733                android.Manifest.permission.DELETE_PACKAGES, null);
13734        synchronized (mPackages) {
13735            PackageSetting ps = mSettings.mPackages.get(packageName);
13736            if (ps == null) {
13737                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13738                return false;
13739            }
13740            if (!ps.getInstalled(userId)) {
13741                // Can't block uninstall for an app that is not installed or enabled.
13742                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13743                return false;
13744            }
13745            ps.setBlockUninstall(blockUninstall, userId);
13746            mSettings.writePackageRestrictionsLPr(userId);
13747        }
13748        return true;
13749    }
13750
13751    @Override
13752    public boolean getBlockUninstallForUser(String packageName, int userId) {
13753        synchronized (mPackages) {
13754            PackageSetting ps = mSettings.mPackages.get(packageName);
13755            if (ps == null) {
13756                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13757                return false;
13758            }
13759            return ps.getBlockUninstall(userId);
13760        }
13761    }
13762
13763    @Override
13764    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13765        int callingUid = Binder.getCallingUid();
13766        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13767            throw new SecurityException(
13768                    "setRequiredForSystemUser can only be run by the system or root");
13769        }
13770        synchronized (mPackages) {
13771            PackageSetting ps = mSettings.mPackages.get(packageName);
13772            if (ps == null) {
13773                Log.w(TAG, "Package doesn't exist: " + packageName);
13774                return false;
13775            }
13776            if (systemUserApp) {
13777                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13778            } else {
13779                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13780            }
13781            mSettings.writeLPr();
13782        }
13783        return true;
13784    }
13785
13786    /*
13787     * This method handles package deletion in general
13788     */
13789    private boolean deletePackageLI(String packageName, UserHandle user,
13790            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13791            int flags, PackageRemovedInfo outInfo,
13792            boolean writeSettings) {
13793        if (packageName == null) {
13794            Slog.w(TAG, "Attempt to delete null packageName.");
13795            return false;
13796        }
13797        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13798        PackageSetting ps;
13799        boolean dataOnly = false;
13800        int removeUser = -1;
13801        int appId = -1;
13802        synchronized (mPackages) {
13803            ps = mSettings.mPackages.get(packageName);
13804            if (ps == null) {
13805                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13806                return false;
13807            }
13808            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13809                    && user.getIdentifier() != UserHandle.USER_ALL) {
13810                // The caller is asking that the package only be deleted for a single
13811                // user.  To do this, we just mark its uninstalled state and delete
13812                // its data.  If this is a system app, we only allow this to happen if
13813                // they have set the special DELETE_SYSTEM_APP which requests different
13814                // semantics than normal for uninstalling system apps.
13815                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13816                final int userId = user.getIdentifier();
13817                ps.setUserState(userId,
13818                        COMPONENT_ENABLED_STATE_DEFAULT,
13819                        false, //installed
13820                        true,  //stopped
13821                        true,  //notLaunched
13822                        false, //hidden
13823                        false, //suspended
13824                        null, null, null,
13825                        false, // blockUninstall
13826                        ps.readUserState(userId).domainVerificationStatus, 0);
13827                if (!isSystemApp(ps)) {
13828                    // Do not uninstall the APK if an app should be cached
13829                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13830                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13831                        // Other user still have this package installed, so all
13832                        // we need to do is clear this user's data and save that
13833                        // it is uninstalled.
13834                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13835                        removeUser = user.getIdentifier();
13836                        appId = ps.appId;
13837                        scheduleWritePackageRestrictionsLocked(removeUser);
13838                    } else {
13839                        // We need to set it back to 'installed' so the uninstall
13840                        // broadcasts will be sent correctly.
13841                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13842                        ps.setInstalled(true, user.getIdentifier());
13843                    }
13844                } else {
13845                    // This is a system app, so we assume that the
13846                    // other users still have this package installed, so all
13847                    // we need to do is clear this user's data and save that
13848                    // it is uninstalled.
13849                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13850                    removeUser = user.getIdentifier();
13851                    appId = ps.appId;
13852                    scheduleWritePackageRestrictionsLocked(removeUser);
13853                }
13854            }
13855        }
13856
13857        if (removeUser >= 0) {
13858            // From above, we determined that we are deleting this only
13859            // for a single user.  Continue the work here.
13860            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13861            if (outInfo != null) {
13862                outInfo.removedPackage = packageName;
13863                outInfo.removedAppId = appId;
13864                outInfo.removedUsers = new int[] {removeUser};
13865            }
13866            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13867            removeKeystoreDataIfNeeded(removeUser, appId);
13868            schedulePackageCleaning(packageName, removeUser, false);
13869            synchronized (mPackages) {
13870                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13871                    scheduleWritePackageRestrictionsLocked(removeUser);
13872                }
13873                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13874            }
13875            return true;
13876        }
13877
13878        if (dataOnly) {
13879            // Delete application data first
13880            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13881            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13882            return true;
13883        }
13884
13885        boolean ret = false;
13886        if (isSystemApp(ps)) {
13887            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13888            // When an updated system application is deleted we delete the existing resources as well and
13889            // fall back to existing code in system partition
13890            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13891                    flags, outInfo, writeSettings);
13892        } else {
13893            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13894            // Kill application pre-emptively especially for apps on sd.
13895            killApplication(packageName, ps.appId, "uninstall pkg");
13896            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13897                    allUserHandles, perUserInstalled,
13898                    outInfo, writeSettings);
13899        }
13900
13901        return ret;
13902    }
13903
13904    private final static class ClearStorageConnection implements ServiceConnection {
13905        IMediaContainerService mContainerService;
13906
13907        @Override
13908        public void onServiceConnected(ComponentName name, IBinder service) {
13909            synchronized (this) {
13910                mContainerService = IMediaContainerService.Stub.asInterface(service);
13911                notifyAll();
13912            }
13913        }
13914
13915        @Override
13916        public void onServiceDisconnected(ComponentName name) {
13917        }
13918    }
13919
13920    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13921        final boolean mounted;
13922        if (Environment.isExternalStorageEmulated()) {
13923            mounted = true;
13924        } else {
13925            final String status = Environment.getExternalStorageState();
13926
13927            mounted = status.equals(Environment.MEDIA_MOUNTED)
13928                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13929        }
13930
13931        if (!mounted) {
13932            return;
13933        }
13934
13935        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13936        int[] users;
13937        if (userId == UserHandle.USER_ALL) {
13938            users = sUserManager.getUserIds();
13939        } else {
13940            users = new int[] { userId };
13941        }
13942        final ClearStorageConnection conn = new ClearStorageConnection();
13943        if (mContext.bindServiceAsUser(
13944                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13945            try {
13946                for (int curUser : users) {
13947                    long timeout = SystemClock.uptimeMillis() + 5000;
13948                    synchronized (conn) {
13949                        long now = SystemClock.uptimeMillis();
13950                        while (conn.mContainerService == null && now < timeout) {
13951                            try {
13952                                conn.wait(timeout - now);
13953                            } catch (InterruptedException e) {
13954                            }
13955                        }
13956                    }
13957                    if (conn.mContainerService == null) {
13958                        return;
13959                    }
13960
13961                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13962                    clearDirectory(conn.mContainerService,
13963                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13964                    if (allData) {
13965                        clearDirectory(conn.mContainerService,
13966                                userEnv.buildExternalStorageAppDataDirs(packageName));
13967                        clearDirectory(conn.mContainerService,
13968                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13969                    }
13970                }
13971            } finally {
13972                mContext.unbindService(conn);
13973            }
13974        }
13975    }
13976
13977    @Override
13978    public void clearApplicationUserData(final String packageName,
13979            final IPackageDataObserver observer, final int userId) {
13980        mContext.enforceCallingOrSelfPermission(
13981                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13982        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13983        // Queue up an async operation since the package deletion may take a little while.
13984        mHandler.post(new Runnable() {
13985            public void run() {
13986                mHandler.removeCallbacks(this);
13987                final boolean succeeded;
13988                synchronized (mInstallLock) {
13989                    succeeded = clearApplicationUserDataLI(packageName, userId);
13990                }
13991                clearExternalStorageDataSync(packageName, userId, true);
13992                if (succeeded) {
13993                    // invoke DeviceStorageMonitor's update method to clear any notifications
13994                    DeviceStorageMonitorInternal
13995                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13996                    if (dsm != null) {
13997                        dsm.checkMemory();
13998                    }
13999                }
14000                if(observer != null) {
14001                    try {
14002                        observer.onRemoveCompleted(packageName, succeeded);
14003                    } catch (RemoteException e) {
14004                        Log.i(TAG, "Observer no longer exists.");
14005                    }
14006                } //end if observer
14007            } //end run
14008        });
14009    }
14010
14011    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14012        if (packageName == null) {
14013            Slog.w(TAG, "Attempt to delete null packageName.");
14014            return false;
14015        }
14016
14017        // Try finding details about the requested package
14018        PackageParser.Package pkg;
14019        synchronized (mPackages) {
14020            pkg = mPackages.get(packageName);
14021            if (pkg == null) {
14022                final PackageSetting ps = mSettings.mPackages.get(packageName);
14023                if (ps != null) {
14024                    pkg = ps.pkg;
14025                }
14026            }
14027
14028            if (pkg == null) {
14029                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14030                return false;
14031            }
14032
14033            PackageSetting ps = (PackageSetting) pkg.mExtras;
14034            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14035        }
14036
14037        // Always delete data directories for package, even if we found no other
14038        // record of app. This helps users recover from UID mismatches without
14039        // resorting to a full data wipe.
14040        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14041        if (retCode < 0) {
14042            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
14043            return false;
14044        }
14045
14046        final int appId = pkg.applicationInfo.uid;
14047        removeKeystoreDataIfNeeded(userId, appId);
14048
14049        // Create a native library symlink only if we have native libraries
14050        // and if the native libraries are 32 bit libraries. We do not provide
14051        // this symlink for 64 bit libraries.
14052        if (pkg.applicationInfo.primaryCpuAbi != null &&
14053                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14054            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14055            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14056                    nativeLibPath, userId) < 0) {
14057                Slog.w(TAG, "Failed linking native library dir");
14058                return false;
14059            }
14060        }
14061
14062        return true;
14063    }
14064
14065    /**
14066     * Reverts user permission state changes (permissions and flags) in
14067     * all packages for a given user.
14068     *
14069     * @param userId The device user for which to do a reset.
14070     */
14071    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14072        final int packageCount = mPackages.size();
14073        for (int i = 0; i < packageCount; i++) {
14074            PackageParser.Package pkg = mPackages.valueAt(i);
14075            PackageSetting ps = (PackageSetting) pkg.mExtras;
14076            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14077        }
14078    }
14079
14080    /**
14081     * Reverts user permission state changes (permissions and flags).
14082     *
14083     * @param ps The package for which to reset.
14084     * @param userId The device user for which to do a reset.
14085     */
14086    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14087            final PackageSetting ps, final int userId) {
14088        if (ps.pkg == null) {
14089            return;
14090        }
14091
14092        // These are flags that can change base on user actions.
14093        final int userSettableMask = FLAG_PERMISSION_USER_SET
14094                | FLAG_PERMISSION_USER_FIXED
14095                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14096                | FLAG_PERMISSION_REVIEW_REQUIRED;
14097
14098        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14099                | FLAG_PERMISSION_POLICY_FIXED;
14100
14101        boolean writeInstallPermissions = false;
14102        boolean writeRuntimePermissions = false;
14103
14104        final int permissionCount = ps.pkg.requestedPermissions.size();
14105        for (int i = 0; i < permissionCount; i++) {
14106            String permission = ps.pkg.requestedPermissions.get(i);
14107
14108            BasePermission bp = mSettings.mPermissions.get(permission);
14109            if (bp == null) {
14110                continue;
14111            }
14112
14113            // If shared user we just reset the state to which only this app contributed.
14114            if (ps.sharedUser != null) {
14115                boolean used = false;
14116                final int packageCount = ps.sharedUser.packages.size();
14117                for (int j = 0; j < packageCount; j++) {
14118                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14119                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14120                            && pkg.pkg.requestedPermissions.contains(permission)) {
14121                        used = true;
14122                        break;
14123                    }
14124                }
14125                if (used) {
14126                    continue;
14127                }
14128            }
14129
14130            PermissionsState permissionsState = ps.getPermissionsState();
14131
14132            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14133
14134            // Always clear the user settable flags.
14135            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14136                    bp.name) != null;
14137            // If permission review is enabled and this is a legacy app, mark the
14138            // permission as requiring a review as this is the initial state.
14139            int flags = 0;
14140            if (Build.PERMISSIONS_REVIEW_REQUIRED
14141                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14142                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14143            }
14144            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14145                if (hasInstallState) {
14146                    writeInstallPermissions = true;
14147                } else {
14148                    writeRuntimePermissions = true;
14149                }
14150            }
14151
14152            // Below is only runtime permission handling.
14153            if (!bp.isRuntime()) {
14154                continue;
14155            }
14156
14157            // Never clobber system or policy.
14158            if ((oldFlags & policyOrSystemFlags) != 0) {
14159                continue;
14160            }
14161
14162            // If this permission was granted by default, make sure it is.
14163            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14164                if (permissionsState.grantRuntimePermission(bp, userId)
14165                        != PERMISSION_OPERATION_FAILURE) {
14166                    writeRuntimePermissions = true;
14167                }
14168            // If permission review is enabled the permissions for a legacy apps
14169            // are represented as constantly granted runtime ones, so don't revoke.
14170            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14171                // Otherwise, reset the permission.
14172                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14173                switch (revokeResult) {
14174                    case PERMISSION_OPERATION_SUCCESS: {
14175                        writeRuntimePermissions = true;
14176                    } break;
14177
14178                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14179                        writeRuntimePermissions = true;
14180                        final int appId = ps.appId;
14181                        mHandler.post(new Runnable() {
14182                            @Override
14183                            public void run() {
14184                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14185                            }
14186                        });
14187                    } break;
14188                }
14189            }
14190        }
14191
14192        // Synchronously write as we are taking permissions away.
14193        if (writeRuntimePermissions) {
14194            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14195        }
14196
14197        // Synchronously write as we are taking permissions away.
14198        if (writeInstallPermissions) {
14199            mSettings.writeLPr();
14200        }
14201    }
14202
14203    /**
14204     * Remove entries from the keystore daemon. Will only remove it if the
14205     * {@code appId} is valid.
14206     */
14207    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14208        if (appId < 0) {
14209            return;
14210        }
14211
14212        final KeyStore keyStore = KeyStore.getInstance();
14213        if (keyStore != null) {
14214            if (userId == UserHandle.USER_ALL) {
14215                for (final int individual : sUserManager.getUserIds()) {
14216                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14217                }
14218            } else {
14219                keyStore.clearUid(UserHandle.getUid(userId, appId));
14220            }
14221        } else {
14222            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14223        }
14224    }
14225
14226    @Override
14227    public void deleteApplicationCacheFiles(final String packageName,
14228            final IPackageDataObserver observer) {
14229        mContext.enforceCallingOrSelfPermission(
14230                android.Manifest.permission.DELETE_CACHE_FILES, null);
14231        // Queue up an async operation since the package deletion may take a little while.
14232        final int userId = UserHandle.getCallingUserId();
14233        mHandler.post(new Runnable() {
14234            public void run() {
14235                mHandler.removeCallbacks(this);
14236                final boolean succeded;
14237                synchronized (mInstallLock) {
14238                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14239                }
14240                clearExternalStorageDataSync(packageName, userId, false);
14241                if (observer != null) {
14242                    try {
14243                        observer.onRemoveCompleted(packageName, succeded);
14244                    } catch (RemoteException e) {
14245                        Log.i(TAG, "Observer no longer exists.");
14246                    }
14247                } //end if observer
14248            } //end run
14249        });
14250    }
14251
14252    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14253        if (packageName == null) {
14254            Slog.w(TAG, "Attempt to delete null packageName.");
14255            return false;
14256        }
14257        PackageParser.Package p;
14258        synchronized (mPackages) {
14259            p = mPackages.get(packageName);
14260        }
14261        if (p == null) {
14262            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14263            return false;
14264        }
14265        final ApplicationInfo applicationInfo = p.applicationInfo;
14266        if (applicationInfo == null) {
14267            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14268            return false;
14269        }
14270        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14271        if (retCode < 0) {
14272            Slog.w(TAG, "Couldn't remove cache files for package: "
14273                       + packageName + " u" + userId);
14274            return false;
14275        }
14276        return true;
14277    }
14278
14279    @Override
14280    public void getPackageSizeInfo(final String packageName, int userHandle,
14281            final IPackageStatsObserver observer) {
14282        mContext.enforceCallingOrSelfPermission(
14283                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14284        if (packageName == null) {
14285            throw new IllegalArgumentException("Attempt to get size of null packageName");
14286        }
14287
14288        PackageStats stats = new PackageStats(packageName, userHandle);
14289
14290        /*
14291         * Queue up an async operation since the package measurement may take a
14292         * little while.
14293         */
14294        Message msg = mHandler.obtainMessage(INIT_COPY);
14295        msg.obj = new MeasureParams(stats, observer);
14296        mHandler.sendMessage(msg);
14297    }
14298
14299    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14300            PackageStats pStats) {
14301        if (packageName == null) {
14302            Slog.w(TAG, "Attempt to get size of null packageName.");
14303            return false;
14304        }
14305        PackageParser.Package p;
14306        boolean dataOnly = false;
14307        String libDirRoot = null;
14308        String asecPath = null;
14309        PackageSetting ps = null;
14310        synchronized (mPackages) {
14311            p = mPackages.get(packageName);
14312            ps = mSettings.mPackages.get(packageName);
14313            if(p == null) {
14314                dataOnly = true;
14315                if((ps == null) || (ps.pkg == null)) {
14316                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14317                    return false;
14318                }
14319                p = ps.pkg;
14320            }
14321            if (ps != null) {
14322                libDirRoot = ps.legacyNativeLibraryPathString;
14323            }
14324            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14325                final long token = Binder.clearCallingIdentity();
14326                try {
14327                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14328                    if (secureContainerId != null) {
14329                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14330                    }
14331                } finally {
14332                    Binder.restoreCallingIdentity(token);
14333                }
14334            }
14335        }
14336        String publicSrcDir = null;
14337        if(!dataOnly) {
14338            final ApplicationInfo applicationInfo = p.applicationInfo;
14339            if (applicationInfo == null) {
14340                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14341                return false;
14342            }
14343            if (p.isForwardLocked()) {
14344                publicSrcDir = applicationInfo.getBaseResourcePath();
14345            }
14346        }
14347        // TODO: extend to measure size of split APKs
14348        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14349        // not just the first level.
14350        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14351        // just the primary.
14352        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14353
14354        String apkPath;
14355        File packageDir = new File(p.codePath);
14356
14357        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14358            apkPath = packageDir.getAbsolutePath();
14359            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14360            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14361                libDirRoot = null;
14362            }
14363        } else {
14364            apkPath = p.baseCodePath;
14365        }
14366
14367        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14368                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14369        if (res < 0) {
14370            return false;
14371        }
14372
14373        // Fix-up for forward-locked applications in ASEC containers.
14374        if (!isExternal(p)) {
14375            pStats.codeSize += pStats.externalCodeSize;
14376            pStats.externalCodeSize = 0L;
14377        }
14378
14379        return true;
14380    }
14381
14382
14383    @Override
14384    public void addPackageToPreferred(String packageName) {
14385        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14386    }
14387
14388    @Override
14389    public void removePackageFromPreferred(String packageName) {
14390        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14391    }
14392
14393    @Override
14394    public List<PackageInfo> getPreferredPackages(int flags) {
14395        return new ArrayList<PackageInfo>();
14396    }
14397
14398    private int getUidTargetSdkVersionLockedLPr(int uid) {
14399        Object obj = mSettings.getUserIdLPr(uid);
14400        if (obj instanceof SharedUserSetting) {
14401            final SharedUserSetting sus = (SharedUserSetting) obj;
14402            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14403            final Iterator<PackageSetting> it = sus.packages.iterator();
14404            while (it.hasNext()) {
14405                final PackageSetting ps = it.next();
14406                if (ps.pkg != null) {
14407                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14408                    if (v < vers) vers = v;
14409                }
14410            }
14411            return vers;
14412        } else if (obj instanceof PackageSetting) {
14413            final PackageSetting ps = (PackageSetting) obj;
14414            if (ps.pkg != null) {
14415                return ps.pkg.applicationInfo.targetSdkVersion;
14416            }
14417        }
14418        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14419    }
14420
14421    @Override
14422    public void addPreferredActivity(IntentFilter filter, int match,
14423            ComponentName[] set, ComponentName activity, int userId) {
14424        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14425                "Adding preferred");
14426    }
14427
14428    private void addPreferredActivityInternal(IntentFilter filter, int match,
14429            ComponentName[] set, ComponentName activity, boolean always, int userId,
14430            String opname) {
14431        // writer
14432        int callingUid = Binder.getCallingUid();
14433        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14434        if (filter.countActions() == 0) {
14435            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14436            return;
14437        }
14438        synchronized (mPackages) {
14439            if (mContext.checkCallingOrSelfPermission(
14440                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14441                    != PackageManager.PERMISSION_GRANTED) {
14442                if (getUidTargetSdkVersionLockedLPr(callingUid)
14443                        < Build.VERSION_CODES.FROYO) {
14444                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14445                            + callingUid);
14446                    return;
14447                }
14448                mContext.enforceCallingOrSelfPermission(
14449                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14450            }
14451
14452            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14453            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14454                    + userId + ":");
14455            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14456            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14457            scheduleWritePackageRestrictionsLocked(userId);
14458        }
14459    }
14460
14461    @Override
14462    public void replacePreferredActivity(IntentFilter filter, int match,
14463            ComponentName[] set, ComponentName activity, int userId) {
14464        if (filter.countActions() != 1) {
14465            throw new IllegalArgumentException(
14466                    "replacePreferredActivity expects filter to have only 1 action.");
14467        }
14468        if (filter.countDataAuthorities() != 0
14469                || filter.countDataPaths() != 0
14470                || filter.countDataSchemes() > 1
14471                || filter.countDataTypes() != 0) {
14472            throw new IllegalArgumentException(
14473                    "replacePreferredActivity expects filter to have no data authorities, " +
14474                    "paths, or types; and at most one scheme.");
14475        }
14476
14477        final int callingUid = Binder.getCallingUid();
14478        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14479        synchronized (mPackages) {
14480            if (mContext.checkCallingOrSelfPermission(
14481                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14482                    != PackageManager.PERMISSION_GRANTED) {
14483                if (getUidTargetSdkVersionLockedLPr(callingUid)
14484                        < Build.VERSION_CODES.FROYO) {
14485                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14486                            + Binder.getCallingUid());
14487                    return;
14488                }
14489                mContext.enforceCallingOrSelfPermission(
14490                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14491            }
14492
14493            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14494            if (pir != null) {
14495                // Get all of the existing entries that exactly match this filter.
14496                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14497                if (existing != null && existing.size() == 1) {
14498                    PreferredActivity cur = existing.get(0);
14499                    if (DEBUG_PREFERRED) {
14500                        Slog.i(TAG, "Checking replace of preferred:");
14501                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14502                        if (!cur.mPref.mAlways) {
14503                            Slog.i(TAG, "  -- CUR; not mAlways!");
14504                        } else {
14505                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14506                            Slog.i(TAG, "  -- CUR: mSet="
14507                                    + Arrays.toString(cur.mPref.mSetComponents));
14508                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14509                            Slog.i(TAG, "  -- NEW: mMatch="
14510                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14511                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14512                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14513                        }
14514                    }
14515                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14516                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14517                            && cur.mPref.sameSet(set)) {
14518                        // Setting the preferred activity to what it happens to be already
14519                        if (DEBUG_PREFERRED) {
14520                            Slog.i(TAG, "Replacing with same preferred activity "
14521                                    + cur.mPref.mShortComponent + " for user "
14522                                    + userId + ":");
14523                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14524                        }
14525                        return;
14526                    }
14527                }
14528
14529                if (existing != null) {
14530                    if (DEBUG_PREFERRED) {
14531                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14532                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14533                    }
14534                    for (int i = 0; i < existing.size(); i++) {
14535                        PreferredActivity pa = existing.get(i);
14536                        if (DEBUG_PREFERRED) {
14537                            Slog.i(TAG, "Removing existing preferred activity "
14538                                    + pa.mPref.mComponent + ":");
14539                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14540                        }
14541                        pir.removeFilter(pa);
14542                    }
14543                }
14544            }
14545            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14546                    "Replacing preferred");
14547        }
14548    }
14549
14550    @Override
14551    public void clearPackagePreferredActivities(String packageName) {
14552        final int uid = Binder.getCallingUid();
14553        // writer
14554        synchronized (mPackages) {
14555            PackageParser.Package pkg = mPackages.get(packageName);
14556            if (pkg == null || pkg.applicationInfo.uid != uid) {
14557                if (mContext.checkCallingOrSelfPermission(
14558                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14559                        != PackageManager.PERMISSION_GRANTED) {
14560                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14561                            < Build.VERSION_CODES.FROYO) {
14562                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14563                                + Binder.getCallingUid());
14564                        return;
14565                    }
14566                    mContext.enforceCallingOrSelfPermission(
14567                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14568                }
14569            }
14570
14571            int user = UserHandle.getCallingUserId();
14572            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14573                scheduleWritePackageRestrictionsLocked(user);
14574            }
14575        }
14576    }
14577
14578    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14579    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14580        ArrayList<PreferredActivity> removed = null;
14581        boolean changed = false;
14582        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14583            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14584            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14585            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14586                continue;
14587            }
14588            Iterator<PreferredActivity> it = pir.filterIterator();
14589            while (it.hasNext()) {
14590                PreferredActivity pa = it.next();
14591                // Mark entry for removal only if it matches the package name
14592                // and the entry is of type "always".
14593                if (packageName == null ||
14594                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14595                                && pa.mPref.mAlways)) {
14596                    if (removed == null) {
14597                        removed = new ArrayList<PreferredActivity>();
14598                    }
14599                    removed.add(pa);
14600                }
14601            }
14602            if (removed != null) {
14603                for (int j=0; j<removed.size(); j++) {
14604                    PreferredActivity pa = removed.get(j);
14605                    pir.removeFilter(pa);
14606                }
14607                changed = true;
14608            }
14609        }
14610        return changed;
14611    }
14612
14613    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14614    private void clearIntentFilterVerificationsLPw(int userId) {
14615        final int packageCount = mPackages.size();
14616        for (int i = 0; i < packageCount; i++) {
14617            PackageParser.Package pkg = mPackages.valueAt(i);
14618            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14619        }
14620    }
14621
14622    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14623    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14624        if (userId == UserHandle.USER_ALL) {
14625            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14626                    sUserManager.getUserIds())) {
14627                for (int oneUserId : sUserManager.getUserIds()) {
14628                    scheduleWritePackageRestrictionsLocked(oneUserId);
14629                }
14630            }
14631        } else {
14632            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14633                scheduleWritePackageRestrictionsLocked(userId);
14634            }
14635        }
14636    }
14637
14638    void clearDefaultBrowserIfNeeded(String packageName) {
14639        for (int oneUserId : sUserManager.getUserIds()) {
14640            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14641            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14642            if (packageName.equals(defaultBrowserPackageName)) {
14643                setDefaultBrowserPackageName(null, oneUserId);
14644            }
14645        }
14646    }
14647
14648    @Override
14649    public void resetApplicationPreferences(int userId) {
14650        mContext.enforceCallingOrSelfPermission(
14651                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14652        // writer
14653        synchronized (mPackages) {
14654            final long identity = Binder.clearCallingIdentity();
14655            try {
14656                clearPackagePreferredActivitiesLPw(null, userId);
14657                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14658                // TODO: We have to reset the default SMS and Phone. This requires
14659                // significant refactoring to keep all default apps in the package
14660                // manager (cleaner but more work) or have the services provide
14661                // callbacks to the package manager to request a default app reset.
14662                applyFactoryDefaultBrowserLPw(userId);
14663                clearIntentFilterVerificationsLPw(userId);
14664                primeDomainVerificationsLPw(userId);
14665                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14666                scheduleWritePackageRestrictionsLocked(userId);
14667            } finally {
14668                Binder.restoreCallingIdentity(identity);
14669            }
14670        }
14671    }
14672
14673    @Override
14674    public int getPreferredActivities(List<IntentFilter> outFilters,
14675            List<ComponentName> outActivities, String packageName) {
14676
14677        int num = 0;
14678        final int userId = UserHandle.getCallingUserId();
14679        // reader
14680        synchronized (mPackages) {
14681            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14682            if (pir != null) {
14683                final Iterator<PreferredActivity> it = pir.filterIterator();
14684                while (it.hasNext()) {
14685                    final PreferredActivity pa = it.next();
14686                    if (packageName == null
14687                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14688                                    && pa.mPref.mAlways)) {
14689                        if (outFilters != null) {
14690                            outFilters.add(new IntentFilter(pa));
14691                        }
14692                        if (outActivities != null) {
14693                            outActivities.add(pa.mPref.mComponent);
14694                        }
14695                    }
14696                }
14697            }
14698        }
14699
14700        return num;
14701    }
14702
14703    @Override
14704    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14705            int userId) {
14706        int callingUid = Binder.getCallingUid();
14707        if (callingUid != Process.SYSTEM_UID) {
14708            throw new SecurityException(
14709                    "addPersistentPreferredActivity can only be run by the system");
14710        }
14711        if (filter.countActions() == 0) {
14712            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14713            return;
14714        }
14715        synchronized (mPackages) {
14716            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14717                    " :");
14718            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14719            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14720                    new PersistentPreferredActivity(filter, activity));
14721            scheduleWritePackageRestrictionsLocked(userId);
14722        }
14723    }
14724
14725    @Override
14726    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14727        int callingUid = Binder.getCallingUid();
14728        if (callingUid != Process.SYSTEM_UID) {
14729            throw new SecurityException(
14730                    "clearPackagePersistentPreferredActivities can only be run by the system");
14731        }
14732        ArrayList<PersistentPreferredActivity> removed = null;
14733        boolean changed = false;
14734        synchronized (mPackages) {
14735            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14736                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14737                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14738                        .valueAt(i);
14739                if (userId != thisUserId) {
14740                    continue;
14741                }
14742                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14743                while (it.hasNext()) {
14744                    PersistentPreferredActivity ppa = it.next();
14745                    // Mark entry for removal only if it matches the package name.
14746                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14747                        if (removed == null) {
14748                            removed = new ArrayList<PersistentPreferredActivity>();
14749                        }
14750                        removed.add(ppa);
14751                    }
14752                }
14753                if (removed != null) {
14754                    for (int j=0; j<removed.size(); j++) {
14755                        PersistentPreferredActivity ppa = removed.get(j);
14756                        ppir.removeFilter(ppa);
14757                    }
14758                    changed = true;
14759                }
14760            }
14761
14762            if (changed) {
14763                scheduleWritePackageRestrictionsLocked(userId);
14764            }
14765        }
14766    }
14767
14768    /**
14769     * Common machinery for picking apart a restored XML blob and passing
14770     * it to a caller-supplied functor to be applied to the running system.
14771     */
14772    private void restoreFromXml(XmlPullParser parser, int userId,
14773            String expectedStartTag, BlobXmlRestorer functor)
14774            throws IOException, XmlPullParserException {
14775        int type;
14776        while ((type = parser.next()) != XmlPullParser.START_TAG
14777                && type != XmlPullParser.END_DOCUMENT) {
14778        }
14779        if (type != XmlPullParser.START_TAG) {
14780            // oops didn't find a start tag?!
14781            if (DEBUG_BACKUP) {
14782                Slog.e(TAG, "Didn't find start tag during restore");
14783            }
14784            return;
14785        }
14786
14787        // this is supposed to be TAG_PREFERRED_BACKUP
14788        if (!expectedStartTag.equals(parser.getName())) {
14789            if (DEBUG_BACKUP) {
14790                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14791            }
14792            return;
14793        }
14794
14795        // skip interfering stuff, then we're aligned with the backing implementation
14796        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14797        functor.apply(parser, userId);
14798    }
14799
14800    private interface BlobXmlRestorer {
14801        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14802    }
14803
14804    /**
14805     * Non-Binder method, support for the backup/restore mechanism: write the
14806     * full set of preferred activities in its canonical XML format.  Returns the
14807     * XML output as a byte array, or null if there is none.
14808     */
14809    @Override
14810    public byte[] getPreferredActivityBackup(int userId) {
14811        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14812            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14813        }
14814
14815        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14816        try {
14817            final XmlSerializer serializer = new FastXmlSerializer();
14818            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14819            serializer.startDocument(null, true);
14820            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14821
14822            synchronized (mPackages) {
14823                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14824            }
14825
14826            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14827            serializer.endDocument();
14828            serializer.flush();
14829        } catch (Exception e) {
14830            if (DEBUG_BACKUP) {
14831                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14832            }
14833            return null;
14834        }
14835
14836        return dataStream.toByteArray();
14837    }
14838
14839    @Override
14840    public void restorePreferredActivities(byte[] backup, int userId) {
14841        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14842            throw new SecurityException("Only the system may call restorePreferredActivities()");
14843        }
14844
14845        try {
14846            final XmlPullParser parser = Xml.newPullParser();
14847            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14848            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14849                    new BlobXmlRestorer() {
14850                        @Override
14851                        public void apply(XmlPullParser parser, int userId)
14852                                throws XmlPullParserException, IOException {
14853                            synchronized (mPackages) {
14854                                mSettings.readPreferredActivitiesLPw(parser, userId);
14855                            }
14856                        }
14857                    } );
14858        } catch (Exception e) {
14859            if (DEBUG_BACKUP) {
14860                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14861            }
14862        }
14863    }
14864
14865    /**
14866     * Non-Binder method, support for the backup/restore mechanism: write the
14867     * default browser (etc) settings in its canonical XML format.  Returns the default
14868     * browser XML representation as a byte array, or null if there is none.
14869     */
14870    @Override
14871    public byte[] getDefaultAppsBackup(int userId) {
14872        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14873            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14874        }
14875
14876        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14877        try {
14878            final XmlSerializer serializer = new FastXmlSerializer();
14879            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14880            serializer.startDocument(null, true);
14881            serializer.startTag(null, TAG_DEFAULT_APPS);
14882
14883            synchronized (mPackages) {
14884                mSettings.writeDefaultAppsLPr(serializer, userId);
14885            }
14886
14887            serializer.endTag(null, TAG_DEFAULT_APPS);
14888            serializer.endDocument();
14889            serializer.flush();
14890        } catch (Exception e) {
14891            if (DEBUG_BACKUP) {
14892                Slog.e(TAG, "Unable to write default apps for backup", e);
14893            }
14894            return null;
14895        }
14896
14897        return dataStream.toByteArray();
14898    }
14899
14900    @Override
14901    public void restoreDefaultApps(byte[] backup, int userId) {
14902        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14903            throw new SecurityException("Only the system may call restoreDefaultApps()");
14904        }
14905
14906        try {
14907            final XmlPullParser parser = Xml.newPullParser();
14908            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14909            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14910                    new BlobXmlRestorer() {
14911                        @Override
14912                        public void apply(XmlPullParser parser, int userId)
14913                                throws XmlPullParserException, IOException {
14914                            synchronized (mPackages) {
14915                                mSettings.readDefaultAppsLPw(parser, userId);
14916                            }
14917                        }
14918                    } );
14919        } catch (Exception e) {
14920            if (DEBUG_BACKUP) {
14921                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14922            }
14923        }
14924    }
14925
14926    @Override
14927    public byte[] getIntentFilterVerificationBackup(int userId) {
14928        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14929            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14930        }
14931
14932        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14933        try {
14934            final XmlSerializer serializer = new FastXmlSerializer();
14935            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14936            serializer.startDocument(null, true);
14937            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14938
14939            synchronized (mPackages) {
14940                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14941            }
14942
14943            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14944            serializer.endDocument();
14945            serializer.flush();
14946        } catch (Exception e) {
14947            if (DEBUG_BACKUP) {
14948                Slog.e(TAG, "Unable to write default apps for backup", e);
14949            }
14950            return null;
14951        }
14952
14953        return dataStream.toByteArray();
14954    }
14955
14956    @Override
14957    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14958        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14959            throw new SecurityException("Only the system may call restorePreferredActivities()");
14960        }
14961
14962        try {
14963            final XmlPullParser parser = Xml.newPullParser();
14964            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14965            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14966                    new BlobXmlRestorer() {
14967                        @Override
14968                        public void apply(XmlPullParser parser, int userId)
14969                                throws XmlPullParserException, IOException {
14970                            synchronized (mPackages) {
14971                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14972                                mSettings.writeLPr();
14973                            }
14974                        }
14975                    } );
14976        } catch (Exception e) {
14977            if (DEBUG_BACKUP) {
14978                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14979            }
14980        }
14981    }
14982
14983    @Override
14984    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14985            int sourceUserId, int targetUserId, int flags) {
14986        mContext.enforceCallingOrSelfPermission(
14987                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14988        int callingUid = Binder.getCallingUid();
14989        enforceOwnerRights(ownerPackage, callingUid);
14990        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14991        if (intentFilter.countActions() == 0) {
14992            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14993            return;
14994        }
14995        synchronized (mPackages) {
14996            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14997                    ownerPackage, targetUserId, flags);
14998            CrossProfileIntentResolver resolver =
14999                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15000            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15001            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15002            if (existing != null) {
15003                int size = existing.size();
15004                for (int i = 0; i < size; i++) {
15005                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15006                        return;
15007                    }
15008                }
15009            }
15010            resolver.addFilter(newFilter);
15011            scheduleWritePackageRestrictionsLocked(sourceUserId);
15012        }
15013    }
15014
15015    @Override
15016    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15017        mContext.enforceCallingOrSelfPermission(
15018                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15019        int callingUid = Binder.getCallingUid();
15020        enforceOwnerRights(ownerPackage, callingUid);
15021        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15022        synchronized (mPackages) {
15023            CrossProfileIntentResolver resolver =
15024                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15025            ArraySet<CrossProfileIntentFilter> set =
15026                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15027            for (CrossProfileIntentFilter filter : set) {
15028                if (filter.getOwnerPackage().equals(ownerPackage)) {
15029                    resolver.removeFilter(filter);
15030                }
15031            }
15032            scheduleWritePackageRestrictionsLocked(sourceUserId);
15033        }
15034    }
15035
15036    // Enforcing that callingUid is owning pkg on userId
15037    private void enforceOwnerRights(String pkg, int callingUid) {
15038        // The system owns everything.
15039        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15040            return;
15041        }
15042        int callingUserId = UserHandle.getUserId(callingUid);
15043        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15044        if (pi == null) {
15045            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15046                    + callingUserId);
15047        }
15048        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15049            throw new SecurityException("Calling uid " + callingUid
15050                    + " does not own package " + pkg);
15051        }
15052    }
15053
15054    @Override
15055    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15056        Intent intent = new Intent(Intent.ACTION_MAIN);
15057        intent.addCategory(Intent.CATEGORY_HOME);
15058
15059        final int callingUserId = UserHandle.getCallingUserId();
15060        List<ResolveInfo> list = queryIntentActivities(intent, null,
15061                PackageManager.GET_META_DATA, callingUserId);
15062        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15063                true, false, false, callingUserId);
15064
15065        allHomeCandidates.clear();
15066        if (list != null) {
15067            for (ResolveInfo ri : list) {
15068                allHomeCandidates.add(ri);
15069            }
15070        }
15071        return (preferred == null || preferred.activityInfo == null)
15072                ? null
15073                : new ComponentName(preferred.activityInfo.packageName,
15074                        preferred.activityInfo.name);
15075    }
15076
15077    @Override
15078    public void setApplicationEnabledSetting(String appPackageName,
15079            int newState, int flags, int userId, String callingPackage) {
15080        if (!sUserManager.exists(userId)) return;
15081        if (callingPackage == null) {
15082            callingPackage = Integer.toString(Binder.getCallingUid());
15083        }
15084        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15085    }
15086
15087    @Override
15088    public void setComponentEnabledSetting(ComponentName componentName,
15089            int newState, int flags, int userId) {
15090        if (!sUserManager.exists(userId)) return;
15091        setEnabledSetting(componentName.getPackageName(),
15092                componentName.getClassName(), newState, flags, userId, null);
15093    }
15094
15095    private void setEnabledSetting(final String packageName, String className, int newState,
15096            final int flags, int userId, String callingPackage) {
15097        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15098              || newState == COMPONENT_ENABLED_STATE_ENABLED
15099              || newState == COMPONENT_ENABLED_STATE_DISABLED
15100              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15101              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15102            throw new IllegalArgumentException("Invalid new component state: "
15103                    + newState);
15104        }
15105        PackageSetting pkgSetting;
15106        final int uid = Binder.getCallingUid();
15107        final int permission = mContext.checkCallingOrSelfPermission(
15108                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15109        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15110        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15111        boolean sendNow = false;
15112        boolean isApp = (className == null);
15113        String componentName = isApp ? packageName : className;
15114        int packageUid = -1;
15115        ArrayList<String> components;
15116
15117        // writer
15118        synchronized (mPackages) {
15119            pkgSetting = mSettings.mPackages.get(packageName);
15120            if (pkgSetting == null) {
15121                if (className == null) {
15122                    throw new IllegalArgumentException(
15123                            "Unknown package: " + packageName);
15124                }
15125                throw new IllegalArgumentException(
15126                        "Unknown component: " + packageName
15127                        + "/" + className);
15128            }
15129            // Allow root and verify that userId is not being specified by a different user
15130            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15131                throw new SecurityException(
15132                        "Permission Denial: attempt to change component state from pid="
15133                        + Binder.getCallingPid()
15134                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15135            }
15136            if (className == null) {
15137                // We're dealing with an application/package level state change
15138                if (pkgSetting.getEnabled(userId) == newState) {
15139                    // Nothing to do
15140                    return;
15141                }
15142                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15143                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15144                    // Don't care about who enables an app.
15145                    callingPackage = null;
15146                }
15147                pkgSetting.setEnabled(newState, userId, callingPackage);
15148                // pkgSetting.pkg.mSetEnabled = newState;
15149            } else {
15150                // We're dealing with a component level state change
15151                // First, verify that this is a valid class name.
15152                PackageParser.Package pkg = pkgSetting.pkg;
15153                if (pkg == null || !pkg.hasComponentClassName(className)) {
15154                    if (pkg != null &&
15155                            pkg.applicationInfo.targetSdkVersion >=
15156                                    Build.VERSION_CODES.JELLY_BEAN) {
15157                        throw new IllegalArgumentException("Component class " + className
15158                                + " does not exist in " + packageName);
15159                    } else {
15160                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15161                                + className + " does not exist in " + packageName);
15162                    }
15163                }
15164                switch (newState) {
15165                case COMPONENT_ENABLED_STATE_ENABLED:
15166                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15167                        return;
15168                    }
15169                    break;
15170                case COMPONENT_ENABLED_STATE_DISABLED:
15171                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15172                        return;
15173                    }
15174                    break;
15175                case COMPONENT_ENABLED_STATE_DEFAULT:
15176                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15177                        return;
15178                    }
15179                    break;
15180                default:
15181                    Slog.e(TAG, "Invalid new component state: " + newState);
15182                    return;
15183                }
15184            }
15185            scheduleWritePackageRestrictionsLocked(userId);
15186            components = mPendingBroadcasts.get(userId, packageName);
15187            final boolean newPackage = components == null;
15188            if (newPackage) {
15189                components = new ArrayList<String>();
15190            }
15191            if (!components.contains(componentName)) {
15192                components.add(componentName);
15193            }
15194            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15195                sendNow = true;
15196                // Purge entry from pending broadcast list if another one exists already
15197                // since we are sending one right away.
15198                mPendingBroadcasts.remove(userId, packageName);
15199            } else {
15200                if (newPackage) {
15201                    mPendingBroadcasts.put(userId, packageName, components);
15202                }
15203                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15204                    // Schedule a message
15205                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15206                }
15207            }
15208        }
15209
15210        long callingId = Binder.clearCallingIdentity();
15211        try {
15212            if (sendNow) {
15213                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15214                sendPackageChangedBroadcast(packageName,
15215                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15216            }
15217        } finally {
15218            Binder.restoreCallingIdentity(callingId);
15219        }
15220    }
15221
15222    private void sendPackageChangedBroadcast(String packageName,
15223            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15224        if (DEBUG_INSTALL)
15225            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15226                    + componentNames);
15227        Bundle extras = new Bundle(4);
15228        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15229        String nameList[] = new String[componentNames.size()];
15230        componentNames.toArray(nameList);
15231        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15232        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15233        extras.putInt(Intent.EXTRA_UID, packageUid);
15234        // If this is not reporting a change of the overall package, then only send it
15235        // to registered receivers.  We don't want to launch a swath of apps for every
15236        // little component state change.
15237        final int flags = !componentNames.contains(packageName)
15238                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15239        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15240                new int[] {UserHandle.getUserId(packageUid)});
15241    }
15242
15243    @Override
15244    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15245        if (!sUserManager.exists(userId)) return;
15246        final int uid = Binder.getCallingUid();
15247        final int permission = mContext.checkCallingOrSelfPermission(
15248                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15249        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15250        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15251        // writer
15252        synchronized (mPackages) {
15253            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15254                    allowedByPermission, uid, userId)) {
15255                scheduleWritePackageRestrictionsLocked(userId);
15256            }
15257        }
15258    }
15259
15260    @Override
15261    public String getInstallerPackageName(String packageName) {
15262        // reader
15263        synchronized (mPackages) {
15264            return mSettings.getInstallerPackageNameLPr(packageName);
15265        }
15266    }
15267
15268    @Override
15269    public int getApplicationEnabledSetting(String packageName, int userId) {
15270        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15271        int uid = Binder.getCallingUid();
15272        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15273        // reader
15274        synchronized (mPackages) {
15275            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15276        }
15277    }
15278
15279    @Override
15280    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15281        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15282        int uid = Binder.getCallingUid();
15283        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15284        // reader
15285        synchronized (mPackages) {
15286            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15287        }
15288    }
15289
15290    @Override
15291    public void enterSafeMode() {
15292        enforceSystemOrRoot("Only the system can request entering safe mode");
15293
15294        if (!mSystemReady) {
15295            mSafeMode = true;
15296        }
15297    }
15298
15299    @Override
15300    public void systemReady() {
15301        mSystemReady = true;
15302
15303        // Read the compatibilty setting when the system is ready.
15304        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15305                mContext.getContentResolver(),
15306                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15307        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15308        if (DEBUG_SETTINGS) {
15309            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15310        }
15311
15312        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15313
15314        synchronized (mPackages) {
15315            // Verify that all of the preferred activity components actually
15316            // exist.  It is possible for applications to be updated and at
15317            // that point remove a previously declared activity component that
15318            // had been set as a preferred activity.  We try to clean this up
15319            // the next time we encounter that preferred activity, but it is
15320            // possible for the user flow to never be able to return to that
15321            // situation so here we do a sanity check to make sure we haven't
15322            // left any junk around.
15323            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15324            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15325                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15326                removed.clear();
15327                for (PreferredActivity pa : pir.filterSet()) {
15328                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15329                        removed.add(pa);
15330                    }
15331                }
15332                if (removed.size() > 0) {
15333                    for (int r=0; r<removed.size(); r++) {
15334                        PreferredActivity pa = removed.get(r);
15335                        Slog.w(TAG, "Removing dangling preferred activity: "
15336                                + pa.mPref.mComponent);
15337                        pir.removeFilter(pa);
15338                    }
15339                    mSettings.writePackageRestrictionsLPr(
15340                            mSettings.mPreferredActivities.keyAt(i));
15341                }
15342            }
15343
15344            for (int userId : UserManagerService.getInstance().getUserIds()) {
15345                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15346                    grantPermissionsUserIds = ArrayUtils.appendInt(
15347                            grantPermissionsUserIds, userId);
15348                }
15349            }
15350        }
15351        sUserManager.systemReady();
15352
15353        // If we upgraded grant all default permissions before kicking off.
15354        for (int userId : grantPermissionsUserIds) {
15355            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15356        }
15357
15358        // Kick off any messages waiting for system ready
15359        if (mPostSystemReadyMessages != null) {
15360            for (Message msg : mPostSystemReadyMessages) {
15361                msg.sendToTarget();
15362            }
15363            mPostSystemReadyMessages = null;
15364        }
15365
15366        // Watch for external volumes that come and go over time
15367        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15368        storage.registerListener(mStorageListener);
15369
15370        mInstallerService.systemReady();
15371        mPackageDexOptimizer.systemReady();
15372
15373        MountServiceInternal mountServiceInternal = LocalServices.getService(
15374                MountServiceInternal.class);
15375        mountServiceInternal.addExternalStoragePolicy(
15376                new MountServiceInternal.ExternalStorageMountPolicy() {
15377            @Override
15378            public int getMountMode(int uid, String packageName) {
15379                if (Process.isIsolated(uid)) {
15380                    return Zygote.MOUNT_EXTERNAL_NONE;
15381                }
15382                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15383                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15384                }
15385                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15386                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15387                }
15388                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15389                    return Zygote.MOUNT_EXTERNAL_READ;
15390                }
15391                return Zygote.MOUNT_EXTERNAL_WRITE;
15392            }
15393
15394            @Override
15395            public boolean hasExternalStorage(int uid, String packageName) {
15396                return true;
15397            }
15398        });
15399    }
15400
15401    @Override
15402    public boolean isSafeMode() {
15403        return mSafeMode;
15404    }
15405
15406    @Override
15407    public boolean hasSystemUidErrors() {
15408        return mHasSystemUidErrors;
15409    }
15410
15411    static String arrayToString(int[] array) {
15412        StringBuffer buf = new StringBuffer(128);
15413        buf.append('[');
15414        if (array != null) {
15415            for (int i=0; i<array.length; i++) {
15416                if (i > 0) buf.append(", ");
15417                buf.append(array[i]);
15418            }
15419        }
15420        buf.append(']');
15421        return buf.toString();
15422    }
15423
15424    static class DumpState {
15425        public static final int DUMP_LIBS = 1 << 0;
15426        public static final int DUMP_FEATURES = 1 << 1;
15427        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15428        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15429        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15430        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15431        public static final int DUMP_PERMISSIONS = 1 << 6;
15432        public static final int DUMP_PACKAGES = 1 << 7;
15433        public static final int DUMP_SHARED_USERS = 1 << 8;
15434        public static final int DUMP_MESSAGES = 1 << 9;
15435        public static final int DUMP_PROVIDERS = 1 << 10;
15436        public static final int DUMP_VERIFIERS = 1 << 11;
15437        public static final int DUMP_PREFERRED = 1 << 12;
15438        public static final int DUMP_PREFERRED_XML = 1 << 13;
15439        public static final int DUMP_KEYSETS = 1 << 14;
15440        public static final int DUMP_VERSION = 1 << 15;
15441        public static final int DUMP_INSTALLS = 1 << 16;
15442        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15443        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15444
15445        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15446
15447        private int mTypes;
15448
15449        private int mOptions;
15450
15451        private boolean mTitlePrinted;
15452
15453        private SharedUserSetting mSharedUser;
15454
15455        public boolean isDumping(int type) {
15456            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15457                return true;
15458            }
15459
15460            return (mTypes & type) != 0;
15461        }
15462
15463        public void setDump(int type) {
15464            mTypes |= type;
15465        }
15466
15467        public boolean isOptionEnabled(int option) {
15468            return (mOptions & option) != 0;
15469        }
15470
15471        public void setOptionEnabled(int option) {
15472            mOptions |= option;
15473        }
15474
15475        public boolean onTitlePrinted() {
15476            final boolean printed = mTitlePrinted;
15477            mTitlePrinted = true;
15478            return printed;
15479        }
15480
15481        public boolean getTitlePrinted() {
15482            return mTitlePrinted;
15483        }
15484
15485        public void setTitlePrinted(boolean enabled) {
15486            mTitlePrinted = enabled;
15487        }
15488
15489        public SharedUserSetting getSharedUser() {
15490            return mSharedUser;
15491        }
15492
15493        public void setSharedUser(SharedUserSetting user) {
15494            mSharedUser = user;
15495        }
15496    }
15497
15498    @Override
15499    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15500            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15501        (new PackageManagerShellCommand(this)).exec(
15502                this, in, out, err, args, resultReceiver);
15503    }
15504
15505    @Override
15506    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15507        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15508                != PackageManager.PERMISSION_GRANTED) {
15509            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15510                    + Binder.getCallingPid()
15511                    + ", uid=" + Binder.getCallingUid()
15512                    + " without permission "
15513                    + android.Manifest.permission.DUMP);
15514            return;
15515        }
15516
15517        DumpState dumpState = new DumpState();
15518        boolean fullPreferred = false;
15519        boolean checkin = false;
15520
15521        String packageName = null;
15522        ArraySet<String> permissionNames = null;
15523
15524        int opti = 0;
15525        while (opti < args.length) {
15526            String opt = args[opti];
15527            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15528                break;
15529            }
15530            opti++;
15531
15532            if ("-a".equals(opt)) {
15533                // Right now we only know how to print all.
15534            } else if ("-h".equals(opt)) {
15535                pw.println("Package manager dump options:");
15536                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15537                pw.println("    --checkin: dump for a checkin");
15538                pw.println("    -f: print details of intent filters");
15539                pw.println("    -h: print this help");
15540                pw.println("  cmd may be one of:");
15541                pw.println("    l[ibraries]: list known shared libraries");
15542                pw.println("    f[eatures]: list device features");
15543                pw.println("    k[eysets]: print known keysets");
15544                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15545                pw.println("    perm[issions]: dump permissions");
15546                pw.println("    permission [name ...]: dump declaration and use of given permission");
15547                pw.println("    pref[erred]: print preferred package settings");
15548                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15549                pw.println("    prov[iders]: dump content providers");
15550                pw.println("    p[ackages]: dump installed packages");
15551                pw.println("    s[hared-users]: dump shared user IDs");
15552                pw.println("    m[essages]: print collected runtime messages");
15553                pw.println("    v[erifiers]: print package verifier info");
15554                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15555                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15556                pw.println("    version: print database version info");
15557                pw.println("    write: write current settings now");
15558                pw.println("    installs: details about install sessions");
15559                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15560                pw.println("    <package.name>: info about given package");
15561                return;
15562            } else if ("--checkin".equals(opt)) {
15563                checkin = true;
15564            } else if ("-f".equals(opt)) {
15565                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15566            } else {
15567                pw.println("Unknown argument: " + opt + "; use -h for help");
15568            }
15569        }
15570
15571        // Is the caller requesting to dump a particular piece of data?
15572        if (opti < args.length) {
15573            String cmd = args[opti];
15574            opti++;
15575            // Is this a package name?
15576            if ("android".equals(cmd) || cmd.contains(".")) {
15577                packageName = cmd;
15578                // When dumping a single package, we always dump all of its
15579                // filter information since the amount of data will be reasonable.
15580                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15581            } else if ("check-permission".equals(cmd)) {
15582                if (opti >= args.length) {
15583                    pw.println("Error: check-permission missing permission argument");
15584                    return;
15585                }
15586                String perm = args[opti];
15587                opti++;
15588                if (opti >= args.length) {
15589                    pw.println("Error: check-permission missing package argument");
15590                    return;
15591                }
15592                String pkg = args[opti];
15593                opti++;
15594                int user = UserHandle.getUserId(Binder.getCallingUid());
15595                if (opti < args.length) {
15596                    try {
15597                        user = Integer.parseInt(args[opti]);
15598                    } catch (NumberFormatException e) {
15599                        pw.println("Error: check-permission user argument is not a number: "
15600                                + args[opti]);
15601                        return;
15602                    }
15603                }
15604                pw.println(checkPermission(perm, pkg, user));
15605                return;
15606            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15607                dumpState.setDump(DumpState.DUMP_LIBS);
15608            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15609                dumpState.setDump(DumpState.DUMP_FEATURES);
15610            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15611                if (opti >= args.length) {
15612                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15613                            | DumpState.DUMP_SERVICE_RESOLVERS
15614                            | DumpState.DUMP_RECEIVER_RESOLVERS
15615                            | DumpState.DUMP_CONTENT_RESOLVERS);
15616                } else {
15617                    while (opti < args.length) {
15618                        String name = args[opti];
15619                        if ("a".equals(name) || "activity".equals(name)) {
15620                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15621                        } else if ("s".equals(name) || "service".equals(name)) {
15622                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15623                        } else if ("r".equals(name) || "receiver".equals(name)) {
15624                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15625                        } else if ("c".equals(name) || "content".equals(name)) {
15626                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15627                        } else {
15628                            pw.println("Error: unknown resolver table type: " + name);
15629                            return;
15630                        }
15631                        opti++;
15632                    }
15633                }
15634            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15635                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15636            } else if ("permission".equals(cmd)) {
15637                if (opti >= args.length) {
15638                    pw.println("Error: permission requires permission name");
15639                    return;
15640                }
15641                permissionNames = new ArraySet<>();
15642                while (opti < args.length) {
15643                    permissionNames.add(args[opti]);
15644                    opti++;
15645                }
15646                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15647                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15648            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15649                dumpState.setDump(DumpState.DUMP_PREFERRED);
15650            } else if ("preferred-xml".equals(cmd)) {
15651                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15652                if (opti < args.length && "--full".equals(args[opti])) {
15653                    fullPreferred = true;
15654                    opti++;
15655                }
15656            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15657                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15658            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15659                dumpState.setDump(DumpState.DUMP_PACKAGES);
15660            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15661                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15662            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15663                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15664            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15665                dumpState.setDump(DumpState.DUMP_MESSAGES);
15666            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15667                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15668            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15669                    || "intent-filter-verifiers".equals(cmd)) {
15670                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15671            } else if ("version".equals(cmd)) {
15672                dumpState.setDump(DumpState.DUMP_VERSION);
15673            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15674                dumpState.setDump(DumpState.DUMP_KEYSETS);
15675            } else if ("installs".equals(cmd)) {
15676                dumpState.setDump(DumpState.DUMP_INSTALLS);
15677            } else if ("write".equals(cmd)) {
15678                synchronized (mPackages) {
15679                    mSettings.writeLPr();
15680                    pw.println("Settings written.");
15681                    return;
15682                }
15683            }
15684        }
15685
15686        if (checkin) {
15687            pw.println("vers,1");
15688        }
15689
15690        // reader
15691        synchronized (mPackages) {
15692            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15693                if (!checkin) {
15694                    if (dumpState.onTitlePrinted())
15695                        pw.println();
15696                    pw.println("Database versions:");
15697                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15698                }
15699            }
15700
15701            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15702                if (!checkin) {
15703                    if (dumpState.onTitlePrinted())
15704                        pw.println();
15705                    pw.println("Verifiers:");
15706                    pw.print("  Required: ");
15707                    pw.print(mRequiredVerifierPackage);
15708                    pw.print(" (uid=");
15709                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15710                    pw.println(")");
15711                } else if (mRequiredVerifierPackage != null) {
15712                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15713                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15714                }
15715            }
15716
15717            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15718                    packageName == null) {
15719                if (mIntentFilterVerifierComponent != null) {
15720                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15721                    if (!checkin) {
15722                        if (dumpState.onTitlePrinted())
15723                            pw.println();
15724                        pw.println("Intent Filter Verifier:");
15725                        pw.print("  Using: ");
15726                        pw.print(verifierPackageName);
15727                        pw.print(" (uid=");
15728                        pw.print(getPackageUid(verifierPackageName, 0));
15729                        pw.println(")");
15730                    } else if (verifierPackageName != null) {
15731                        pw.print("ifv,"); pw.print(verifierPackageName);
15732                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15733                    }
15734                } else {
15735                    pw.println();
15736                    pw.println("No Intent Filter Verifier available!");
15737                }
15738            }
15739
15740            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15741                boolean printedHeader = false;
15742                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15743                while (it.hasNext()) {
15744                    String name = it.next();
15745                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15746                    if (!checkin) {
15747                        if (!printedHeader) {
15748                            if (dumpState.onTitlePrinted())
15749                                pw.println();
15750                            pw.println("Libraries:");
15751                            printedHeader = true;
15752                        }
15753                        pw.print("  ");
15754                    } else {
15755                        pw.print("lib,");
15756                    }
15757                    pw.print(name);
15758                    if (!checkin) {
15759                        pw.print(" -> ");
15760                    }
15761                    if (ent.path != null) {
15762                        if (!checkin) {
15763                            pw.print("(jar) ");
15764                            pw.print(ent.path);
15765                        } else {
15766                            pw.print(",jar,");
15767                            pw.print(ent.path);
15768                        }
15769                    } else {
15770                        if (!checkin) {
15771                            pw.print("(apk) ");
15772                            pw.print(ent.apk);
15773                        } else {
15774                            pw.print(",apk,");
15775                            pw.print(ent.apk);
15776                        }
15777                    }
15778                    pw.println();
15779                }
15780            }
15781
15782            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15783                if (dumpState.onTitlePrinted())
15784                    pw.println();
15785                if (!checkin) {
15786                    pw.println("Features:");
15787                }
15788                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15789                while (it.hasNext()) {
15790                    String name = it.next();
15791                    if (!checkin) {
15792                        pw.print("  ");
15793                    } else {
15794                        pw.print("feat,");
15795                    }
15796                    pw.println(name);
15797                }
15798            }
15799
15800            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15801                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15802                        : "Activity Resolver Table:", "  ", packageName,
15803                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15804                    dumpState.setTitlePrinted(true);
15805                }
15806            }
15807            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15808                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15809                        : "Receiver Resolver Table:", "  ", packageName,
15810                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15811                    dumpState.setTitlePrinted(true);
15812                }
15813            }
15814            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15815                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15816                        : "Service Resolver Table:", "  ", packageName,
15817                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15818                    dumpState.setTitlePrinted(true);
15819                }
15820            }
15821            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15822                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15823                        : "Provider Resolver Table:", "  ", packageName,
15824                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15825                    dumpState.setTitlePrinted(true);
15826                }
15827            }
15828
15829            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15830                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15831                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15832                    int user = mSettings.mPreferredActivities.keyAt(i);
15833                    if (pir.dump(pw,
15834                            dumpState.getTitlePrinted()
15835                                ? "\nPreferred Activities User " + user + ":"
15836                                : "Preferred Activities User " + user + ":", "  ",
15837                            packageName, true, false)) {
15838                        dumpState.setTitlePrinted(true);
15839                    }
15840                }
15841            }
15842
15843            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15844                pw.flush();
15845                FileOutputStream fout = new FileOutputStream(fd);
15846                BufferedOutputStream str = new BufferedOutputStream(fout);
15847                XmlSerializer serializer = new FastXmlSerializer();
15848                try {
15849                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15850                    serializer.startDocument(null, true);
15851                    serializer.setFeature(
15852                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15853                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15854                    serializer.endDocument();
15855                    serializer.flush();
15856                } catch (IllegalArgumentException e) {
15857                    pw.println("Failed writing: " + e);
15858                } catch (IllegalStateException e) {
15859                    pw.println("Failed writing: " + e);
15860                } catch (IOException e) {
15861                    pw.println("Failed writing: " + e);
15862                }
15863            }
15864
15865            if (!checkin
15866                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15867                    && packageName == null) {
15868                pw.println();
15869                int count = mSettings.mPackages.size();
15870                if (count == 0) {
15871                    pw.println("No applications!");
15872                    pw.println();
15873                } else {
15874                    final String prefix = "  ";
15875                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15876                    if (allPackageSettings.size() == 0) {
15877                        pw.println("No domain preferred apps!");
15878                        pw.println();
15879                    } else {
15880                        pw.println("App verification status:");
15881                        pw.println();
15882                        count = 0;
15883                        for (PackageSetting ps : allPackageSettings) {
15884                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15885                            if (ivi == null || ivi.getPackageName() == null) continue;
15886                            pw.println(prefix + "Package: " + ivi.getPackageName());
15887                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15888                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15889                            pw.println();
15890                            count++;
15891                        }
15892                        if (count == 0) {
15893                            pw.println(prefix + "No app verification established.");
15894                            pw.println();
15895                        }
15896                        for (int userId : sUserManager.getUserIds()) {
15897                            pw.println("App linkages for user " + userId + ":");
15898                            pw.println();
15899                            count = 0;
15900                            for (PackageSetting ps : allPackageSettings) {
15901                                final long status = ps.getDomainVerificationStatusForUser(userId);
15902                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15903                                    continue;
15904                                }
15905                                pw.println(prefix + "Package: " + ps.name);
15906                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15907                                String statusStr = IntentFilterVerificationInfo.
15908                                        getStatusStringFromValue(status);
15909                                pw.println(prefix + "Status:  " + statusStr);
15910                                pw.println();
15911                                count++;
15912                            }
15913                            if (count == 0) {
15914                                pw.println(prefix + "No configured app linkages.");
15915                                pw.println();
15916                            }
15917                        }
15918                    }
15919                }
15920            }
15921
15922            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15923                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15924                if (packageName == null && permissionNames == null) {
15925                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15926                        if (iperm == 0) {
15927                            if (dumpState.onTitlePrinted())
15928                                pw.println();
15929                            pw.println("AppOp Permissions:");
15930                        }
15931                        pw.print("  AppOp Permission ");
15932                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15933                        pw.println(":");
15934                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15935                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15936                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15937                        }
15938                    }
15939                }
15940            }
15941
15942            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15943                boolean printedSomething = false;
15944                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15945                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15946                        continue;
15947                    }
15948                    if (!printedSomething) {
15949                        if (dumpState.onTitlePrinted())
15950                            pw.println();
15951                        pw.println("Registered ContentProviders:");
15952                        printedSomething = true;
15953                    }
15954                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15955                    pw.print("    "); pw.println(p.toString());
15956                }
15957                printedSomething = false;
15958                for (Map.Entry<String, PackageParser.Provider> entry :
15959                        mProvidersByAuthority.entrySet()) {
15960                    PackageParser.Provider p = entry.getValue();
15961                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15962                        continue;
15963                    }
15964                    if (!printedSomething) {
15965                        if (dumpState.onTitlePrinted())
15966                            pw.println();
15967                        pw.println("ContentProvider Authorities:");
15968                        printedSomething = true;
15969                    }
15970                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15971                    pw.print("    "); pw.println(p.toString());
15972                    if (p.info != null && p.info.applicationInfo != null) {
15973                        final String appInfo = p.info.applicationInfo.toString();
15974                        pw.print("      applicationInfo="); pw.println(appInfo);
15975                    }
15976                }
15977            }
15978
15979            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15980                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15981            }
15982
15983            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15984                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15985            }
15986
15987            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15988                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15989            }
15990
15991            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15992                // XXX should handle packageName != null by dumping only install data that
15993                // the given package is involved with.
15994                if (dumpState.onTitlePrinted()) pw.println();
15995                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15996            }
15997
15998            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15999                if (dumpState.onTitlePrinted()) pw.println();
16000                mSettings.dumpReadMessagesLPr(pw, dumpState);
16001
16002                pw.println();
16003                pw.println("Package warning messages:");
16004                BufferedReader in = null;
16005                String line = null;
16006                try {
16007                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16008                    while ((line = in.readLine()) != null) {
16009                        if (line.contains("ignored: updated version")) continue;
16010                        pw.println(line);
16011                    }
16012                } catch (IOException ignored) {
16013                } finally {
16014                    IoUtils.closeQuietly(in);
16015                }
16016            }
16017
16018            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16019                BufferedReader in = null;
16020                String line = null;
16021                try {
16022                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16023                    while ((line = in.readLine()) != null) {
16024                        if (line.contains("ignored: updated version")) continue;
16025                        pw.print("msg,");
16026                        pw.println(line);
16027                    }
16028                } catch (IOException ignored) {
16029                } finally {
16030                    IoUtils.closeQuietly(in);
16031                }
16032            }
16033        }
16034    }
16035
16036    private String dumpDomainString(String packageName) {
16037        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16038        List<IntentFilter> filters = getAllIntentFilters(packageName);
16039
16040        ArraySet<String> result = new ArraySet<>();
16041        if (iviList.size() > 0) {
16042            for (IntentFilterVerificationInfo ivi : iviList) {
16043                for (String host : ivi.getDomains()) {
16044                    result.add(host);
16045                }
16046            }
16047        }
16048        if (filters != null && filters.size() > 0) {
16049            for (IntentFilter filter : filters) {
16050                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16051                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16052                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16053                    result.addAll(filter.getHostsList());
16054                }
16055            }
16056        }
16057
16058        StringBuilder sb = new StringBuilder(result.size() * 16);
16059        for (String domain : result) {
16060            if (sb.length() > 0) sb.append(" ");
16061            sb.append(domain);
16062        }
16063        return sb.toString();
16064    }
16065
16066    // ------- apps on sdcard specific code -------
16067    static final boolean DEBUG_SD_INSTALL = false;
16068
16069    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16070
16071    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16072
16073    private boolean mMediaMounted = false;
16074
16075    static String getEncryptKey() {
16076        try {
16077            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16078                    SD_ENCRYPTION_KEYSTORE_NAME);
16079            if (sdEncKey == null) {
16080                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16081                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16082                if (sdEncKey == null) {
16083                    Slog.e(TAG, "Failed to create encryption keys");
16084                    return null;
16085                }
16086            }
16087            return sdEncKey;
16088        } catch (NoSuchAlgorithmException nsae) {
16089            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16090            return null;
16091        } catch (IOException ioe) {
16092            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16093            return null;
16094        }
16095    }
16096
16097    /*
16098     * Update media status on PackageManager.
16099     */
16100    @Override
16101    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16102        int callingUid = Binder.getCallingUid();
16103        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16104            throw new SecurityException("Media status can only be updated by the system");
16105        }
16106        // reader; this apparently protects mMediaMounted, but should probably
16107        // be a different lock in that case.
16108        synchronized (mPackages) {
16109            Log.i(TAG, "Updating external media status from "
16110                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16111                    + (mediaStatus ? "mounted" : "unmounted"));
16112            if (DEBUG_SD_INSTALL)
16113                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16114                        + ", mMediaMounted=" + mMediaMounted);
16115            if (mediaStatus == mMediaMounted) {
16116                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16117                        : 0, -1);
16118                mHandler.sendMessage(msg);
16119                return;
16120            }
16121            mMediaMounted = mediaStatus;
16122        }
16123        // Queue up an async operation since the package installation may take a
16124        // little while.
16125        mHandler.post(new Runnable() {
16126            public void run() {
16127                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16128            }
16129        });
16130    }
16131
16132    /**
16133     * Called by MountService when the initial ASECs to scan are available.
16134     * Should block until all the ASEC containers are finished being scanned.
16135     */
16136    public void scanAvailableAsecs() {
16137        updateExternalMediaStatusInner(true, false, false);
16138        if (mShouldRestoreconData) {
16139            SELinuxMMAC.setRestoreconDone();
16140            mShouldRestoreconData = false;
16141        }
16142    }
16143
16144    /*
16145     * Collect information of applications on external media, map them against
16146     * existing containers and update information based on current mount status.
16147     * Please note that we always have to report status if reportStatus has been
16148     * set to true especially when unloading packages.
16149     */
16150    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16151            boolean externalStorage) {
16152        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16153        int[] uidArr = EmptyArray.INT;
16154
16155        final String[] list = PackageHelper.getSecureContainerList();
16156        if (ArrayUtils.isEmpty(list)) {
16157            Log.i(TAG, "No secure containers found");
16158        } else {
16159            // Process list of secure containers and categorize them
16160            // as active or stale based on their package internal state.
16161
16162            // reader
16163            synchronized (mPackages) {
16164                for (String cid : list) {
16165                    // Leave stages untouched for now; installer service owns them
16166                    if (PackageInstallerService.isStageName(cid)) continue;
16167
16168                    if (DEBUG_SD_INSTALL)
16169                        Log.i(TAG, "Processing container " + cid);
16170                    String pkgName = getAsecPackageName(cid);
16171                    if (pkgName == null) {
16172                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16173                        continue;
16174                    }
16175                    if (DEBUG_SD_INSTALL)
16176                        Log.i(TAG, "Looking for pkg : " + pkgName);
16177
16178                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16179                    if (ps == null) {
16180                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16181                        continue;
16182                    }
16183
16184                    /*
16185                     * Skip packages that are not external if we're unmounting
16186                     * external storage.
16187                     */
16188                    if (externalStorage && !isMounted && !isExternal(ps)) {
16189                        continue;
16190                    }
16191
16192                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16193                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16194                    // The package status is changed only if the code path
16195                    // matches between settings and the container id.
16196                    if (ps.codePathString != null
16197                            && ps.codePathString.startsWith(args.getCodePath())) {
16198                        if (DEBUG_SD_INSTALL) {
16199                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16200                                    + " at code path: " + ps.codePathString);
16201                        }
16202
16203                        // We do have a valid package installed on sdcard
16204                        processCids.put(args, ps.codePathString);
16205                        final int uid = ps.appId;
16206                        if (uid != -1) {
16207                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16208                        }
16209                    } else {
16210                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16211                                + ps.codePathString);
16212                    }
16213                }
16214            }
16215
16216            Arrays.sort(uidArr);
16217        }
16218
16219        // Process packages with valid entries.
16220        if (isMounted) {
16221            if (DEBUG_SD_INSTALL)
16222                Log.i(TAG, "Loading packages");
16223            loadMediaPackages(processCids, uidArr, externalStorage);
16224            startCleaningPackages();
16225            mInstallerService.onSecureContainersAvailable();
16226        } else {
16227            if (DEBUG_SD_INSTALL)
16228                Log.i(TAG, "Unloading packages");
16229            unloadMediaPackages(processCids, uidArr, reportStatus);
16230        }
16231    }
16232
16233    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16234            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16235        final int size = infos.size();
16236        final String[] packageNames = new String[size];
16237        final int[] packageUids = new int[size];
16238        for (int i = 0; i < size; i++) {
16239            final ApplicationInfo info = infos.get(i);
16240            packageNames[i] = info.packageName;
16241            packageUids[i] = info.uid;
16242        }
16243        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16244                finishedReceiver);
16245    }
16246
16247    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16248            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16249        sendResourcesChangedBroadcast(mediaStatus, replacing,
16250                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16251    }
16252
16253    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16254            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16255        int size = pkgList.length;
16256        if (size > 0) {
16257            // Send broadcasts here
16258            Bundle extras = new Bundle();
16259            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16260            if (uidArr != null) {
16261                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16262            }
16263            if (replacing) {
16264                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16265            }
16266            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16267                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16268            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16269        }
16270    }
16271
16272   /*
16273     * Look at potentially valid container ids from processCids If package
16274     * information doesn't match the one on record or package scanning fails,
16275     * the cid is added to list of removeCids. We currently don't delete stale
16276     * containers.
16277     */
16278    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16279            boolean externalStorage) {
16280        ArrayList<String> pkgList = new ArrayList<String>();
16281        Set<AsecInstallArgs> keys = processCids.keySet();
16282
16283        for (AsecInstallArgs args : keys) {
16284            String codePath = processCids.get(args);
16285            if (DEBUG_SD_INSTALL)
16286                Log.i(TAG, "Loading container : " + args.cid);
16287            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16288            try {
16289                // Make sure there are no container errors first.
16290                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16291                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16292                            + " when installing from sdcard");
16293                    continue;
16294                }
16295                // Check code path here.
16296                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16297                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16298                            + " does not match one in settings " + codePath);
16299                    continue;
16300                }
16301                // Parse package
16302                int parseFlags = mDefParseFlags;
16303                if (args.isExternalAsec()) {
16304                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16305                }
16306                if (args.isFwdLocked()) {
16307                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16308                }
16309
16310                synchronized (mInstallLock) {
16311                    PackageParser.Package pkg = null;
16312                    try {
16313                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16314                    } catch (PackageManagerException e) {
16315                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16316                    }
16317                    // Scan the package
16318                    if (pkg != null) {
16319                        /*
16320                         * TODO why is the lock being held? doPostInstall is
16321                         * called in other places without the lock. This needs
16322                         * to be straightened out.
16323                         */
16324                        // writer
16325                        synchronized (mPackages) {
16326                            retCode = PackageManager.INSTALL_SUCCEEDED;
16327                            pkgList.add(pkg.packageName);
16328                            // Post process args
16329                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16330                                    pkg.applicationInfo.uid);
16331                        }
16332                    } else {
16333                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16334                    }
16335                }
16336
16337            } finally {
16338                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16339                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16340                }
16341            }
16342        }
16343        // writer
16344        synchronized (mPackages) {
16345            // If the platform SDK has changed since the last time we booted,
16346            // we need to re-grant app permission to catch any new ones that
16347            // appear. This is really a hack, and means that apps can in some
16348            // cases get permissions that the user didn't initially explicitly
16349            // allow... it would be nice to have some better way to handle
16350            // this situation.
16351            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16352                    : mSettings.getInternalVersion();
16353            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16354                    : StorageManager.UUID_PRIVATE_INTERNAL;
16355
16356            int updateFlags = UPDATE_PERMISSIONS_ALL;
16357            if (ver.sdkVersion != mSdkVersion) {
16358                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16359                        + mSdkVersion + "; regranting permissions for external");
16360                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16361            }
16362            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16363
16364            // Yay, everything is now upgraded
16365            ver.forceCurrent();
16366
16367            // can downgrade to reader
16368            // Persist settings
16369            mSettings.writeLPr();
16370        }
16371        // Send a broadcast to let everyone know we are done processing
16372        if (pkgList.size() > 0) {
16373            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16374        }
16375    }
16376
16377   /*
16378     * Utility method to unload a list of specified containers
16379     */
16380    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16381        // Just unmount all valid containers.
16382        for (AsecInstallArgs arg : cidArgs) {
16383            synchronized (mInstallLock) {
16384                arg.doPostDeleteLI(false);
16385           }
16386       }
16387   }
16388
16389    /*
16390     * Unload packages mounted on external media. This involves deleting package
16391     * data from internal structures, sending broadcasts about diabled packages,
16392     * gc'ing to free up references, unmounting all secure containers
16393     * corresponding to packages on external media, and posting a
16394     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16395     * that we always have to post this message if status has been requested no
16396     * matter what.
16397     */
16398    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16399            final boolean reportStatus) {
16400        if (DEBUG_SD_INSTALL)
16401            Log.i(TAG, "unloading media packages");
16402        ArrayList<String> pkgList = new ArrayList<String>();
16403        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16404        final Set<AsecInstallArgs> keys = processCids.keySet();
16405        for (AsecInstallArgs args : keys) {
16406            String pkgName = args.getPackageName();
16407            if (DEBUG_SD_INSTALL)
16408                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16409            // Delete package internally
16410            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16411            synchronized (mInstallLock) {
16412                boolean res = deletePackageLI(pkgName, null, false, null, null,
16413                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16414                if (res) {
16415                    pkgList.add(pkgName);
16416                } else {
16417                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16418                    failedList.add(args);
16419                }
16420            }
16421        }
16422
16423        // reader
16424        synchronized (mPackages) {
16425            // We didn't update the settings after removing each package;
16426            // write them now for all packages.
16427            mSettings.writeLPr();
16428        }
16429
16430        // We have to absolutely send UPDATED_MEDIA_STATUS only
16431        // after confirming that all the receivers processed the ordered
16432        // broadcast when packages get disabled, force a gc to clean things up.
16433        // and unload all the containers.
16434        if (pkgList.size() > 0) {
16435            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16436                    new IIntentReceiver.Stub() {
16437                public void performReceive(Intent intent, int resultCode, String data,
16438                        Bundle extras, boolean ordered, boolean sticky,
16439                        int sendingUser) throws RemoteException {
16440                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16441                            reportStatus ? 1 : 0, 1, keys);
16442                    mHandler.sendMessage(msg);
16443                }
16444            });
16445        } else {
16446            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16447                    keys);
16448            mHandler.sendMessage(msg);
16449        }
16450    }
16451
16452    private void loadPrivatePackages(final VolumeInfo vol) {
16453        mHandler.post(new Runnable() {
16454            @Override
16455            public void run() {
16456                loadPrivatePackagesInner(vol);
16457            }
16458        });
16459    }
16460
16461    private void loadPrivatePackagesInner(VolumeInfo vol) {
16462        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16463        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16464
16465        final VersionInfo ver;
16466        final List<PackageSetting> packages;
16467        synchronized (mPackages) {
16468            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16469            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16470        }
16471
16472        for (PackageSetting ps : packages) {
16473            synchronized (mInstallLock) {
16474                final PackageParser.Package pkg;
16475                try {
16476                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16477                    loaded.add(pkg.applicationInfo);
16478                } catch (PackageManagerException e) {
16479                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16480                }
16481
16482                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16483                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16484                }
16485            }
16486        }
16487
16488        synchronized (mPackages) {
16489            int updateFlags = UPDATE_PERMISSIONS_ALL;
16490            if (ver.sdkVersion != mSdkVersion) {
16491                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16492                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16493                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16494            }
16495            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16496
16497            // Yay, everything is now upgraded
16498            ver.forceCurrent();
16499
16500            mSettings.writeLPr();
16501        }
16502
16503        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16504        sendResourcesChangedBroadcast(true, false, loaded, null);
16505    }
16506
16507    private void unloadPrivatePackages(final VolumeInfo vol) {
16508        mHandler.post(new Runnable() {
16509            @Override
16510            public void run() {
16511                unloadPrivatePackagesInner(vol);
16512            }
16513        });
16514    }
16515
16516    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16517        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16518        synchronized (mInstallLock) {
16519        synchronized (mPackages) {
16520            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16521            for (PackageSetting ps : packages) {
16522                if (ps.pkg == null) continue;
16523
16524                final ApplicationInfo info = ps.pkg.applicationInfo;
16525                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16526                if (deletePackageLI(ps.name, null, false, null, null,
16527                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16528                    unloaded.add(info);
16529                } else {
16530                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16531                }
16532            }
16533
16534            mSettings.writeLPr();
16535        }
16536        }
16537
16538        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16539        sendResourcesChangedBroadcast(false, false, unloaded, null);
16540    }
16541
16542    /**
16543     * Examine all users present on given mounted volume, and destroy data
16544     * belonging to users that are no longer valid, or whose user ID has been
16545     * recycled.
16546     */
16547    private void reconcileUsers(String volumeUuid) {
16548        final File[] files = FileUtils
16549                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16550        for (File file : files) {
16551            if (!file.isDirectory()) continue;
16552
16553            final int userId;
16554            final UserInfo info;
16555            try {
16556                userId = Integer.parseInt(file.getName());
16557                info = sUserManager.getUserInfo(userId);
16558            } catch (NumberFormatException e) {
16559                Slog.w(TAG, "Invalid user directory " + file);
16560                continue;
16561            }
16562
16563            boolean destroyUser = false;
16564            if (info == null) {
16565                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16566                        + " because no matching user was found");
16567                destroyUser = true;
16568            } else {
16569                try {
16570                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16571                } catch (IOException e) {
16572                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16573                            + " because we failed to enforce serial number: " + e);
16574                    destroyUser = true;
16575                }
16576            }
16577
16578            if (destroyUser) {
16579                synchronized (mInstallLock) {
16580                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16581                }
16582            }
16583        }
16584
16585        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16586        final UserManager um = mContext.getSystemService(UserManager.class);
16587        for (UserInfo user : um.getUsers()) {
16588            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16589            if (userDir.exists()) continue;
16590
16591            try {
16592                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16593                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16594            } catch (IOException e) {
16595                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16596            }
16597        }
16598    }
16599
16600    /**
16601     * Examine all apps present on given mounted volume, and destroy apps that
16602     * aren't expected, either due to uninstallation or reinstallation on
16603     * another volume.
16604     */
16605    private void reconcileApps(String volumeUuid) {
16606        final File[] files = FileUtils
16607                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16608        for (File file : files) {
16609            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16610                    && !PackageInstallerService.isStageName(file.getName());
16611            if (!isPackage) {
16612                // Ignore entries which are not packages
16613                continue;
16614            }
16615
16616            boolean destroyApp = false;
16617            String packageName = null;
16618            try {
16619                final PackageLite pkg = PackageParser.parsePackageLite(file,
16620                        PackageParser.PARSE_MUST_BE_APK);
16621                packageName = pkg.packageName;
16622
16623                synchronized (mPackages) {
16624                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16625                    if (ps == null) {
16626                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16627                                + volumeUuid + " because we found no install record");
16628                        destroyApp = true;
16629                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16630                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16631                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16632                        destroyApp = true;
16633                    }
16634                }
16635
16636            } catch (PackageParserException e) {
16637                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16638                destroyApp = true;
16639            }
16640
16641            if (destroyApp) {
16642                synchronized (mInstallLock) {
16643                    if (packageName != null) {
16644                        removeDataDirsLI(volumeUuid, packageName);
16645                    }
16646                    if (file.isDirectory()) {
16647                        mInstaller.rmPackageDir(file.getAbsolutePath());
16648                    } else {
16649                        file.delete();
16650                    }
16651                }
16652            }
16653        }
16654    }
16655
16656    private void unfreezePackage(String packageName) {
16657        synchronized (mPackages) {
16658            final PackageSetting ps = mSettings.mPackages.get(packageName);
16659            if (ps != null) {
16660                ps.frozen = false;
16661            }
16662        }
16663    }
16664
16665    @Override
16666    public int movePackage(final String packageName, final String volumeUuid) {
16667        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16668
16669        final int moveId = mNextMoveId.getAndIncrement();
16670        mHandler.post(new Runnable() {
16671            @Override
16672            public void run() {
16673                try {
16674                    movePackageInternal(packageName, volumeUuid, moveId);
16675                } catch (PackageManagerException e) {
16676                    Slog.w(TAG, "Failed to move " + packageName, e);
16677                    mMoveCallbacks.notifyStatusChanged(moveId,
16678                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16679                }
16680            }
16681        });
16682        return moveId;
16683    }
16684
16685    private void movePackageInternal(final String packageName, final String volumeUuid,
16686            final int moveId) throws PackageManagerException {
16687        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16688        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16689        final PackageManager pm = mContext.getPackageManager();
16690
16691        final boolean currentAsec;
16692        final String currentVolumeUuid;
16693        final File codeFile;
16694        final String installerPackageName;
16695        final String packageAbiOverride;
16696        final int appId;
16697        final String seinfo;
16698        final String label;
16699
16700        // reader
16701        synchronized (mPackages) {
16702            final PackageParser.Package pkg = mPackages.get(packageName);
16703            final PackageSetting ps = mSettings.mPackages.get(packageName);
16704            if (pkg == null || ps == null) {
16705                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16706            }
16707
16708            if (pkg.applicationInfo.isSystemApp()) {
16709                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16710                        "Cannot move system application");
16711            }
16712
16713            if (pkg.applicationInfo.isExternalAsec()) {
16714                currentAsec = true;
16715                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16716            } else if (pkg.applicationInfo.isForwardLocked()) {
16717                currentAsec = true;
16718                currentVolumeUuid = "forward_locked";
16719            } else {
16720                currentAsec = false;
16721                currentVolumeUuid = ps.volumeUuid;
16722
16723                final File probe = new File(pkg.codePath);
16724                final File probeOat = new File(probe, "oat");
16725                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16726                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16727                            "Move only supported for modern cluster style installs");
16728                }
16729            }
16730
16731            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16732                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16733                        "Package already moved to " + volumeUuid);
16734            }
16735
16736            if (ps.frozen) {
16737                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16738                        "Failed to move already frozen package");
16739            }
16740            ps.frozen = true;
16741
16742            codeFile = new File(pkg.codePath);
16743            installerPackageName = ps.installerPackageName;
16744            packageAbiOverride = ps.cpuAbiOverrideString;
16745            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16746            seinfo = pkg.applicationInfo.seinfo;
16747            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16748        }
16749
16750        // Now that we're guarded by frozen state, kill app during move
16751        final long token = Binder.clearCallingIdentity();
16752        try {
16753            killApplication(packageName, appId, "move pkg");
16754        } finally {
16755            Binder.restoreCallingIdentity(token);
16756        }
16757
16758        final Bundle extras = new Bundle();
16759        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16760        extras.putString(Intent.EXTRA_TITLE, label);
16761        mMoveCallbacks.notifyCreated(moveId, extras);
16762
16763        int installFlags;
16764        final boolean moveCompleteApp;
16765        final File measurePath;
16766
16767        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16768            installFlags = INSTALL_INTERNAL;
16769            moveCompleteApp = !currentAsec;
16770            measurePath = Environment.getDataAppDirectory(volumeUuid);
16771        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16772            installFlags = INSTALL_EXTERNAL;
16773            moveCompleteApp = false;
16774            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16775        } else {
16776            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16777            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16778                    || !volume.isMountedWritable()) {
16779                unfreezePackage(packageName);
16780                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16781                        "Move location not mounted private volume");
16782            }
16783
16784            Preconditions.checkState(!currentAsec);
16785
16786            installFlags = INSTALL_INTERNAL;
16787            moveCompleteApp = true;
16788            measurePath = Environment.getDataAppDirectory(volumeUuid);
16789        }
16790
16791        final PackageStats stats = new PackageStats(null, -1);
16792        synchronized (mInstaller) {
16793            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16794                unfreezePackage(packageName);
16795                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16796                        "Failed to measure package size");
16797            }
16798        }
16799
16800        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16801                + stats.dataSize);
16802
16803        final long startFreeBytes = measurePath.getFreeSpace();
16804        final long sizeBytes;
16805        if (moveCompleteApp) {
16806            sizeBytes = stats.codeSize + stats.dataSize;
16807        } else {
16808            sizeBytes = stats.codeSize;
16809        }
16810
16811        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16812            unfreezePackage(packageName);
16813            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16814                    "Not enough free space to move");
16815        }
16816
16817        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16818
16819        final CountDownLatch installedLatch = new CountDownLatch(1);
16820        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16821            @Override
16822            public void onUserActionRequired(Intent intent) throws RemoteException {
16823                throw new IllegalStateException();
16824            }
16825
16826            @Override
16827            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16828                    Bundle extras) throws RemoteException {
16829                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16830                        + PackageManager.installStatusToString(returnCode, msg));
16831
16832                installedLatch.countDown();
16833
16834                // Regardless of success or failure of the move operation,
16835                // always unfreeze the package
16836                unfreezePackage(packageName);
16837
16838                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16839                switch (status) {
16840                    case PackageInstaller.STATUS_SUCCESS:
16841                        mMoveCallbacks.notifyStatusChanged(moveId,
16842                                PackageManager.MOVE_SUCCEEDED);
16843                        break;
16844                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16845                        mMoveCallbacks.notifyStatusChanged(moveId,
16846                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16847                        break;
16848                    default:
16849                        mMoveCallbacks.notifyStatusChanged(moveId,
16850                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16851                        break;
16852                }
16853            }
16854        };
16855
16856        final MoveInfo move;
16857        if (moveCompleteApp) {
16858            // Kick off a thread to report progress estimates
16859            new Thread() {
16860                @Override
16861                public void run() {
16862                    while (true) {
16863                        try {
16864                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16865                                break;
16866                            }
16867                        } catch (InterruptedException ignored) {
16868                        }
16869
16870                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16871                        final int progress = 10 + (int) MathUtils.constrain(
16872                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16873                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16874                    }
16875                }
16876            }.start();
16877
16878            final String dataAppName = codeFile.getName();
16879            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16880                    dataAppName, appId, seinfo);
16881        } else {
16882            move = null;
16883        }
16884
16885        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16886
16887        final Message msg = mHandler.obtainMessage(INIT_COPY);
16888        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16889        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16890                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16891        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16892        msg.obj = params;
16893
16894        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16895                System.identityHashCode(msg.obj));
16896        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16897                System.identityHashCode(msg.obj));
16898
16899        mHandler.sendMessage(msg);
16900    }
16901
16902    @Override
16903    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16904        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16905
16906        final int realMoveId = mNextMoveId.getAndIncrement();
16907        final Bundle extras = new Bundle();
16908        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16909        mMoveCallbacks.notifyCreated(realMoveId, extras);
16910
16911        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16912            @Override
16913            public void onCreated(int moveId, Bundle extras) {
16914                // Ignored
16915            }
16916
16917            @Override
16918            public void onStatusChanged(int moveId, int status, long estMillis) {
16919                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16920            }
16921        };
16922
16923        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16924        storage.setPrimaryStorageUuid(volumeUuid, callback);
16925        return realMoveId;
16926    }
16927
16928    @Override
16929    public int getMoveStatus(int moveId) {
16930        mContext.enforceCallingOrSelfPermission(
16931                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16932        return mMoveCallbacks.mLastStatus.get(moveId);
16933    }
16934
16935    @Override
16936    public void registerMoveCallback(IPackageMoveObserver callback) {
16937        mContext.enforceCallingOrSelfPermission(
16938                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16939        mMoveCallbacks.register(callback);
16940    }
16941
16942    @Override
16943    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16944        mContext.enforceCallingOrSelfPermission(
16945                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16946        mMoveCallbacks.unregister(callback);
16947    }
16948
16949    @Override
16950    public boolean setInstallLocation(int loc) {
16951        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16952                null);
16953        if (getInstallLocation() == loc) {
16954            return true;
16955        }
16956        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16957                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16958            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16959                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16960            return true;
16961        }
16962        return false;
16963   }
16964
16965    @Override
16966    public int getInstallLocation() {
16967        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16968                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16969                PackageHelper.APP_INSTALL_AUTO);
16970    }
16971
16972    /** Called by UserManagerService */
16973    void cleanUpUser(UserManagerService userManager, int userHandle) {
16974        synchronized (mPackages) {
16975            mDirtyUsers.remove(userHandle);
16976            mUserNeedsBadging.delete(userHandle);
16977            mSettings.removeUserLPw(userHandle);
16978            mPendingBroadcasts.remove(userHandle);
16979            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16980        }
16981        synchronized (mInstallLock) {
16982            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16983            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16984                final String volumeUuid = vol.getFsUuid();
16985                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16986                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16987            }
16988            synchronized (mPackages) {
16989                removeUnusedPackagesLILPw(userManager, userHandle);
16990            }
16991        }
16992    }
16993
16994    /**
16995     * We're removing userHandle and would like to remove any downloaded packages
16996     * that are no longer in use by any other user.
16997     * @param userHandle the user being removed
16998     */
16999    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17000        final boolean DEBUG_CLEAN_APKS = false;
17001        int [] users = userManager.getUserIds();
17002        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17003        while (psit.hasNext()) {
17004            PackageSetting ps = psit.next();
17005            if (ps.pkg == null) {
17006                continue;
17007            }
17008            final String packageName = ps.pkg.packageName;
17009            // Skip over if system app
17010            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17011                continue;
17012            }
17013            if (DEBUG_CLEAN_APKS) {
17014                Slog.i(TAG, "Checking package " + packageName);
17015            }
17016            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17017            if (keep) {
17018                if (DEBUG_CLEAN_APKS) {
17019                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17020                }
17021            } else {
17022                for (int i = 0; i < users.length; i++) {
17023                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17024                        keep = true;
17025                        if (DEBUG_CLEAN_APKS) {
17026                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17027                                    + users[i]);
17028                        }
17029                        break;
17030                    }
17031                }
17032            }
17033            if (!keep) {
17034                if (DEBUG_CLEAN_APKS) {
17035                    Slog.i(TAG, "  Removing package " + packageName);
17036                }
17037                mHandler.post(new Runnable() {
17038                    public void run() {
17039                        deletePackageX(packageName, userHandle, 0);
17040                    } //end run
17041                });
17042            }
17043        }
17044    }
17045
17046    /** Called by UserManagerService */
17047    void createNewUser(int userHandle) {
17048        synchronized (mInstallLock) {
17049            mInstaller.createUserConfig(userHandle);
17050            mSettings.createNewUserLI(this, mInstaller, userHandle);
17051        }
17052        synchronized (mPackages) {
17053            applyFactoryDefaultBrowserLPw(userHandle);
17054            primeDomainVerificationsLPw(userHandle);
17055        }
17056    }
17057
17058    void newUserCreated(final int userHandle) {
17059        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17060        // If permission review for legacy apps is required, we represent
17061        // dagerous permissions for such apps as always granted runtime
17062        // permissions to keep per user flag state whether review is needed.
17063        // Hence, if a new user is added we have to propagate dangerous
17064        // permission grants for these legacy apps.
17065        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17066            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17067                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17068        }
17069    }
17070
17071    @Override
17072    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17073        mContext.enforceCallingOrSelfPermission(
17074                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17075                "Only package verification agents can read the verifier device identity");
17076
17077        synchronized (mPackages) {
17078            return mSettings.getVerifierDeviceIdentityLPw();
17079        }
17080    }
17081
17082    @Override
17083    public void setPermissionEnforced(String permission, boolean enforced) {
17084        // TODO: Now that we no longer change GID for storage, this should to away.
17085        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17086                "setPermissionEnforced");
17087        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17088            synchronized (mPackages) {
17089                if (mSettings.mReadExternalStorageEnforced == null
17090                        || mSettings.mReadExternalStorageEnforced != enforced) {
17091                    mSettings.mReadExternalStorageEnforced = enforced;
17092                    mSettings.writeLPr();
17093                }
17094            }
17095            // kill any non-foreground processes so we restart them and
17096            // grant/revoke the GID.
17097            final IActivityManager am = ActivityManagerNative.getDefault();
17098            if (am != null) {
17099                final long token = Binder.clearCallingIdentity();
17100                try {
17101                    am.killProcessesBelowForeground("setPermissionEnforcement");
17102                } catch (RemoteException e) {
17103                } finally {
17104                    Binder.restoreCallingIdentity(token);
17105                }
17106            }
17107        } else {
17108            throw new IllegalArgumentException("No selective enforcement for " + permission);
17109        }
17110    }
17111
17112    @Override
17113    @Deprecated
17114    public boolean isPermissionEnforced(String permission) {
17115        return true;
17116    }
17117
17118    @Override
17119    public boolean isStorageLow() {
17120        final long token = Binder.clearCallingIdentity();
17121        try {
17122            final DeviceStorageMonitorInternal
17123                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17124            if (dsm != null) {
17125                return dsm.isMemoryLow();
17126            } else {
17127                return false;
17128            }
17129        } finally {
17130            Binder.restoreCallingIdentity(token);
17131        }
17132    }
17133
17134    @Override
17135    public IPackageInstaller getPackageInstaller() {
17136        return mInstallerService;
17137    }
17138
17139    private boolean userNeedsBadging(int userId) {
17140        int index = mUserNeedsBadging.indexOfKey(userId);
17141        if (index < 0) {
17142            final UserInfo userInfo;
17143            final long token = Binder.clearCallingIdentity();
17144            try {
17145                userInfo = sUserManager.getUserInfo(userId);
17146            } finally {
17147                Binder.restoreCallingIdentity(token);
17148            }
17149            final boolean b;
17150            if (userInfo != null && userInfo.isManagedProfile()) {
17151                b = true;
17152            } else {
17153                b = false;
17154            }
17155            mUserNeedsBadging.put(userId, b);
17156            return b;
17157        }
17158        return mUserNeedsBadging.valueAt(index);
17159    }
17160
17161    @Override
17162    public KeySet getKeySetByAlias(String packageName, String alias) {
17163        if (packageName == null || alias == null) {
17164            return null;
17165        }
17166        synchronized(mPackages) {
17167            final PackageParser.Package pkg = mPackages.get(packageName);
17168            if (pkg == null) {
17169                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17170                throw new IllegalArgumentException("Unknown package: " + packageName);
17171            }
17172            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17173            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17174        }
17175    }
17176
17177    @Override
17178    public KeySet getSigningKeySet(String packageName) {
17179        if (packageName == null) {
17180            return null;
17181        }
17182        synchronized(mPackages) {
17183            final PackageParser.Package pkg = mPackages.get(packageName);
17184            if (pkg == null) {
17185                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17186                throw new IllegalArgumentException("Unknown package: " + packageName);
17187            }
17188            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17189                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17190                throw new SecurityException("May not access signing KeySet of other apps.");
17191            }
17192            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17193            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17194        }
17195    }
17196
17197    @Override
17198    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17199        if (packageName == null || ks == null) {
17200            return false;
17201        }
17202        synchronized(mPackages) {
17203            final PackageParser.Package pkg = mPackages.get(packageName);
17204            if (pkg == null) {
17205                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17206                throw new IllegalArgumentException("Unknown package: " + packageName);
17207            }
17208            IBinder ksh = ks.getToken();
17209            if (ksh instanceof KeySetHandle) {
17210                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17211                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17212            }
17213            return false;
17214        }
17215    }
17216
17217    @Override
17218    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17219        if (packageName == null || ks == null) {
17220            return false;
17221        }
17222        synchronized(mPackages) {
17223            final PackageParser.Package pkg = mPackages.get(packageName);
17224            if (pkg == null) {
17225                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17226                throw new IllegalArgumentException("Unknown package: " + packageName);
17227            }
17228            IBinder ksh = ks.getToken();
17229            if (ksh instanceof KeySetHandle) {
17230                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17231                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17232            }
17233            return false;
17234        }
17235    }
17236
17237    private void deletePackageIfUnusedLPr(final String packageName) {
17238        PackageSetting ps = mSettings.mPackages.get(packageName);
17239        if (ps == null) {
17240            return;
17241        }
17242        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17243            // TODO Implement atomic delete if package is unused
17244            // It is currently possible that the package will be deleted even if it is installed
17245            // after this method returns.
17246            mHandler.post(new Runnable() {
17247                public void run() {
17248                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17249                }
17250            });
17251        }
17252    }
17253
17254    /**
17255     * Check and throw if the given before/after packages would be considered a
17256     * downgrade.
17257     */
17258    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17259            throws PackageManagerException {
17260        if (after.versionCode < before.mVersionCode) {
17261            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17262                    "Update version code " + after.versionCode + " is older than current "
17263                    + before.mVersionCode);
17264        } else if (after.versionCode == before.mVersionCode) {
17265            if (after.baseRevisionCode < before.baseRevisionCode) {
17266                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17267                        "Update base revision code " + after.baseRevisionCode
17268                        + " is older than current " + before.baseRevisionCode);
17269            }
17270
17271            if (!ArrayUtils.isEmpty(after.splitNames)) {
17272                for (int i = 0; i < after.splitNames.length; i++) {
17273                    final String splitName = after.splitNames[i];
17274                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17275                    if (j != -1) {
17276                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17277                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17278                                    "Update split " + splitName + " revision code "
17279                                    + after.splitRevisionCodes[i] + " is older than current "
17280                                    + before.splitRevisionCodes[j]);
17281                        }
17282                    }
17283                }
17284            }
17285        }
17286    }
17287
17288    private static class MoveCallbacks extends Handler {
17289        private static final int MSG_CREATED = 1;
17290        private static final int MSG_STATUS_CHANGED = 2;
17291
17292        private final RemoteCallbackList<IPackageMoveObserver>
17293                mCallbacks = new RemoteCallbackList<>();
17294
17295        private final SparseIntArray mLastStatus = new SparseIntArray();
17296
17297        public MoveCallbacks(Looper looper) {
17298            super(looper);
17299        }
17300
17301        public void register(IPackageMoveObserver callback) {
17302            mCallbacks.register(callback);
17303        }
17304
17305        public void unregister(IPackageMoveObserver callback) {
17306            mCallbacks.unregister(callback);
17307        }
17308
17309        @Override
17310        public void handleMessage(Message msg) {
17311            final SomeArgs args = (SomeArgs) msg.obj;
17312            final int n = mCallbacks.beginBroadcast();
17313            for (int i = 0; i < n; i++) {
17314                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17315                try {
17316                    invokeCallback(callback, msg.what, args);
17317                } catch (RemoteException ignored) {
17318                }
17319            }
17320            mCallbacks.finishBroadcast();
17321            args.recycle();
17322        }
17323
17324        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17325                throws RemoteException {
17326            switch (what) {
17327                case MSG_CREATED: {
17328                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17329                    break;
17330                }
17331                case MSG_STATUS_CHANGED: {
17332                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17333                    break;
17334                }
17335            }
17336        }
17337
17338        private void notifyCreated(int moveId, Bundle extras) {
17339            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17340
17341            final SomeArgs args = SomeArgs.obtain();
17342            args.argi1 = moveId;
17343            args.arg2 = extras;
17344            obtainMessage(MSG_CREATED, args).sendToTarget();
17345        }
17346
17347        private void notifyStatusChanged(int moveId, int status) {
17348            notifyStatusChanged(moveId, status, -1);
17349        }
17350
17351        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17352            Slog.v(TAG, "Move " + moveId + " status " + status);
17353
17354            final SomeArgs args = SomeArgs.obtain();
17355            args.argi1 = moveId;
17356            args.argi2 = status;
17357            args.arg3 = estMillis;
17358            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17359
17360            synchronized (mLastStatus) {
17361                mLastStatus.put(moveId, status);
17362            }
17363        }
17364    }
17365
17366    private final static class OnPermissionChangeListeners extends Handler {
17367        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17368
17369        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17370                new RemoteCallbackList<>();
17371
17372        public OnPermissionChangeListeners(Looper looper) {
17373            super(looper);
17374        }
17375
17376        @Override
17377        public void handleMessage(Message msg) {
17378            switch (msg.what) {
17379                case MSG_ON_PERMISSIONS_CHANGED: {
17380                    final int uid = msg.arg1;
17381                    handleOnPermissionsChanged(uid);
17382                } break;
17383            }
17384        }
17385
17386        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17387            mPermissionListeners.register(listener);
17388
17389        }
17390
17391        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17392            mPermissionListeners.unregister(listener);
17393        }
17394
17395        public void onPermissionsChanged(int uid) {
17396            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17397                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17398            }
17399        }
17400
17401        private void handleOnPermissionsChanged(int uid) {
17402            final int count = mPermissionListeners.beginBroadcast();
17403            try {
17404                for (int i = 0; i < count; i++) {
17405                    IOnPermissionsChangeListener callback = mPermissionListeners
17406                            .getBroadcastItem(i);
17407                    try {
17408                        callback.onPermissionsChanged(uid);
17409                    } catch (RemoteException e) {
17410                        Log.e(TAG, "Permission listener is dead", e);
17411                    }
17412                }
17413            } finally {
17414                mPermissionListeners.finishBroadcast();
17415            }
17416        }
17417    }
17418
17419    private class PackageManagerInternalImpl extends PackageManagerInternal {
17420        @Override
17421        public void setLocationPackagesProvider(PackagesProvider provider) {
17422            synchronized (mPackages) {
17423                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17424            }
17425        }
17426
17427        @Override
17428        public void setImePackagesProvider(PackagesProvider provider) {
17429            synchronized (mPackages) {
17430                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17431            }
17432        }
17433
17434        @Override
17435        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17436            synchronized (mPackages) {
17437                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17438            }
17439        }
17440
17441        @Override
17442        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17443            synchronized (mPackages) {
17444                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17445            }
17446        }
17447
17448        @Override
17449        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17450            synchronized (mPackages) {
17451                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17452            }
17453        }
17454
17455        @Override
17456        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17457            synchronized (mPackages) {
17458                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17459            }
17460        }
17461
17462        @Override
17463        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17464            synchronized (mPackages) {
17465                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17466            }
17467        }
17468
17469        @Override
17470        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17471            synchronized (mPackages) {
17472                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17473                        packageName, userId);
17474            }
17475        }
17476
17477        @Override
17478        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17479            synchronized (mPackages) {
17480                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17481                        packageName, userId);
17482            }
17483        }
17484
17485        @Override
17486        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17487            synchronized (mPackages) {
17488                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17489                        packageName, userId);
17490            }
17491        }
17492
17493        @Override
17494        public void setKeepUninstalledPackages(final List<String> packageList) {
17495            Preconditions.checkNotNull(packageList);
17496            List<String> removedFromList = null;
17497            synchronized (mPackages) {
17498                if (mKeepUninstalledPackages != null) {
17499                    final int packagesCount = mKeepUninstalledPackages.size();
17500                    for (int i = 0; i < packagesCount; i++) {
17501                        String oldPackage = mKeepUninstalledPackages.get(i);
17502                        if (packageList != null && packageList.contains(oldPackage)) {
17503                            continue;
17504                        }
17505                        if (removedFromList == null) {
17506                            removedFromList = new ArrayList<>();
17507                        }
17508                        removedFromList.add(oldPackage);
17509                    }
17510                }
17511                mKeepUninstalledPackages = new ArrayList<>(packageList);
17512                if (removedFromList != null) {
17513                    final int removedCount = removedFromList.size();
17514                    for (int i = 0; i < removedCount; i++) {
17515                        deletePackageIfUnusedLPr(removedFromList.get(i));
17516                    }
17517                }
17518            }
17519        }
17520
17521        @Override
17522        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17523            synchronized (mPackages) {
17524                // If we do not support permission review, done.
17525                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17526                    return false;
17527                }
17528
17529                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17530                if (packageSetting == null) {
17531                    return false;
17532                }
17533
17534                // Permission review applies only to apps not supporting the new permission model.
17535                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17536                    return false;
17537                }
17538
17539                // Legacy apps have the permission and get user consent on launch.
17540                PermissionsState permissionsState = packageSetting.getPermissionsState();
17541                return permissionsState.isPermissionReviewRequired(userId);
17542            }
17543        }
17544    }
17545
17546    @Override
17547    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17548        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17549        synchronized (mPackages) {
17550            final long identity = Binder.clearCallingIdentity();
17551            try {
17552                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17553                        packageNames, userId);
17554            } finally {
17555                Binder.restoreCallingIdentity(identity);
17556            }
17557        }
17558    }
17559
17560    private static void enforceSystemOrPhoneCaller(String tag) {
17561        int callingUid = Binder.getCallingUid();
17562        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17563            throw new SecurityException(
17564                    "Cannot call " + tag + " from UID " + callingUid);
17565        }
17566    }
17567}
17568