PackageManagerService.java revision 5fd83dcda2d5423014c64cbcb6a880742145dc59
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_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
71import static android.content.pm.PackageManager.PERMISSION_DENIED;
72import static android.content.pm.PackageManager.PERMISSION_GRANTED;
73import static android.content.pm.PackageParser.isApkFile;
74import static android.os.Process.PACKAGE_INFO_GID;
75import static android.os.Process.SYSTEM_UID;
76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
77import static android.system.OsConstants.O_CREAT;
78import static android.system.OsConstants.O_RDWR;
79
80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
84import static com.android.internal.util.ArrayUtils.appendInt;
85import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
94
95import android.Manifest;
96import android.annotation.NonNull;
97import android.annotation.Nullable;
98import android.app.ActivityManager;
99import android.app.ActivityManagerNative;
100import android.app.AppGlobals;
101import android.app.IActivityManager;
102import android.app.admin.IDevicePolicyManager;
103import android.app.backup.IBackupManager;
104import android.content.BroadcastReceiver;
105import android.content.ComponentName;
106import android.content.Context;
107import android.content.IIntentReceiver;
108import android.content.Intent;
109import android.content.IntentFilter;
110import android.content.IntentSender;
111import android.content.IntentSender.SendIntentException;
112import android.content.ServiceConnection;
113import android.content.pm.ActivityInfo;
114import android.content.pm.ApplicationInfo;
115import android.content.pm.AppsQueryHelper;
116import android.content.pm.ComponentInfo;
117import android.content.pm.EphemeralApplicationInfo;
118import android.content.pm.EphemeralResolveInfo;
119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
120import android.content.pm.FeatureInfo;
121import android.content.pm.IOnPermissionsChangeListener;
122import android.content.pm.IPackageDataObserver;
123import android.content.pm.IPackageDeleteObserver;
124import android.content.pm.IPackageDeleteObserver2;
125import android.content.pm.IPackageInstallObserver2;
126import android.content.pm.IPackageInstaller;
127import android.content.pm.IPackageManager;
128import android.content.pm.IPackageMoveObserver;
129import android.content.pm.IPackageStatsObserver;
130import android.content.pm.InstrumentationInfo;
131import android.content.pm.IntentFilterVerificationInfo;
132import android.content.pm.KeySet;
133import android.content.pm.PackageCleanItem;
134import android.content.pm.PackageInfo;
135import android.content.pm.PackageInfoLite;
136import android.content.pm.PackageInstaller;
137import android.content.pm.PackageManager;
138import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
139import android.content.pm.PackageManagerInternal;
140import android.content.pm.PackageParser;
141import android.content.pm.PackageParser.ActivityIntentInfo;
142import android.content.pm.PackageParser.PackageLite;
143import android.content.pm.PackageParser.PackageParserException;
144import android.content.pm.PackageStats;
145import android.content.pm.PackageUserState;
146import android.content.pm.ParceledListSlice;
147import android.content.pm.PermissionGroupInfo;
148import android.content.pm.PermissionInfo;
149import android.content.pm.ProviderInfo;
150import android.content.pm.ResolveInfo;
151import android.content.pm.ServiceInfo;
152import android.content.pm.Signature;
153import android.content.pm.UserInfo;
154import android.content.pm.VerificationParams;
155import android.content.pm.VerifierDeviceIdentity;
156import android.content.pm.VerifierInfo;
157import android.content.res.Resources;
158import android.graphics.Bitmap;
159import android.hardware.display.DisplayManager;
160import android.net.Uri;
161import android.os.Binder;
162import android.os.Build;
163import android.os.Bundle;
164import android.os.Debug;
165import android.os.Environment;
166import android.os.Environment.UserEnvironment;
167import android.os.FileUtils;
168import android.os.Handler;
169import android.os.IBinder;
170import android.os.Looper;
171import android.os.Message;
172import android.os.Parcel;
173import android.os.ParcelFileDescriptor;
174import android.os.Process;
175import android.os.RemoteCallbackList;
176import android.os.RemoteException;
177import android.os.ResultReceiver;
178import android.os.SELinux;
179import android.os.ServiceManager;
180import android.os.SystemClock;
181import android.os.SystemProperties;
182import android.os.Trace;
183import android.os.UserHandle;
184import android.os.UserManager;
185import android.os.storage.IMountService;
186import android.os.storage.MountServiceInternal;
187import android.os.storage.StorageEventListener;
188import android.os.storage.StorageManager;
189import android.os.storage.VolumeInfo;
190import android.os.storage.VolumeRecord;
191import android.security.KeyStore;
192import android.security.SystemKeyStore;
193import android.system.ErrnoException;
194import android.system.Os;
195import android.system.StructStat;
196import android.text.TextUtils;
197import android.text.format.DateUtils;
198import android.util.ArrayMap;
199import android.util.ArraySet;
200import android.util.AtomicFile;
201import android.util.DisplayMetrics;
202import android.util.EventLog;
203import android.util.ExceptionUtils;
204import android.util.Log;
205import android.util.LogPrinter;
206import android.util.MathUtils;
207import android.util.PrintStreamPrinter;
208import android.util.Slog;
209import android.util.SparseArray;
210import android.util.SparseBooleanArray;
211import android.util.SparseIntArray;
212import android.util.Xml;
213import android.view.Display;
214
215import com.android.internal.R;
216import com.android.internal.annotations.GuardedBy;
217import com.android.internal.app.IMediaContainerService;
218import com.android.internal.app.ResolverActivity;
219import com.android.internal.content.NativeLibraryHelper;
220import com.android.internal.content.PackageHelper;
221import com.android.internal.os.IParcelFileDescriptorFactory;
222import com.android.internal.os.InstallerConnection.InstallerException;
223import com.android.internal.os.SomeArgs;
224import com.android.internal.os.Zygote;
225import com.android.internal.util.ArrayUtils;
226import com.android.internal.util.FastPrintWriter;
227import com.android.internal.util.FastXmlSerializer;
228import com.android.internal.util.IndentingPrintWriter;
229import com.android.internal.util.Preconditions;
230import com.android.server.EventLogTags;
231import com.android.server.FgThread;
232import com.android.server.IntentResolver;
233import com.android.server.LocalServices;
234import com.android.server.ServiceThread;
235import com.android.server.SystemConfig;
236import com.android.server.Watchdog;
237import com.android.server.pm.PermissionsState.PermissionState;
238import com.android.server.pm.Settings.DatabaseVersion;
239import com.android.server.pm.Settings.VersionInfo;
240import com.android.server.storage.DeviceStorageMonitorInternal;
241
242import dalvik.system.DexFile;
243import dalvik.system.VMRuntime;
244
245import libcore.io.IoUtils;
246import libcore.util.EmptyArray;
247
248import org.xmlpull.v1.XmlPullParser;
249import org.xmlpull.v1.XmlPullParserException;
250import org.xmlpull.v1.XmlSerializer;
251
252import java.io.BufferedInputStream;
253import java.io.BufferedOutputStream;
254import java.io.BufferedReader;
255import java.io.ByteArrayInputStream;
256import java.io.ByteArrayOutputStream;
257import java.io.File;
258import java.io.FileDescriptor;
259import java.io.FileNotFoundException;
260import java.io.FileOutputStream;
261import java.io.FileReader;
262import java.io.FilenameFilter;
263import java.io.IOException;
264import java.io.InputStream;
265import java.io.PrintWriter;
266import java.nio.charset.StandardCharsets;
267import java.security.MessageDigest;
268import java.security.NoSuchAlgorithmException;
269import java.security.PublicKey;
270import java.security.cert.CertificateEncodingException;
271import java.security.cert.CertificateException;
272import java.text.SimpleDateFormat;
273import java.util.ArrayList;
274import java.util.Arrays;
275import java.util.Collection;
276import java.util.Collections;
277import java.util.Comparator;
278import java.util.Date;
279import java.util.Iterator;
280import java.util.List;
281import java.util.Map;
282import java.util.Objects;
283import java.util.Set;
284import java.util.concurrent.CountDownLatch;
285import java.util.concurrent.TimeUnit;
286import java.util.concurrent.atomic.AtomicBoolean;
287import java.util.concurrent.atomic.AtomicInteger;
288import java.util.concurrent.atomic.AtomicLong;
289
290/**
291 * Keep track of all those .apks everywhere.
292 *
293 * This is very central to the platform's security; please run the unit
294 * tests whenever making modifications here:
295 *
296runtest -c android.content.pm.PackageManagerTests frameworks-core
297 *
298 * {@hide}
299 */
300public class PackageManagerService extends IPackageManager.Stub {
301    static final String TAG = "PackageManager";
302    static final boolean DEBUG_SETTINGS = false;
303    static final boolean DEBUG_PREFERRED = false;
304    static final boolean DEBUG_UPGRADE = false;
305    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
306    private static final boolean DEBUG_BACKUP = false;
307    private static final boolean DEBUG_INSTALL = false;
308    private static final boolean DEBUG_REMOVE = false;
309    private static final boolean DEBUG_BROADCASTS = false;
310    private static final boolean DEBUG_SHOW_INFO = false;
311    private static final boolean DEBUG_PACKAGE_INFO = false;
312    private static final boolean DEBUG_INTENT_MATCHING = false;
313    private static final boolean DEBUG_PACKAGE_SCANNING = false;
314    private static final boolean DEBUG_VERIFY = false;
315    private static final boolean DEBUG_DEXOPT = false;
316    private static final boolean DEBUG_ABI_SELECTION = false;
317    private static final boolean DEBUG_EPHEMERAL = false;
318    private static final boolean DEBUG_TRIAGED_MISSING = false;
319
320    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
321
322    private static final boolean DISABLE_EPHEMERAL_APPS = true;
323
324    private static final int RADIO_UID = Process.PHONE_UID;
325    private static final int LOG_UID = Process.LOG_UID;
326    private static final int NFC_UID = Process.NFC_UID;
327    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
328    private static final int SHELL_UID = Process.SHELL_UID;
329
330    // Cap the size of permission trees that 3rd party apps can define
331    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
332
333    // Suffix used during package installation when copying/moving
334    // package apks to install directory.
335    private static final String INSTALL_PACKAGE_SUFFIX = "-";
336
337    static final int SCAN_NO_DEX = 1<<1;
338    static final int SCAN_FORCE_DEX = 1<<2;
339    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
340    static final int SCAN_NEW_INSTALL = 1<<4;
341    static final int SCAN_NO_PATHS = 1<<5;
342    static final int SCAN_UPDATE_TIME = 1<<6;
343    static final int SCAN_DEFER_DEX = 1<<7;
344    static final int SCAN_BOOTING = 1<<8;
345    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
346    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
347    static final int SCAN_REPLACING = 1<<11;
348    static final int SCAN_REQUIRE_KNOWN = 1<<12;
349    static final int SCAN_MOVE = 1<<13;
350    static final int SCAN_INITIAL = 1<<14;
351
352    static final int REMOVE_CHATTY = 1<<16;
353
354    private static final int[] EMPTY_INT_ARRAY = new int[0];
355
356    /**
357     * Timeout (in milliseconds) after which the watchdog should declare that
358     * our handler thread is wedged.  The usual default for such things is one
359     * minute but we sometimes do very lengthy I/O operations on this thread,
360     * such as installing multi-gigabyte applications, so ours needs to be longer.
361     */
362    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
363
364    /**
365     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
366     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
367     * settings entry if available, otherwise we use the hardcoded default.  If it's been
368     * more than this long since the last fstrim, we force one during the boot sequence.
369     *
370     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
371     * one gets run at the next available charging+idle time.  This final mandatory
372     * no-fstrim check kicks in only of the other scheduling criteria is never met.
373     */
374    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
375
376    /**
377     * Whether verification is enabled by default.
378     */
379    private static final boolean DEFAULT_VERIFY_ENABLE = true;
380
381    /**
382     * The default maximum time to wait for the verification agent to return in
383     * milliseconds.
384     */
385    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
386
387    /**
388     * The default response for package verification timeout.
389     *
390     * This can be either PackageManager.VERIFICATION_ALLOW or
391     * PackageManager.VERIFICATION_REJECT.
392     */
393    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
394
395    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
396
397    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
398            DEFAULT_CONTAINER_PACKAGE,
399            "com.android.defcontainer.DefaultContainerService");
400
401    private static final String KILL_APP_REASON_GIDS_CHANGED =
402            "permission grant or revoke changed gids";
403
404    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
405            "permissions revoked";
406
407    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
408
409    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
410
411    /** Permission grant: not grant the permission. */
412    private static final int GRANT_DENIED = 1;
413
414    /** Permission grant: grant the permission as an install permission. */
415    private static final int GRANT_INSTALL = 2;
416
417    /** Permission grant: grant the permission as a runtime one. */
418    private static final int GRANT_RUNTIME = 3;
419
420    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
421    private static final int GRANT_UPGRADE = 4;
422
423    /** Canonical intent used to identify what counts as a "web browser" app */
424    private static final Intent sBrowserIntent;
425    static {
426        sBrowserIntent = new Intent();
427        sBrowserIntent.setAction(Intent.ACTION_VIEW);
428        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
429        sBrowserIntent.setData(Uri.parse("http:"));
430    }
431
432    final ServiceThread mHandlerThread;
433
434    final PackageHandler mHandler;
435
436    /**
437     * Messages for {@link #mHandler} that need to wait for system ready before
438     * being dispatched.
439     */
440    private ArrayList<Message> mPostSystemReadyMessages;
441
442    final int mSdkVersion = Build.VERSION.SDK_INT;
443
444    final Context mContext;
445    final boolean mFactoryTest;
446    final boolean mOnlyCore;
447    final DisplayMetrics mMetrics;
448    final int mDefParseFlags;
449    final String[] mSeparateProcesses;
450    final boolean mIsUpgrade;
451
452    /** The location for ASEC container files on internal storage. */
453    final String mAsecInternalPath;
454
455    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
456    // LOCK HELD.  Can be called with mInstallLock held.
457    @GuardedBy("mInstallLock")
458    final Installer mInstaller;
459
460    /** Directory where installed third-party apps stored */
461    final File mAppInstallDir;
462    final File mEphemeralInstallDir;
463
464    /**
465     * Directory to which applications installed internally have their
466     * 32 bit native libraries copied.
467     */
468    private File mAppLib32InstallDir;
469
470    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
471    // apps.
472    final File mDrmAppPrivateInstallDir;
473
474    // ----------------------------------------------------------------
475
476    // Lock for state used when installing and doing other long running
477    // operations.  Methods that must be called with this lock held have
478    // the suffix "LI".
479    final Object mInstallLock = new Object();
480
481    // ----------------------------------------------------------------
482
483    // Keys are String (package name), values are Package.  This also serves
484    // as the lock for the global state.  Methods that must be called with
485    // this lock held have the prefix "LP".
486    @GuardedBy("mPackages")
487    final ArrayMap<String, PackageParser.Package> mPackages =
488            new ArrayMap<String, PackageParser.Package>();
489
490    // Tracks available target package names -> overlay package paths.
491    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
492        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
493
494    /**
495     * Tracks new system packages [received in an OTA] that we expect to
496     * find updated user-installed versions. Keys are package name, values
497     * are package location.
498     */
499    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
500
501    /**
502     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
503     */
504    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
505    /**
506     * Whether or not system app permissions should be promoted from install to runtime.
507     */
508    boolean mPromoteSystemApps;
509
510    final Settings mSettings;
511    boolean mRestoredSettings;
512
513    // System configuration read by SystemConfig.
514    final int[] mGlobalGids;
515    final SparseArray<ArraySet<String>> mSystemPermissions;
516    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
517
518    // If mac_permissions.xml was found for seinfo labeling.
519    boolean mFoundPolicyFile;
520
521    // If a recursive restorecon of /data/data/<pkg> is needed.
522    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
523
524    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
525
526    public static final class SharedLibraryEntry {
527        public final String path;
528        public final String apk;
529
530        SharedLibraryEntry(String _path, String _apk) {
531            path = _path;
532            apk = _apk;
533        }
534    }
535
536    // Currently known shared libraries.
537    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
538            new ArrayMap<String, SharedLibraryEntry>();
539
540    // All available activities, for your resolving pleasure.
541    final ActivityIntentResolver mActivities =
542            new ActivityIntentResolver();
543
544    // All available receivers, for your resolving pleasure.
545    final ActivityIntentResolver mReceivers =
546            new ActivityIntentResolver();
547
548    // All available services, for your resolving pleasure.
549    final ServiceIntentResolver mServices = new ServiceIntentResolver();
550
551    // All available providers, for your resolving pleasure.
552    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
553
554    // Mapping from provider base names (first directory in content URI codePath)
555    // to the provider information.
556    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
557            new ArrayMap<String, PackageParser.Provider>();
558
559    // Mapping from instrumentation class names to info about them.
560    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
561            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
562
563    // Mapping from permission names to info about them.
564    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
565            new ArrayMap<String, PackageParser.PermissionGroup>();
566
567    // Packages whose data we have transfered into another package, thus
568    // should no longer exist.
569    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
570
571    // Broadcast actions that are only available to the system.
572    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
573
574    /** List of packages waiting for verification. */
575    final SparseArray<PackageVerificationState> mPendingVerification
576            = new SparseArray<PackageVerificationState>();
577
578    /** Set of packages associated with each app op permission. */
579    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
580
581    final PackageInstallerService mInstallerService;
582
583    private final PackageDexOptimizer mPackageDexOptimizer;
584
585    private AtomicInteger mNextMoveId = new AtomicInteger();
586    private final MoveCallbacks mMoveCallbacks;
587
588    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
589
590    // Cache of users who need badging.
591    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
592
593    /** Token for keys in mPendingVerification. */
594    private int mPendingVerificationToken = 0;
595
596    volatile boolean mSystemReady;
597    volatile boolean mSafeMode;
598    volatile boolean mHasSystemUidErrors;
599
600    ApplicationInfo mAndroidApplication;
601    final ActivityInfo mResolveActivity = new ActivityInfo();
602    final ResolveInfo mResolveInfo = new ResolveInfo();
603    ComponentName mResolveComponentName;
604    PackageParser.Package mPlatformPackage;
605    ComponentName mCustomResolverComponentName;
606
607    boolean mResolverReplaced = false;
608
609    private final @Nullable ComponentName mIntentFilterVerifierComponent;
610    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
611
612    private int mIntentFilterVerificationToken = 0;
613
614    /** Component that knows whether or not an ephemeral application exists */
615    final ComponentName mEphemeralResolverComponent;
616    /** The service connection to the ephemeral resolver */
617    final EphemeralResolverConnection mEphemeralResolverConnection;
618
619    /** Component used to install ephemeral applications */
620    final ComponentName mEphemeralInstallerComponent;
621    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
622    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
623
624    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
625            = new SparseArray<IntentFilterVerificationState>();
626
627    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
628            new DefaultPermissionGrantPolicy(this);
629
630    // List of packages names to keep cached, even if they are uninstalled for all users
631    private List<String> mKeepUninstalledPackages;
632
633    private static class IFVerificationParams {
634        PackageParser.Package pkg;
635        boolean replacing;
636        int userId;
637        int verifierUid;
638
639        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
640                int _userId, int _verifierUid) {
641            pkg = _pkg;
642            replacing = _replacing;
643            userId = _userId;
644            replacing = _replacing;
645            verifierUid = _verifierUid;
646        }
647    }
648
649    private interface IntentFilterVerifier<T extends IntentFilter> {
650        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
651                                               T filter, String packageName);
652        void startVerifications(int userId);
653        void receiveVerificationResponse(int verificationId);
654    }
655
656    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
657        private Context mContext;
658        private ComponentName mIntentFilterVerifierComponent;
659        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
660
661        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
662            mContext = context;
663            mIntentFilterVerifierComponent = verifierComponent;
664        }
665
666        private String getDefaultScheme() {
667            return IntentFilter.SCHEME_HTTPS;
668        }
669
670        @Override
671        public void startVerifications(int userId) {
672            // Launch verifications requests
673            int count = mCurrentIntentFilterVerifications.size();
674            for (int n=0; n<count; n++) {
675                int verificationId = mCurrentIntentFilterVerifications.get(n);
676                final IntentFilterVerificationState ivs =
677                        mIntentFilterVerificationStates.get(verificationId);
678
679                String packageName = ivs.getPackageName();
680
681                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
682                final int filterCount = filters.size();
683                ArraySet<String> domainsSet = new ArraySet<>();
684                for (int m=0; m<filterCount; m++) {
685                    PackageParser.ActivityIntentInfo filter = filters.get(m);
686                    domainsSet.addAll(filter.getHostsList());
687                }
688                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
689                synchronized (mPackages) {
690                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
691                            packageName, domainsList) != null) {
692                        scheduleWriteSettingsLocked();
693                    }
694                }
695                sendVerificationRequest(userId, verificationId, ivs);
696            }
697            mCurrentIntentFilterVerifications.clear();
698        }
699
700        private void sendVerificationRequest(int userId, int verificationId,
701                IntentFilterVerificationState ivs) {
702
703            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
704            verificationIntent.putExtra(
705                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
706                    verificationId);
707            verificationIntent.putExtra(
708                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
709                    getDefaultScheme());
710            verificationIntent.putExtra(
711                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
712                    ivs.getHostsString());
713            verificationIntent.putExtra(
714                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
715                    ivs.getPackageName());
716            verificationIntent.setComponent(mIntentFilterVerifierComponent);
717            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
718
719            UserHandle user = new UserHandle(userId);
720            mContext.sendBroadcastAsUser(verificationIntent, user);
721            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
722                    "Sending IntentFilter verification broadcast");
723        }
724
725        public void receiveVerificationResponse(int verificationId) {
726            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
727
728            final boolean verified = ivs.isVerified();
729
730            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
731            final int count = filters.size();
732            if (DEBUG_DOMAIN_VERIFICATION) {
733                Slog.i(TAG, "Received verification response " + verificationId
734                        + " for " + count + " filters, verified=" + verified);
735            }
736            for (int n=0; n<count; n++) {
737                PackageParser.ActivityIntentInfo filter = filters.get(n);
738                filter.setVerified(verified);
739
740                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
741                        + " verified with result:" + verified + " and hosts:"
742                        + ivs.getHostsString());
743            }
744
745            mIntentFilterVerificationStates.remove(verificationId);
746
747            final String packageName = ivs.getPackageName();
748            IntentFilterVerificationInfo ivi = null;
749
750            synchronized (mPackages) {
751                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
752            }
753            if (ivi == null) {
754                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
755                        + verificationId + " packageName:" + packageName);
756                return;
757            }
758            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
759                    "Updating IntentFilterVerificationInfo for package " + packageName
760                            +" verificationId:" + verificationId);
761
762            synchronized (mPackages) {
763                if (verified) {
764                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
765                } else {
766                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
767                }
768                scheduleWriteSettingsLocked();
769
770                final int userId = ivs.getUserId();
771                if (userId != UserHandle.USER_ALL) {
772                    final int userStatus =
773                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
774
775                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
776                    boolean needUpdate = false;
777
778                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
779                    // already been set by the User thru the Disambiguation dialog
780                    switch (userStatus) {
781                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
782                            if (verified) {
783                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
784                            } else {
785                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
786                            }
787                            needUpdate = true;
788                            break;
789
790                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
791                            if (verified) {
792                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
793                                needUpdate = true;
794                            }
795                            break;
796
797                        default:
798                            // Nothing to do
799                    }
800
801                    if (needUpdate) {
802                        mSettings.updateIntentFilterVerificationStatusLPw(
803                                packageName, updatedStatus, userId);
804                        scheduleWritePackageRestrictionsLocked(userId);
805                    }
806                }
807            }
808        }
809
810        @Override
811        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
812                    ActivityIntentInfo filter, String packageName) {
813            if (!hasValidDomains(filter)) {
814                return false;
815            }
816            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
817            if (ivs == null) {
818                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
819                        packageName);
820            }
821            if (DEBUG_DOMAIN_VERIFICATION) {
822                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
823            }
824            ivs.addFilter(filter);
825            return true;
826        }
827
828        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
829                int userId, int verificationId, String packageName) {
830            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
831                    verifierUid, userId, packageName);
832            ivs.setPendingState();
833            synchronized (mPackages) {
834                mIntentFilterVerificationStates.append(verificationId, ivs);
835                mCurrentIntentFilterVerifications.add(verificationId);
836            }
837            return ivs;
838        }
839    }
840
841    private static boolean hasValidDomains(ActivityIntentInfo filter) {
842        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
843                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
844                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
845    }
846
847    // Set of pending broadcasts for aggregating enable/disable of components.
848    static class PendingPackageBroadcasts {
849        // for each user id, a map of <package name -> components within that package>
850        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
851
852        public PendingPackageBroadcasts() {
853            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
854        }
855
856        public ArrayList<String> get(int userId, String packageName) {
857            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
858            return packages.get(packageName);
859        }
860
861        public void put(int userId, String packageName, ArrayList<String> components) {
862            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
863            packages.put(packageName, components);
864        }
865
866        public void remove(int userId, String packageName) {
867            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
868            if (packages != null) {
869                packages.remove(packageName);
870            }
871        }
872
873        public void remove(int userId) {
874            mUidMap.remove(userId);
875        }
876
877        public int userIdCount() {
878            return mUidMap.size();
879        }
880
881        public int userIdAt(int n) {
882            return mUidMap.keyAt(n);
883        }
884
885        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
886            return mUidMap.get(userId);
887        }
888
889        public int size() {
890            // total number of pending broadcast entries across all userIds
891            int num = 0;
892            for (int i = 0; i< mUidMap.size(); i++) {
893                num += mUidMap.valueAt(i).size();
894            }
895            return num;
896        }
897
898        public void clear() {
899            mUidMap.clear();
900        }
901
902        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
903            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
904            if (map == null) {
905                map = new ArrayMap<String, ArrayList<String>>();
906                mUidMap.put(userId, map);
907            }
908            return map;
909        }
910    }
911    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
912
913    // Service Connection to remote media container service to copy
914    // package uri's from external media onto secure containers
915    // or internal storage.
916    private IMediaContainerService mContainerService = null;
917
918    static final int SEND_PENDING_BROADCAST = 1;
919    static final int MCS_BOUND = 3;
920    static final int END_COPY = 4;
921    static final int INIT_COPY = 5;
922    static final int MCS_UNBIND = 6;
923    static final int START_CLEANING_PACKAGE = 7;
924    static final int FIND_INSTALL_LOC = 8;
925    static final int POST_INSTALL = 9;
926    static final int MCS_RECONNECT = 10;
927    static final int MCS_GIVE_UP = 11;
928    static final int UPDATED_MEDIA_STATUS = 12;
929    static final int WRITE_SETTINGS = 13;
930    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
931    static final int PACKAGE_VERIFIED = 15;
932    static final int CHECK_PENDING_VERIFICATION = 16;
933    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
934    static final int INTENT_FILTER_VERIFIED = 18;
935
936    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
937
938    // Delay time in millisecs
939    static final int BROADCAST_DELAY = 10 * 1000;
940
941    static UserManagerService sUserManager;
942
943    // Stores a list of users whose package restrictions file needs to be updated
944    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
945
946    final private DefaultContainerConnection mDefContainerConn =
947            new DefaultContainerConnection();
948    class DefaultContainerConnection implements ServiceConnection {
949        public void onServiceConnected(ComponentName name, IBinder service) {
950            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
951            IMediaContainerService imcs =
952                IMediaContainerService.Stub.asInterface(service);
953            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
954        }
955
956        public void onServiceDisconnected(ComponentName name) {
957            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
958        }
959    }
960
961    // Recordkeeping of restore-after-install operations that are currently in flight
962    // between the Package Manager and the Backup Manager
963    static class PostInstallData {
964        public InstallArgs args;
965        public PackageInstalledInfo res;
966
967        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
968            args = _a;
969            res = _r;
970        }
971    }
972
973    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
974    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
975
976    // XML tags for backup/restore of various bits of state
977    private static final String TAG_PREFERRED_BACKUP = "pa";
978    private static final String TAG_DEFAULT_APPS = "da";
979    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
980
981    final @Nullable String mRequiredVerifierPackage;
982    final @Nullable String mRequiredInstallerPackage;
983
984    private final PackageUsage mPackageUsage = new PackageUsage();
985
986    private class PackageUsage {
987        private static final int WRITE_INTERVAL
988            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
989
990        private final Object mFileLock = new Object();
991        private final AtomicLong mLastWritten = new AtomicLong(0);
992        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
993
994        private boolean mIsHistoricalPackageUsageAvailable = true;
995
996        boolean isHistoricalPackageUsageAvailable() {
997            return mIsHistoricalPackageUsageAvailable;
998        }
999
1000        void write(boolean force) {
1001            if (force) {
1002                writeInternal();
1003                return;
1004            }
1005            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1006                && !DEBUG_DEXOPT) {
1007                return;
1008            }
1009            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1010                new Thread("PackageUsage_DiskWriter") {
1011                    @Override
1012                    public void run() {
1013                        try {
1014                            writeInternal();
1015                        } finally {
1016                            mBackgroundWriteRunning.set(false);
1017                        }
1018                    }
1019                }.start();
1020            }
1021        }
1022
1023        private void writeInternal() {
1024            synchronized (mPackages) {
1025                synchronized (mFileLock) {
1026                    AtomicFile file = getFile();
1027                    FileOutputStream f = null;
1028                    try {
1029                        f = file.startWrite();
1030                        BufferedOutputStream out = new BufferedOutputStream(f);
1031                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1032                        StringBuilder sb = new StringBuilder();
1033                        for (PackageParser.Package pkg : mPackages.values()) {
1034                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1035                                continue;
1036                            }
1037                            sb.setLength(0);
1038                            sb.append(pkg.packageName);
1039                            sb.append(' ');
1040                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1041                            sb.append('\n');
1042                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1043                        }
1044                        out.flush();
1045                        file.finishWrite(f);
1046                    } catch (IOException e) {
1047                        if (f != null) {
1048                            file.failWrite(f);
1049                        }
1050                        Log.e(TAG, "Failed to write package usage times", e);
1051                    }
1052                }
1053            }
1054            mLastWritten.set(SystemClock.elapsedRealtime());
1055        }
1056
1057        void readLP() {
1058            synchronized (mFileLock) {
1059                AtomicFile file = getFile();
1060                BufferedInputStream in = null;
1061                try {
1062                    in = new BufferedInputStream(file.openRead());
1063                    StringBuffer sb = new StringBuffer();
1064                    while (true) {
1065                        String packageName = readToken(in, sb, ' ');
1066                        if (packageName == null) {
1067                            break;
1068                        }
1069                        String timeInMillisString = readToken(in, sb, '\n');
1070                        if (timeInMillisString == null) {
1071                            throw new IOException("Failed to find last usage time for package "
1072                                                  + packageName);
1073                        }
1074                        PackageParser.Package pkg = mPackages.get(packageName);
1075                        if (pkg == null) {
1076                            continue;
1077                        }
1078                        long timeInMillis;
1079                        try {
1080                            timeInMillis = Long.parseLong(timeInMillisString);
1081                        } catch (NumberFormatException e) {
1082                            throw new IOException("Failed to parse " + timeInMillisString
1083                                                  + " as a long.", e);
1084                        }
1085                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1086                    }
1087                } catch (FileNotFoundException expected) {
1088                    mIsHistoricalPackageUsageAvailable = false;
1089                } catch (IOException e) {
1090                    Log.w(TAG, "Failed to read package usage times", e);
1091                } finally {
1092                    IoUtils.closeQuietly(in);
1093                }
1094            }
1095            mLastWritten.set(SystemClock.elapsedRealtime());
1096        }
1097
1098        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1099                throws IOException {
1100            sb.setLength(0);
1101            while (true) {
1102                int ch = in.read();
1103                if (ch == -1) {
1104                    if (sb.length() == 0) {
1105                        return null;
1106                    }
1107                    throw new IOException("Unexpected EOF");
1108                }
1109                if (ch == endOfToken) {
1110                    return sb.toString();
1111                }
1112                sb.append((char)ch);
1113            }
1114        }
1115
1116        private AtomicFile getFile() {
1117            File dataDir = Environment.getDataDirectory();
1118            File systemDir = new File(dataDir, "system");
1119            File fname = new File(systemDir, "package-usage.list");
1120            return new AtomicFile(fname);
1121        }
1122    }
1123
1124    class PackageHandler extends Handler {
1125        private boolean mBound = false;
1126        final ArrayList<HandlerParams> mPendingInstalls =
1127            new ArrayList<HandlerParams>();
1128
1129        private boolean connectToService() {
1130            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1131                    " DefaultContainerService");
1132            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1133            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1134            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1135                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1136                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1137                mBound = true;
1138                return true;
1139            }
1140            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1141            return false;
1142        }
1143
1144        private void disconnectService() {
1145            mContainerService = null;
1146            mBound = false;
1147            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1148            mContext.unbindService(mDefContainerConn);
1149            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1150        }
1151
1152        PackageHandler(Looper looper) {
1153            super(looper);
1154        }
1155
1156        public void handleMessage(Message msg) {
1157            try {
1158                doHandleMessage(msg);
1159            } finally {
1160                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1161            }
1162        }
1163
1164        void doHandleMessage(Message msg) {
1165            switch (msg.what) {
1166                case INIT_COPY: {
1167                    HandlerParams params = (HandlerParams) msg.obj;
1168                    int idx = mPendingInstalls.size();
1169                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1170                    // If a bind was already initiated we dont really
1171                    // need to do anything. The pending install
1172                    // will be processed later on.
1173                    if (!mBound) {
1174                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1175                                System.identityHashCode(mHandler));
1176                        // If this is the only one pending we might
1177                        // have to bind to the service again.
1178                        if (!connectToService()) {
1179                            Slog.e(TAG, "Failed to bind to media container service");
1180                            params.serviceError();
1181                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1182                                    System.identityHashCode(mHandler));
1183                            if (params.traceMethod != null) {
1184                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1185                                        params.traceCookie);
1186                            }
1187                            return;
1188                        } else {
1189                            // Once we bind to the service, the first
1190                            // pending request will be processed.
1191                            mPendingInstalls.add(idx, params);
1192                        }
1193                    } else {
1194                        mPendingInstalls.add(idx, params);
1195                        // Already bound to the service. Just make
1196                        // sure we trigger off processing the first request.
1197                        if (idx == 0) {
1198                            mHandler.sendEmptyMessage(MCS_BOUND);
1199                        }
1200                    }
1201                    break;
1202                }
1203                case MCS_BOUND: {
1204                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1205                    if (msg.obj != null) {
1206                        mContainerService = (IMediaContainerService) msg.obj;
1207                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1208                                System.identityHashCode(mHandler));
1209                    }
1210                    if (mContainerService == null) {
1211                        if (!mBound) {
1212                            // Something seriously wrong since we are not bound and we are not
1213                            // waiting for connection. Bail out.
1214                            Slog.e(TAG, "Cannot bind to media container service");
1215                            for (HandlerParams params : mPendingInstalls) {
1216                                // Indicate service bind error
1217                                params.serviceError();
1218                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1219                                        System.identityHashCode(params));
1220                                if (params.traceMethod != null) {
1221                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1222                                            params.traceMethod, params.traceCookie);
1223                                }
1224                                return;
1225                            }
1226                            mPendingInstalls.clear();
1227                        } else {
1228                            Slog.w(TAG, "Waiting to connect to media container service");
1229                        }
1230                    } else if (mPendingInstalls.size() > 0) {
1231                        HandlerParams params = mPendingInstalls.get(0);
1232                        if (params != null) {
1233                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1234                                    System.identityHashCode(params));
1235                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1236                            if (params.startCopy()) {
1237                                // We are done...  look for more work or to
1238                                // go idle.
1239                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1240                                        "Checking for more work or unbind...");
1241                                // Delete pending install
1242                                if (mPendingInstalls.size() > 0) {
1243                                    mPendingInstalls.remove(0);
1244                                }
1245                                if (mPendingInstalls.size() == 0) {
1246                                    if (mBound) {
1247                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1248                                                "Posting delayed MCS_UNBIND");
1249                                        removeMessages(MCS_UNBIND);
1250                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1251                                        // Unbind after a little delay, to avoid
1252                                        // continual thrashing.
1253                                        sendMessageDelayed(ubmsg, 10000);
1254                                    }
1255                                } else {
1256                                    // There are more pending requests in queue.
1257                                    // Just post MCS_BOUND message to trigger processing
1258                                    // of next pending install.
1259                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1260                                            "Posting MCS_BOUND for next work");
1261                                    mHandler.sendEmptyMessage(MCS_BOUND);
1262                                }
1263                            }
1264                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1265                        }
1266                    } else {
1267                        // Should never happen ideally.
1268                        Slog.w(TAG, "Empty queue");
1269                    }
1270                    break;
1271                }
1272                case MCS_RECONNECT: {
1273                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1274                    if (mPendingInstalls.size() > 0) {
1275                        if (mBound) {
1276                            disconnectService();
1277                        }
1278                        if (!connectToService()) {
1279                            Slog.e(TAG, "Failed to bind to media container service");
1280                            for (HandlerParams params : mPendingInstalls) {
1281                                // Indicate service bind error
1282                                params.serviceError();
1283                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1284                                        System.identityHashCode(params));
1285                            }
1286                            mPendingInstalls.clear();
1287                        }
1288                    }
1289                    break;
1290                }
1291                case MCS_UNBIND: {
1292                    // If there is no actual work left, then time to unbind.
1293                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1294
1295                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1296                        if (mBound) {
1297                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1298
1299                            disconnectService();
1300                        }
1301                    } else if (mPendingInstalls.size() > 0) {
1302                        // There are more pending requests in queue.
1303                        // Just post MCS_BOUND message to trigger processing
1304                        // of next pending install.
1305                        mHandler.sendEmptyMessage(MCS_BOUND);
1306                    }
1307
1308                    break;
1309                }
1310                case MCS_GIVE_UP: {
1311                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1312                    HandlerParams params = mPendingInstalls.remove(0);
1313                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1314                            System.identityHashCode(params));
1315                    break;
1316                }
1317                case SEND_PENDING_BROADCAST: {
1318                    String packages[];
1319                    ArrayList<String> components[];
1320                    int size = 0;
1321                    int uids[];
1322                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1323                    synchronized (mPackages) {
1324                        if (mPendingBroadcasts == null) {
1325                            return;
1326                        }
1327                        size = mPendingBroadcasts.size();
1328                        if (size <= 0) {
1329                            // Nothing to be done. Just return
1330                            return;
1331                        }
1332                        packages = new String[size];
1333                        components = new ArrayList[size];
1334                        uids = new int[size];
1335                        int i = 0;  // filling out the above arrays
1336
1337                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1338                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1339                            Iterator<Map.Entry<String, ArrayList<String>>> it
1340                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1341                                            .entrySet().iterator();
1342                            while (it.hasNext() && i < size) {
1343                                Map.Entry<String, ArrayList<String>> ent = it.next();
1344                                packages[i] = ent.getKey();
1345                                components[i] = ent.getValue();
1346                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1347                                uids[i] = (ps != null)
1348                                        ? UserHandle.getUid(packageUserId, ps.appId)
1349                                        : -1;
1350                                i++;
1351                            }
1352                        }
1353                        size = i;
1354                        mPendingBroadcasts.clear();
1355                    }
1356                    // Send broadcasts
1357                    for (int i = 0; i < size; i++) {
1358                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1359                    }
1360                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1361                    break;
1362                }
1363                case START_CLEANING_PACKAGE: {
1364                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1365                    final String packageName = (String)msg.obj;
1366                    final int userId = msg.arg1;
1367                    final boolean andCode = msg.arg2 != 0;
1368                    synchronized (mPackages) {
1369                        if (userId == UserHandle.USER_ALL) {
1370                            int[] users = sUserManager.getUserIds();
1371                            for (int user : users) {
1372                                mSettings.addPackageToCleanLPw(
1373                                        new PackageCleanItem(user, packageName, andCode));
1374                            }
1375                        } else {
1376                            mSettings.addPackageToCleanLPw(
1377                                    new PackageCleanItem(userId, packageName, andCode));
1378                        }
1379                    }
1380                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1381                    startCleaningPackages();
1382                } break;
1383                case POST_INSTALL: {
1384                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1385
1386                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1387                    mRunningInstalls.delete(msg.arg1);
1388                    boolean deleteOld = false;
1389
1390                    if (data != null) {
1391                        InstallArgs args = data.args;
1392                        PackageInstalledInfo res = data.res;
1393
1394                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1395                            final String packageName = res.pkg.applicationInfo.packageName;
1396                            res.removedInfo.sendBroadcast(false, true, false);
1397                            Bundle extras = new Bundle(1);
1398                            extras.putInt(Intent.EXTRA_UID, res.uid);
1399
1400                            // Now that we successfully installed the package, grant runtime
1401                            // permissions if requested before broadcasting the install.
1402                            if ((args.installFlags
1403                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1404                                    && res.pkg.applicationInfo.targetSdkVersion
1405                                            >= Build.VERSION_CODES.M) {
1406                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1407                                        args.installGrantPermissions);
1408                            }
1409
1410                            synchronized (mPackages) {
1411                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1412                            }
1413
1414                            // Determine the set of users who are adding this
1415                            // package for the first time vs. those who are seeing
1416                            // an update.
1417                            int[] firstUsers;
1418                            int[] updateUsers = new int[0];
1419                            if (res.origUsers == null || res.origUsers.length == 0) {
1420                                firstUsers = res.newUsers;
1421                            } else {
1422                                firstUsers = new int[0];
1423                                for (int i=0; i<res.newUsers.length; i++) {
1424                                    int user = res.newUsers[i];
1425                                    boolean isNew = true;
1426                                    for (int j=0; j<res.origUsers.length; j++) {
1427                                        if (res.origUsers[j] == user) {
1428                                            isNew = false;
1429                                            break;
1430                                        }
1431                                    }
1432                                    if (isNew) {
1433                                        int[] newFirst = new int[firstUsers.length+1];
1434                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1435                                                firstUsers.length);
1436                                        newFirst[firstUsers.length] = user;
1437                                        firstUsers = newFirst;
1438                                    } else {
1439                                        int[] newUpdate = new int[updateUsers.length+1];
1440                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1441                                                updateUsers.length);
1442                                        newUpdate[updateUsers.length] = user;
1443                                        updateUsers = newUpdate;
1444                                    }
1445                                }
1446                            }
1447                            // don't broadcast for ephemeral installs/updates
1448                            final boolean isEphemeral = isEphemeral(res.pkg);
1449                            if (!isEphemeral) {
1450                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1451                                        extras, 0 /*flags*/, null /*targetPackage*/,
1452                                        null /*finishedReceiver*/, firstUsers);
1453                            }
1454                            final boolean update = res.removedInfo.removedPackage != null;
1455                            if (update) {
1456                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1457                            }
1458                            if (!isEphemeral) {
1459                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1460                                        extras, 0 /*flags*/, null /*targetPackage*/,
1461                                        null /*finishedReceiver*/, updateUsers);
1462                            }
1463                            if (update) {
1464                                if (!isEphemeral) {
1465                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1466                                            packageName, extras, 0 /*flags*/,
1467                                            null /*targetPackage*/, null /*finishedReceiver*/,
1468                                            updateUsers);
1469                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1470                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1471                                            packageName /*targetPackage*/,
1472                                            null /*finishedReceiver*/, updateUsers);
1473                                }
1474
1475                                // treat asec-hosted packages like removable media on upgrade
1476                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1477                                    if (DEBUG_INSTALL) {
1478                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1479                                                + " is ASEC-hosted -> AVAILABLE");
1480                                    }
1481                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1482                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1483                                    pkgList.add(packageName);
1484                                    sendResourcesChangedBroadcast(true, true,
1485                                            pkgList,uidArray, null);
1486                                }
1487                            }
1488                            if (res.removedInfo.args != null) {
1489                                // Remove the replaced package's older resources safely now
1490                                deleteOld = true;
1491                            }
1492
1493                            // If this app is a browser and it's newly-installed for some
1494                            // users, clear any default-browser state in those users
1495                            if (firstUsers.length > 0) {
1496                                // the app's nature doesn't depend on the user, so we can just
1497                                // check its browser nature in any user and generalize.
1498                                if (packageIsBrowser(packageName, firstUsers[0])) {
1499                                    synchronized (mPackages) {
1500                                        for (int userId : firstUsers) {
1501                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1502                                        }
1503                                    }
1504                                }
1505                            }
1506                            // Log current value of "unknown sources" setting
1507                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1508                                getUnknownSourcesSettings());
1509                        }
1510                        // Force a gc to clear up things
1511                        Runtime.getRuntime().gc();
1512                        // We delete after a gc for applications  on sdcard.
1513                        if (deleteOld) {
1514                            synchronized (mInstallLock) {
1515                                res.removedInfo.args.doPostDeleteLI(true);
1516                            }
1517                        }
1518                        if (args.observer != null) {
1519                            try {
1520                                Bundle extras = extrasForInstallResult(res);
1521                                args.observer.onPackageInstalled(res.name, res.returnCode,
1522                                        res.returnMsg, extras);
1523                            } catch (RemoteException e) {
1524                                Slog.i(TAG, "Observer no longer exists.");
1525                            }
1526                        }
1527                        if (args.traceMethod != null) {
1528                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1529                                    args.traceCookie);
1530                        }
1531                        return;
1532                    } else {
1533                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1534                    }
1535
1536                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1537                } break;
1538                case UPDATED_MEDIA_STATUS: {
1539                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1540                    boolean reportStatus = msg.arg1 == 1;
1541                    boolean doGc = msg.arg2 == 1;
1542                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1543                    if (doGc) {
1544                        // Force a gc to clear up stale containers.
1545                        Runtime.getRuntime().gc();
1546                    }
1547                    if (msg.obj != null) {
1548                        @SuppressWarnings("unchecked")
1549                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1550                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1551                        // Unload containers
1552                        unloadAllContainers(args);
1553                    }
1554                    if (reportStatus) {
1555                        try {
1556                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1557                            PackageHelper.getMountService().finishMediaUpdate();
1558                        } catch (RemoteException e) {
1559                            Log.e(TAG, "MountService not running?");
1560                        }
1561                    }
1562                } break;
1563                case WRITE_SETTINGS: {
1564                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1565                    synchronized (mPackages) {
1566                        removeMessages(WRITE_SETTINGS);
1567                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1568                        mSettings.writeLPr();
1569                        mDirtyUsers.clear();
1570                    }
1571                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1572                } break;
1573                case WRITE_PACKAGE_RESTRICTIONS: {
1574                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1575                    synchronized (mPackages) {
1576                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1577                        for (int userId : mDirtyUsers) {
1578                            mSettings.writePackageRestrictionsLPr(userId);
1579                        }
1580                        mDirtyUsers.clear();
1581                    }
1582                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1583                } break;
1584                case CHECK_PENDING_VERIFICATION: {
1585                    final int verificationId = msg.arg1;
1586                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1587
1588                    if ((state != null) && !state.timeoutExtended()) {
1589                        final InstallArgs args = state.getInstallArgs();
1590                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1591
1592                        Slog.i(TAG, "Verification timed out for " + originUri);
1593                        mPendingVerification.remove(verificationId);
1594
1595                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1596
1597                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1598                            Slog.i(TAG, "Continuing with installation of " + originUri);
1599                            state.setVerifierResponse(Binder.getCallingUid(),
1600                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1601                            broadcastPackageVerified(verificationId, originUri,
1602                                    PackageManager.VERIFICATION_ALLOW,
1603                                    state.getInstallArgs().getUser());
1604                            try {
1605                                ret = args.copyApk(mContainerService, true);
1606                            } catch (RemoteException e) {
1607                                Slog.e(TAG, "Could not contact the ContainerService");
1608                            }
1609                        } else {
1610                            broadcastPackageVerified(verificationId, originUri,
1611                                    PackageManager.VERIFICATION_REJECT,
1612                                    state.getInstallArgs().getUser());
1613                        }
1614
1615                        Trace.asyncTraceEnd(
1616                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1617
1618                        processPendingInstall(args, ret);
1619                        mHandler.sendEmptyMessage(MCS_UNBIND);
1620                    }
1621                    break;
1622                }
1623                case PACKAGE_VERIFIED: {
1624                    final int verificationId = msg.arg1;
1625
1626                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1627                    if (state == null) {
1628                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1629                        break;
1630                    }
1631
1632                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1633
1634                    state.setVerifierResponse(response.callerUid, response.code);
1635
1636                    if (state.isVerificationComplete()) {
1637                        mPendingVerification.remove(verificationId);
1638
1639                        final InstallArgs args = state.getInstallArgs();
1640                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1641
1642                        int ret;
1643                        if (state.isInstallAllowed()) {
1644                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1645                            broadcastPackageVerified(verificationId, originUri,
1646                                    response.code, state.getInstallArgs().getUser());
1647                            try {
1648                                ret = args.copyApk(mContainerService, true);
1649                            } catch (RemoteException e) {
1650                                Slog.e(TAG, "Could not contact the ContainerService");
1651                            }
1652                        } else {
1653                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1654                        }
1655
1656                        Trace.asyncTraceEnd(
1657                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1658
1659                        processPendingInstall(args, ret);
1660                        mHandler.sendEmptyMessage(MCS_UNBIND);
1661                    }
1662
1663                    break;
1664                }
1665                case START_INTENT_FILTER_VERIFICATIONS: {
1666                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1667                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1668                            params.replacing, params.pkg);
1669                    break;
1670                }
1671                case INTENT_FILTER_VERIFIED: {
1672                    final int verificationId = msg.arg1;
1673
1674                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1675                            verificationId);
1676                    if (state == null) {
1677                        Slog.w(TAG, "Invalid IntentFilter verification token "
1678                                + verificationId + " received");
1679                        break;
1680                    }
1681
1682                    final int userId = state.getUserId();
1683
1684                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1685                            "Processing IntentFilter verification with token:"
1686                            + verificationId + " and userId:" + userId);
1687
1688                    final IntentFilterVerificationResponse response =
1689                            (IntentFilterVerificationResponse) msg.obj;
1690
1691                    state.setVerifierResponse(response.callerUid, response.code);
1692
1693                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1694                            "IntentFilter verification with token:" + verificationId
1695                            + " and userId:" + userId
1696                            + " is settings verifier response with response code:"
1697                            + response.code);
1698
1699                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1700                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1701                                + response.getFailedDomainsString());
1702                    }
1703
1704                    if (state.isVerificationComplete()) {
1705                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1706                    } else {
1707                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1708                                "IntentFilter verification with token:" + verificationId
1709                                + " was not said to be complete");
1710                    }
1711
1712                    break;
1713                }
1714            }
1715        }
1716    }
1717
1718    private StorageEventListener mStorageListener = new StorageEventListener() {
1719        @Override
1720        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1721            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1722                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1723                    final String volumeUuid = vol.getFsUuid();
1724
1725                    // Clean up any users or apps that were removed or recreated
1726                    // while this volume was missing
1727                    reconcileUsers(volumeUuid);
1728                    reconcileApps(volumeUuid);
1729
1730                    // Clean up any install sessions that expired or were
1731                    // cancelled while this volume was missing
1732                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1733
1734                    loadPrivatePackages(vol);
1735
1736                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1737                    unloadPrivatePackages(vol);
1738                }
1739            }
1740
1741            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1742                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1743                    updateExternalMediaStatus(true, false);
1744                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1745                    updateExternalMediaStatus(false, false);
1746                }
1747            }
1748        }
1749
1750        @Override
1751        public void onVolumeForgotten(String fsUuid) {
1752            if (TextUtils.isEmpty(fsUuid)) {
1753                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1754                return;
1755            }
1756
1757            // Remove any apps installed on the forgotten volume
1758            synchronized (mPackages) {
1759                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1760                for (PackageSetting ps : packages) {
1761                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1762                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1763                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1764                }
1765
1766                mSettings.onVolumeForgotten(fsUuid);
1767                mSettings.writeLPr();
1768            }
1769        }
1770    };
1771
1772    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1773            String[] grantedPermissions) {
1774        if (userId >= UserHandle.USER_SYSTEM) {
1775            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1776        } else if (userId == UserHandle.USER_ALL) {
1777            final int[] userIds;
1778            synchronized (mPackages) {
1779                userIds = UserManagerService.getInstance().getUserIds();
1780            }
1781            for (int someUserId : userIds) {
1782                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1783            }
1784        }
1785
1786        // We could have touched GID membership, so flush out packages.list
1787        synchronized (mPackages) {
1788            mSettings.writePackageListLPr();
1789        }
1790    }
1791
1792    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1793            String[] grantedPermissions) {
1794        SettingBase sb = (SettingBase) pkg.mExtras;
1795        if (sb == null) {
1796            return;
1797        }
1798
1799        PermissionsState permissionsState = sb.getPermissionsState();
1800
1801        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1802                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1803
1804        synchronized (mPackages) {
1805            for (String permission : pkg.requestedPermissions) {
1806                BasePermission bp = mSettings.mPermissions.get(permission);
1807                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1808                        && (grantedPermissions == null
1809                               || ArrayUtils.contains(grantedPermissions, permission))) {
1810                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1811                    // Installer cannot change immutable permissions.
1812                    if ((flags & immutableFlags) == 0) {
1813                        grantRuntimePermission(pkg.packageName, permission, userId);
1814                    }
1815                }
1816            }
1817        }
1818    }
1819
1820    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1821        Bundle extras = null;
1822        switch (res.returnCode) {
1823            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1824                extras = new Bundle();
1825                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1826                        res.origPermission);
1827                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1828                        res.origPackage);
1829                break;
1830            }
1831            case PackageManager.INSTALL_SUCCEEDED: {
1832                extras = new Bundle();
1833                extras.putBoolean(Intent.EXTRA_REPLACING,
1834                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1835                break;
1836            }
1837        }
1838        return extras;
1839    }
1840
1841    void scheduleWriteSettingsLocked() {
1842        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1843            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1844        }
1845    }
1846
1847    void scheduleWritePackageRestrictionsLocked(int userId) {
1848        if (!sUserManager.exists(userId)) return;
1849        mDirtyUsers.add(userId);
1850        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1851            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1852        }
1853    }
1854
1855    public static PackageManagerService main(Context context, Installer installer,
1856            boolean factoryTest, boolean onlyCore) {
1857        PackageManagerService m = new PackageManagerService(context, installer,
1858                factoryTest, onlyCore);
1859        m.enableSystemUserPackages();
1860        ServiceManager.addService("package", m);
1861        return m;
1862    }
1863
1864    private void enableSystemUserPackages() {
1865        if (!UserManager.isSplitSystemUser()) {
1866            return;
1867        }
1868        // For system user, enable apps based on the following conditions:
1869        // - app is whitelisted or belong to one of these groups:
1870        //   -- system app which has no launcher icons
1871        //   -- system app which has INTERACT_ACROSS_USERS permission
1872        //   -- system IME app
1873        // - app is not in the blacklist
1874        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1875        Set<String> enableApps = new ArraySet<>();
1876        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1877                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1878                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1879        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1880        enableApps.addAll(wlApps);
1881        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1882                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1883        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1884        enableApps.removeAll(blApps);
1885        Log.i(TAG, "Applications installed for system user: " + enableApps);
1886        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1887                UserHandle.SYSTEM);
1888        final int allAppsSize = allAps.size();
1889        synchronized (mPackages) {
1890            for (int i = 0; i < allAppsSize; i++) {
1891                String pName = allAps.get(i);
1892                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1893                // Should not happen, but we shouldn't be failing if it does
1894                if (pkgSetting == null) {
1895                    continue;
1896                }
1897                boolean install = enableApps.contains(pName);
1898                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1899                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1900                            + " for system user");
1901                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1902                }
1903            }
1904        }
1905    }
1906
1907    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1908        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1909                Context.DISPLAY_SERVICE);
1910        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1911    }
1912
1913    public PackageManagerService(Context context, Installer installer,
1914            boolean factoryTest, boolean onlyCore) {
1915        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1916                SystemClock.uptimeMillis());
1917
1918        if (mSdkVersion <= 0) {
1919            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1920        }
1921
1922        mContext = context;
1923        mFactoryTest = factoryTest;
1924        mOnlyCore = onlyCore;
1925        mMetrics = new DisplayMetrics();
1926        mSettings = new Settings(mPackages);
1927        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1928                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1929        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1930                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1931        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1932                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1933        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1934                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1935        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1936                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1937        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1938                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1939
1940        String separateProcesses = SystemProperties.get("debug.separate_processes");
1941        if (separateProcesses != null && separateProcesses.length() > 0) {
1942            if ("*".equals(separateProcesses)) {
1943                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1944                mSeparateProcesses = null;
1945                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1946            } else {
1947                mDefParseFlags = 0;
1948                mSeparateProcesses = separateProcesses.split(",");
1949                Slog.w(TAG, "Running with debug.separate_processes: "
1950                        + separateProcesses);
1951            }
1952        } else {
1953            mDefParseFlags = 0;
1954            mSeparateProcesses = null;
1955        }
1956
1957        mInstaller = installer;
1958        mPackageDexOptimizer = new PackageDexOptimizer(this);
1959        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1960
1961        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1962                FgThread.get().getLooper());
1963
1964        getDefaultDisplayMetrics(context, mMetrics);
1965
1966        SystemConfig systemConfig = SystemConfig.getInstance();
1967        mGlobalGids = systemConfig.getGlobalGids();
1968        mSystemPermissions = systemConfig.getSystemPermissions();
1969        mAvailableFeatures = systemConfig.getAvailableFeatures();
1970
1971        synchronized (mInstallLock) {
1972        // writer
1973        synchronized (mPackages) {
1974            mHandlerThread = new ServiceThread(TAG,
1975                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1976            mHandlerThread.start();
1977            mHandler = new PackageHandler(mHandlerThread.getLooper());
1978            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1979
1980            File dataDir = Environment.getDataDirectory();
1981            mAppInstallDir = new File(dataDir, "app");
1982            mAppLib32InstallDir = new File(dataDir, "app-lib");
1983            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1984            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1985            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1986
1987            sUserManager = new UserManagerService(context, this, mPackages);
1988
1989            // Propagate permission configuration in to package manager.
1990            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1991                    = systemConfig.getPermissions();
1992            for (int i=0; i<permConfig.size(); i++) {
1993                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1994                BasePermission bp = mSettings.mPermissions.get(perm.name);
1995                if (bp == null) {
1996                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1997                    mSettings.mPermissions.put(perm.name, bp);
1998                }
1999                if (perm.gids != null) {
2000                    bp.setGids(perm.gids, perm.perUser);
2001                }
2002            }
2003
2004            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2005            for (int i=0; i<libConfig.size(); i++) {
2006                mSharedLibraries.put(libConfig.keyAt(i),
2007                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2008            }
2009
2010            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2011
2012            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2013
2014            String customResolverActivity = Resources.getSystem().getString(
2015                    R.string.config_customResolverActivity);
2016            if (TextUtils.isEmpty(customResolverActivity)) {
2017                customResolverActivity = null;
2018            } else {
2019                mCustomResolverComponentName = ComponentName.unflattenFromString(
2020                        customResolverActivity);
2021            }
2022
2023            long startTime = SystemClock.uptimeMillis();
2024
2025            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2026                    startTime);
2027
2028            // Set flag to monitor and not change apk file paths when
2029            // scanning install directories.
2030            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2031
2032            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2033            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2034
2035            if (bootClassPath == null) {
2036                Slog.w(TAG, "No BOOTCLASSPATH found!");
2037            }
2038
2039            if (systemServerClassPath == null) {
2040                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2041            }
2042
2043            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2044            final String[] dexCodeInstructionSets =
2045                    getDexCodeInstructionSets(
2046                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2047
2048            /**
2049             * Ensure all external libraries have had dexopt run on them.
2050             */
2051            if (mSharedLibraries.size() > 0) {
2052                // NOTE: For now, we're compiling these system "shared libraries"
2053                // (and framework jars) into all available architectures. It's possible
2054                // to compile them only when we come across an app that uses them (there's
2055                // already logic for that in scanPackageLI) but that adds some complexity.
2056                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2057                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2058                        final String lib = libEntry.path;
2059                        if (lib == null) {
2060                            continue;
2061                        }
2062
2063                        try {
2064                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2065                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2066                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2067                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2068                            }
2069                        } catch (FileNotFoundException e) {
2070                            Slog.w(TAG, "Library not found: " + lib);
2071                        } catch (IOException | InstallerException e) {
2072                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2073                                    + e.getMessage());
2074                        }
2075                    }
2076                }
2077            }
2078
2079            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2080
2081            final VersionInfo ver = mSettings.getInternalVersion();
2082            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2083            // when upgrading from pre-M, promote system app permissions from install to runtime
2084            mPromoteSystemApps =
2085                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2086
2087            // save off the names of pre-existing system packages prior to scanning; we don't
2088            // want to automatically grant runtime permissions for new system apps
2089            if (mPromoteSystemApps) {
2090                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2091                while (pkgSettingIter.hasNext()) {
2092                    PackageSetting ps = pkgSettingIter.next();
2093                    if (isSystemApp(ps)) {
2094                        mExistingSystemPackages.add(ps.name);
2095                    }
2096                }
2097            }
2098
2099            // Collect vendor overlay packages.
2100            // (Do this before scanning any apps.)
2101            // For security and version matching reason, only consider
2102            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2103            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2104            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2105                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2106
2107            // Find base frameworks (resource packages without code).
2108            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2109                    | PackageParser.PARSE_IS_SYSTEM_DIR
2110                    | PackageParser.PARSE_IS_PRIVILEGED,
2111                    scanFlags | SCAN_NO_DEX, 0);
2112
2113            // Collected privileged system packages.
2114            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2115            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2116                    | PackageParser.PARSE_IS_SYSTEM_DIR
2117                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2118
2119            // Collect ordinary system packages.
2120            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2121            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2122                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2123
2124            // Collect all vendor packages.
2125            File vendorAppDir = new File("/vendor/app");
2126            try {
2127                vendorAppDir = vendorAppDir.getCanonicalFile();
2128            } catch (IOException e) {
2129                // failed to look up canonical path, continue with original one
2130            }
2131            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2132                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2133
2134            // Collect all OEM packages.
2135            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2136            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2137                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2138
2139            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2140            try {
2141                mInstaller.moveFiles();
2142            } catch (InstallerException e) {
2143                logCriticalInfo(Log.WARN, "Update commands failed: " + e);
2144            }
2145
2146            // Prune any system packages that no longer exist.
2147            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2148            if (!mOnlyCore) {
2149                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2150                while (psit.hasNext()) {
2151                    PackageSetting ps = psit.next();
2152
2153                    /*
2154                     * If this is not a system app, it can't be a
2155                     * disable system app.
2156                     */
2157                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2158                        continue;
2159                    }
2160
2161                    /*
2162                     * If the package is scanned, it's not erased.
2163                     */
2164                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2165                    if (scannedPkg != null) {
2166                        /*
2167                         * If the system app is both scanned and in the
2168                         * disabled packages list, then it must have been
2169                         * added via OTA. Remove it from the currently
2170                         * scanned package so the previously user-installed
2171                         * application can be scanned.
2172                         */
2173                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2174                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2175                                    + ps.name + "; removing system app.  Last known codePath="
2176                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2177                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2178                                    + scannedPkg.mVersionCode);
2179                            removePackageLI(ps, true);
2180                            mExpectingBetter.put(ps.name, ps.codePath);
2181                        }
2182
2183                        continue;
2184                    }
2185
2186                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2187                        psit.remove();
2188                        logCriticalInfo(Log.WARN, "System package " + ps.name
2189                                + " no longer exists; wiping its data");
2190                        removeDataDirsLI(null, ps.name);
2191                    } else {
2192                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2193                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2194                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2195                        }
2196                    }
2197                }
2198            }
2199
2200            //look for any incomplete package installations
2201            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2202            //clean up list
2203            for(int i = 0; i < deletePkgsList.size(); i++) {
2204                //clean up here
2205                cleanupInstallFailedPackage(deletePkgsList.get(i));
2206            }
2207            //delete tmp files
2208            deleteTempPackageFiles();
2209
2210            // Remove any shared userIDs that have no associated packages
2211            mSettings.pruneSharedUsersLPw();
2212
2213            if (!mOnlyCore) {
2214                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2215                        SystemClock.uptimeMillis());
2216                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2217
2218                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2219                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2220
2221                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2222                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2223
2224                /**
2225                 * Remove disable package settings for any updated system
2226                 * apps that were removed via an OTA. If they're not a
2227                 * previously-updated app, remove them completely.
2228                 * Otherwise, just revoke their system-level permissions.
2229                 */
2230                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2231                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2232                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2233
2234                    String msg;
2235                    if (deletedPkg == null) {
2236                        msg = "Updated system package " + deletedAppName
2237                                + " no longer exists; wiping its data";
2238                        removeDataDirsLI(null, deletedAppName);
2239                    } else {
2240                        msg = "Updated system app + " + deletedAppName
2241                                + " no longer present; removing system privileges for "
2242                                + deletedAppName;
2243
2244                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2245
2246                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2247                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2248                    }
2249                    logCriticalInfo(Log.WARN, msg);
2250                }
2251
2252                /**
2253                 * Make sure all system apps that we expected to appear on
2254                 * the userdata partition actually showed up. If they never
2255                 * appeared, crawl back and revive the system version.
2256                 */
2257                for (int i = 0; i < mExpectingBetter.size(); i++) {
2258                    final String packageName = mExpectingBetter.keyAt(i);
2259                    if (!mPackages.containsKey(packageName)) {
2260                        final File scanFile = mExpectingBetter.valueAt(i);
2261
2262                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2263                                + " but never showed up; reverting to system");
2264
2265                        final int reparseFlags;
2266                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2267                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2268                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2269                                    | PackageParser.PARSE_IS_PRIVILEGED;
2270                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2271                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2272                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2273                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2274                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2275                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2276                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2277                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2278                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2279                        } else {
2280                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2281                            continue;
2282                        }
2283
2284                        mSettings.enableSystemPackageLPw(packageName);
2285
2286                        try {
2287                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2288                        } catch (PackageManagerException e) {
2289                            Slog.e(TAG, "Failed to parse original system package: "
2290                                    + e.getMessage());
2291                        }
2292                    }
2293                }
2294            }
2295            mExpectingBetter.clear();
2296
2297            // Now that we know all of the shared libraries, update all clients to have
2298            // the correct library paths.
2299            updateAllSharedLibrariesLPw();
2300
2301            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2302                // NOTE: We ignore potential failures here during a system scan (like
2303                // the rest of the commands above) because there's precious little we
2304                // can do about it. A settings error is reported, though.
2305                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2306                        false /* boot complete */);
2307            }
2308
2309            // Now that we know all the packages we are keeping,
2310            // read and update their last usage times.
2311            mPackageUsage.readLP();
2312
2313            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2314                    SystemClock.uptimeMillis());
2315            Slog.i(TAG, "Time to scan packages: "
2316                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2317                    + " seconds");
2318
2319            // If the platform SDK has changed since the last time we booted,
2320            // we need to re-grant app permission to catch any new ones that
2321            // appear.  This is really a hack, and means that apps can in some
2322            // cases get permissions that the user didn't initially explicitly
2323            // allow...  it would be nice to have some better way to handle
2324            // this situation.
2325            int updateFlags = UPDATE_PERMISSIONS_ALL;
2326            if (ver.sdkVersion != mSdkVersion) {
2327                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2328                        + mSdkVersion + "; regranting permissions for internal storage");
2329                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2330            }
2331            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2332            ver.sdkVersion = mSdkVersion;
2333
2334            // If this is the first boot or an update from pre-M, and it is a normal
2335            // boot, then we need to initialize the default preferred apps across
2336            // all defined users.
2337            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2338                for (UserInfo user : sUserManager.getUsers(true)) {
2339                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2340                    applyFactoryDefaultBrowserLPw(user.id);
2341                    primeDomainVerificationsLPw(user.id);
2342                }
2343            }
2344
2345            // If this is first boot after an OTA, and a normal boot, then
2346            // we need to clear code cache directories.
2347            if (mIsUpgrade && !onlyCore) {
2348                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2349                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2350                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2351                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2352                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2353                    }
2354                }
2355                ver.fingerprint = Build.FINGERPRINT;
2356            }
2357
2358            checkDefaultBrowser();
2359
2360            // clear only after permissions and other defaults have been updated
2361            mExistingSystemPackages.clear();
2362            mPromoteSystemApps = false;
2363
2364            // All the changes are done during package scanning.
2365            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2366
2367            // can downgrade to reader
2368            mSettings.writeLPr();
2369
2370            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2371                    SystemClock.uptimeMillis());
2372
2373            if (!mOnlyCore) {
2374                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2375                mRequiredInstallerPackage = getRequiredInstallerLPr();
2376                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2377                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2378                        mIntentFilterVerifierComponent);
2379            } else {
2380                mRequiredVerifierPackage = null;
2381                mRequiredInstallerPackage = null;
2382                mIntentFilterVerifierComponent = null;
2383                mIntentFilterVerifier = null;
2384            }
2385
2386            mInstallerService = new PackageInstallerService(context, this);
2387
2388            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2389            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2390            // both the installer and resolver must be present to enable ephemeral
2391            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2392                if (DEBUG_EPHEMERAL) {
2393                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2394                            + " installer:" + ephemeralInstallerComponent);
2395                }
2396                mEphemeralResolverComponent = ephemeralResolverComponent;
2397                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2398                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2399                mEphemeralResolverConnection =
2400                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2401            } else {
2402                if (DEBUG_EPHEMERAL) {
2403                    final String missingComponent =
2404                            (ephemeralResolverComponent == null)
2405                            ? (ephemeralInstallerComponent == null)
2406                                    ? "resolver and installer"
2407                                    : "resolver"
2408                            : "installer";
2409                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2410                }
2411                mEphemeralResolverComponent = null;
2412                mEphemeralInstallerComponent = null;
2413                mEphemeralResolverConnection = null;
2414            }
2415
2416            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2417        } // synchronized (mPackages)
2418        } // synchronized (mInstallLock)
2419
2420        // Now after opening every single application zip, make sure they
2421        // are all flushed.  Not really needed, but keeps things nice and
2422        // tidy.
2423        Runtime.getRuntime().gc();
2424
2425        // The initial scanning above does many calls into installd while
2426        // holding the mPackages lock, but we're mostly interested in yelling
2427        // once we have a booted system.
2428        mInstaller.setWarnIfHeld(mPackages);
2429
2430        // Expose private service for system components to use.
2431        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2432    }
2433
2434    @Override
2435    public boolean isFirstBoot() {
2436        return !mRestoredSettings;
2437    }
2438
2439    @Override
2440    public boolean isOnlyCoreApps() {
2441        return mOnlyCore;
2442    }
2443
2444    @Override
2445    public boolean isUpgrade() {
2446        return mIsUpgrade;
2447    }
2448
2449    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2450        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2451
2452        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2453                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2454        if (matches.size() == 1) {
2455            return matches.get(0).getComponentInfo().packageName;
2456        } else {
2457            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2458            return null;
2459        }
2460    }
2461
2462    private @NonNull String getRequiredInstallerLPr() {
2463        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2464        intent.addCategory(Intent.CATEGORY_DEFAULT);
2465        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2466
2467        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2468                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2469        if (matches.size() == 1) {
2470            return matches.get(0).getComponentInfo().packageName;
2471        } else {
2472            throw new RuntimeException("There must be exactly one installer; found " + matches);
2473        }
2474    }
2475
2476    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2477        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2478
2479        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2480                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2481        ResolveInfo best = null;
2482        final int N = matches.size();
2483        for (int i = 0; i < N; i++) {
2484            final ResolveInfo cur = matches.get(i);
2485            final String packageName = cur.getComponentInfo().packageName;
2486            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2487                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2488                continue;
2489            }
2490
2491            if (best == null || cur.priority > best.priority) {
2492                best = cur;
2493            }
2494        }
2495
2496        if (best != null) {
2497            return best.getComponentInfo().getComponentName();
2498        } else {
2499            throw new RuntimeException("There must be at least one intent filter verifier");
2500        }
2501    }
2502
2503    private @Nullable ComponentName getEphemeralResolverLPr() {
2504        final String[] packageArray =
2505                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2506        if (packageArray.length == 0) {
2507            if (DEBUG_EPHEMERAL) {
2508                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2509            }
2510            return null;
2511        }
2512
2513        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2514        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2515                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2516
2517        final int N = resolvers.size();
2518        if (N == 0) {
2519            if (DEBUG_EPHEMERAL) {
2520                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2521            }
2522            return null;
2523        }
2524
2525        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2526        for (int i = 0; i < N; i++) {
2527            final ResolveInfo info = resolvers.get(i);
2528
2529            if (info.serviceInfo == null) {
2530                continue;
2531            }
2532
2533            final String packageName = info.serviceInfo.packageName;
2534            if (!possiblePackages.contains(packageName)) {
2535                if (DEBUG_EPHEMERAL) {
2536                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2537                            + " pkg: " + packageName + ", info:" + info);
2538                }
2539                continue;
2540            }
2541
2542            if (DEBUG_EPHEMERAL) {
2543                Slog.v(TAG, "Ephemeral resolver found;"
2544                        + " pkg: " + packageName + ", info:" + info);
2545            }
2546            return new ComponentName(packageName, info.serviceInfo.name);
2547        }
2548        if (DEBUG_EPHEMERAL) {
2549            Slog.v(TAG, "Ephemeral resolver NOT found");
2550        }
2551        return null;
2552    }
2553
2554    private @Nullable ComponentName getEphemeralInstallerLPr() {
2555        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2556        intent.addCategory(Intent.CATEGORY_DEFAULT);
2557        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2558
2559        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2560                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2561        if (matches.size() == 0) {
2562            return null;
2563        } else if (matches.size() == 1) {
2564            return matches.get(0).getComponentInfo().getComponentName();
2565        } else {
2566            throw new RuntimeException(
2567                    "There must be at most one ephemeral installer; found " + matches);
2568        }
2569    }
2570
2571    private void primeDomainVerificationsLPw(int userId) {
2572        if (DEBUG_DOMAIN_VERIFICATION) {
2573            Slog.d(TAG, "Priming domain verifications in user " + userId);
2574        }
2575
2576        SystemConfig systemConfig = SystemConfig.getInstance();
2577        ArraySet<String> packages = systemConfig.getLinkedApps();
2578        ArraySet<String> domains = new ArraySet<String>();
2579
2580        for (String packageName : packages) {
2581            PackageParser.Package pkg = mPackages.get(packageName);
2582            if (pkg != null) {
2583                if (!pkg.isSystemApp()) {
2584                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2585                    continue;
2586                }
2587
2588                domains.clear();
2589                for (PackageParser.Activity a : pkg.activities) {
2590                    for (ActivityIntentInfo filter : a.intents) {
2591                        if (hasValidDomains(filter)) {
2592                            domains.addAll(filter.getHostsList());
2593                        }
2594                    }
2595                }
2596
2597                if (domains.size() > 0) {
2598                    if (DEBUG_DOMAIN_VERIFICATION) {
2599                        Slog.v(TAG, "      + " + packageName);
2600                    }
2601                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2602                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2603                    // and then 'always' in the per-user state actually used for intent resolution.
2604                    final IntentFilterVerificationInfo ivi;
2605                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2606                            new ArrayList<String>(domains));
2607                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2608                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2609                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2610                } else {
2611                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2612                            + "' does not handle web links");
2613                }
2614            } else {
2615                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2616            }
2617        }
2618
2619        scheduleWritePackageRestrictionsLocked(userId);
2620        scheduleWriteSettingsLocked();
2621    }
2622
2623    private void applyFactoryDefaultBrowserLPw(int userId) {
2624        // The default browser app's package name is stored in a string resource,
2625        // with a product-specific overlay used for vendor customization.
2626        String browserPkg = mContext.getResources().getString(
2627                com.android.internal.R.string.default_browser);
2628        if (!TextUtils.isEmpty(browserPkg)) {
2629            // non-empty string => required to be a known package
2630            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2631            if (ps == null) {
2632                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2633                browserPkg = null;
2634            } else {
2635                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2636            }
2637        }
2638
2639        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2640        // default.  If there's more than one, just leave everything alone.
2641        if (browserPkg == null) {
2642            calculateDefaultBrowserLPw(userId);
2643        }
2644    }
2645
2646    private void calculateDefaultBrowserLPw(int userId) {
2647        List<String> allBrowsers = resolveAllBrowserApps(userId);
2648        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2649        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2650    }
2651
2652    private List<String> resolveAllBrowserApps(int userId) {
2653        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2654        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2655                PackageManager.MATCH_ALL, userId);
2656
2657        final int count = list.size();
2658        List<String> result = new ArrayList<String>(count);
2659        for (int i=0; i<count; i++) {
2660            ResolveInfo info = list.get(i);
2661            if (info.activityInfo == null
2662                    || !info.handleAllWebDataURI
2663                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2664                    || result.contains(info.activityInfo.packageName)) {
2665                continue;
2666            }
2667            result.add(info.activityInfo.packageName);
2668        }
2669
2670        return result;
2671    }
2672
2673    private boolean packageIsBrowser(String packageName, int userId) {
2674        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2675                PackageManager.MATCH_ALL, userId);
2676        final int N = list.size();
2677        for (int i = 0; i < N; i++) {
2678            ResolveInfo info = list.get(i);
2679            if (packageName.equals(info.activityInfo.packageName)) {
2680                return true;
2681            }
2682        }
2683        return false;
2684    }
2685
2686    private void checkDefaultBrowser() {
2687        final int myUserId = UserHandle.myUserId();
2688        final String packageName = getDefaultBrowserPackageName(myUserId);
2689        if (packageName != null) {
2690            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2691            if (info == null) {
2692                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2693                synchronized (mPackages) {
2694                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2695                }
2696            }
2697        }
2698    }
2699
2700    @Override
2701    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2702            throws RemoteException {
2703        try {
2704            return super.onTransact(code, data, reply, flags);
2705        } catch (RuntimeException e) {
2706            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2707                Slog.wtf(TAG, "Package Manager Crash", e);
2708            }
2709            throw e;
2710        }
2711    }
2712
2713    void cleanupInstallFailedPackage(PackageSetting ps) {
2714        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2715
2716        removeDataDirsLI(ps.volumeUuid, ps.name);
2717        if (ps.codePath != null) {
2718            removeCodePathLI(ps.codePath);
2719        }
2720        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2721            if (ps.resourcePath.isDirectory()) {
2722                FileUtils.deleteContents(ps.resourcePath);
2723            }
2724            ps.resourcePath.delete();
2725        }
2726        mSettings.removePackageLPw(ps.name);
2727    }
2728
2729    static int[] appendInts(int[] cur, int[] add) {
2730        if (add == null) return cur;
2731        if (cur == null) return add;
2732        final int N = add.length;
2733        for (int i=0; i<N; i++) {
2734            cur = appendInt(cur, add[i]);
2735        }
2736        return cur;
2737    }
2738
2739    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2740        if (!sUserManager.exists(userId)) return null;
2741        final PackageSetting ps = (PackageSetting) p.mExtras;
2742        if (ps == null) {
2743            return null;
2744        }
2745
2746        final PermissionsState permissionsState = ps.getPermissionsState();
2747
2748        final int[] gids = permissionsState.computeGids(userId);
2749        final Set<String> permissions = permissionsState.getPermissions(userId);
2750        final PackageUserState state = ps.readUserState(userId);
2751
2752        return PackageParser.generatePackageInfo(p, gids, flags,
2753                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2754    }
2755
2756    @Override
2757    public void checkPackageStartable(String packageName, int userId) {
2758        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2759
2760        synchronized (mPackages) {
2761            final PackageSetting ps = mSettings.mPackages.get(packageName);
2762            if (ps == null) {
2763                throw new SecurityException("Package " + packageName + " was not found!");
2764            }
2765
2766            if (ps.frozen) {
2767                throw new SecurityException("Package " + packageName + " is currently frozen!");
2768            }
2769
2770            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2771                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2772                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2773            }
2774        }
2775    }
2776
2777    @Override
2778    public boolean isPackageAvailable(String packageName, int userId) {
2779        if (!sUserManager.exists(userId)) return false;
2780        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2781        synchronized (mPackages) {
2782            PackageParser.Package p = mPackages.get(packageName);
2783            if (p != null) {
2784                final PackageSetting ps = (PackageSetting) p.mExtras;
2785                if (ps != null) {
2786                    final PackageUserState state = ps.readUserState(userId);
2787                    if (state != null) {
2788                        return PackageParser.isAvailable(state);
2789                    }
2790                }
2791            }
2792        }
2793        return false;
2794    }
2795
2796    @Override
2797    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2798        if (!sUserManager.exists(userId)) return null;
2799        flags = updateFlagsForPackage(flags, userId, packageName);
2800        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2801        // reader
2802        synchronized (mPackages) {
2803            PackageParser.Package p = mPackages.get(packageName);
2804            if (DEBUG_PACKAGE_INFO)
2805                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2806            if (p != null) {
2807                return generatePackageInfo(p, flags, userId);
2808            }
2809            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2810                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2811            }
2812        }
2813        return null;
2814    }
2815
2816    @Override
2817    public String[] currentToCanonicalPackageNames(String[] names) {
2818        String[] out = new String[names.length];
2819        // reader
2820        synchronized (mPackages) {
2821            for (int i=names.length-1; i>=0; i--) {
2822                PackageSetting ps = mSettings.mPackages.get(names[i]);
2823                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2824            }
2825        }
2826        return out;
2827    }
2828
2829    @Override
2830    public String[] canonicalToCurrentPackageNames(String[] names) {
2831        String[] out = new String[names.length];
2832        // reader
2833        synchronized (mPackages) {
2834            for (int i=names.length-1; i>=0; i--) {
2835                String cur = mSettings.mRenamedPackages.get(names[i]);
2836                out[i] = cur != null ? cur : names[i];
2837            }
2838        }
2839        return out;
2840    }
2841
2842    @Override
2843    public int getPackageUid(String packageName, int flags, int userId) {
2844        if (!sUserManager.exists(userId)) return -1;
2845        flags = updateFlagsForPackage(flags, userId, packageName);
2846        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2847
2848        // reader
2849        synchronized (mPackages) {
2850            final PackageParser.Package p = mPackages.get(packageName);
2851            if (p != null && p.isMatch(flags)) {
2852                return UserHandle.getUid(userId, p.applicationInfo.uid);
2853            }
2854            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2855                final PackageSetting ps = mSettings.mPackages.get(packageName);
2856                if (ps != null && ps.isMatch(flags)) {
2857                    return UserHandle.getUid(userId, ps.appId);
2858                }
2859            }
2860        }
2861
2862        return -1;
2863    }
2864
2865    @Override
2866    public int[] getPackageGids(String packageName, int flags, int userId) {
2867        if (!sUserManager.exists(userId)) return null;
2868        flags = updateFlagsForPackage(flags, userId, packageName);
2869        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2870                "getPackageGids");
2871
2872        // reader
2873        synchronized (mPackages) {
2874            final PackageParser.Package p = mPackages.get(packageName);
2875            if (p != null && p.isMatch(flags)) {
2876                PackageSetting ps = (PackageSetting) p.mExtras;
2877                return ps.getPermissionsState().computeGids(userId);
2878            }
2879            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2880                final PackageSetting ps = mSettings.mPackages.get(packageName);
2881                if (ps != null && ps.isMatch(flags)) {
2882                    return ps.getPermissionsState().computeGids(userId);
2883                }
2884            }
2885        }
2886
2887        return null;
2888    }
2889
2890    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2891        if (bp.perm != null) {
2892            return PackageParser.generatePermissionInfo(bp.perm, flags);
2893        }
2894        PermissionInfo pi = new PermissionInfo();
2895        pi.name = bp.name;
2896        pi.packageName = bp.sourcePackage;
2897        pi.nonLocalizedLabel = bp.name;
2898        pi.protectionLevel = bp.protectionLevel;
2899        return pi;
2900    }
2901
2902    @Override
2903    public PermissionInfo getPermissionInfo(String name, int flags) {
2904        // reader
2905        synchronized (mPackages) {
2906            final BasePermission p = mSettings.mPermissions.get(name);
2907            if (p != null) {
2908                return generatePermissionInfo(p, flags);
2909            }
2910            return null;
2911        }
2912    }
2913
2914    @Override
2915    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2916        // reader
2917        synchronized (mPackages) {
2918            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2919            for (BasePermission p : mSettings.mPermissions.values()) {
2920                if (group == null) {
2921                    if (p.perm == null || p.perm.info.group == null) {
2922                        out.add(generatePermissionInfo(p, flags));
2923                    }
2924                } else {
2925                    if (p.perm != null && group.equals(p.perm.info.group)) {
2926                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2927                    }
2928                }
2929            }
2930
2931            if (out.size() > 0) {
2932                return out;
2933            }
2934            return mPermissionGroups.containsKey(group) ? out : null;
2935        }
2936    }
2937
2938    @Override
2939    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2940        // reader
2941        synchronized (mPackages) {
2942            return PackageParser.generatePermissionGroupInfo(
2943                    mPermissionGroups.get(name), flags);
2944        }
2945    }
2946
2947    @Override
2948    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2949        // reader
2950        synchronized (mPackages) {
2951            final int N = mPermissionGroups.size();
2952            ArrayList<PermissionGroupInfo> out
2953                    = new ArrayList<PermissionGroupInfo>(N);
2954            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2955                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2956            }
2957            return out;
2958        }
2959    }
2960
2961    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2962            int userId) {
2963        if (!sUserManager.exists(userId)) return null;
2964        PackageSetting ps = mSettings.mPackages.get(packageName);
2965        if (ps != null) {
2966            if (ps.pkg == null) {
2967                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2968                        flags, userId);
2969                if (pInfo != null) {
2970                    return pInfo.applicationInfo;
2971                }
2972                return null;
2973            }
2974            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2975                    ps.readUserState(userId), userId);
2976        }
2977        return null;
2978    }
2979
2980    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2981            int userId) {
2982        if (!sUserManager.exists(userId)) return null;
2983        PackageSetting ps = mSettings.mPackages.get(packageName);
2984        if (ps != null) {
2985            PackageParser.Package pkg = ps.pkg;
2986            if (pkg == null) {
2987                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
2988                    return null;
2989                }
2990                // Only data remains, so we aren't worried about code paths
2991                pkg = new PackageParser.Package(packageName);
2992                pkg.applicationInfo.packageName = packageName;
2993                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2994                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2995                pkg.applicationInfo.uid = ps.appId;
2996                pkg.applicationInfo.initForUser(userId);
2997                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2998                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2999            }
3000            return generatePackageInfo(pkg, flags, userId);
3001        }
3002        return null;
3003    }
3004
3005    @Override
3006    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3007        if (!sUserManager.exists(userId)) return null;
3008        flags = updateFlagsForApplication(flags, userId, packageName);
3009        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3010        // writer
3011        synchronized (mPackages) {
3012            PackageParser.Package p = mPackages.get(packageName);
3013            if (DEBUG_PACKAGE_INFO) Log.v(
3014                    TAG, "getApplicationInfo " + packageName
3015                    + ": " + p);
3016            if (p != null) {
3017                PackageSetting ps = mSettings.mPackages.get(packageName);
3018                if (ps == null) return null;
3019                // Note: isEnabledLP() does not apply here - always return info
3020                return PackageParser.generateApplicationInfo(
3021                        p, flags, ps.readUserState(userId), userId);
3022            }
3023            if ("android".equals(packageName)||"system".equals(packageName)) {
3024                return mAndroidApplication;
3025            }
3026            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3027                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3028            }
3029        }
3030        return null;
3031    }
3032
3033    @Override
3034    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3035            final IPackageDataObserver observer) {
3036        mContext.enforceCallingOrSelfPermission(
3037                android.Manifest.permission.CLEAR_APP_CACHE, null);
3038        // Queue up an async operation since clearing cache may take a little while.
3039        mHandler.post(new Runnable() {
3040            public void run() {
3041                mHandler.removeCallbacks(this);
3042                boolean success = true;
3043                synchronized (mInstallLock) {
3044                    try {
3045                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3046                    } catch (InstallerException e) {
3047                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3048                        success = false;
3049                    }
3050                }
3051                if (observer != null) {
3052                    try {
3053                        observer.onRemoveCompleted(null, success);
3054                    } catch (RemoteException e) {
3055                        Slog.w(TAG, "RemoveException when invoking call back");
3056                    }
3057                }
3058            }
3059        });
3060    }
3061
3062    @Override
3063    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3064            final IntentSender pi) {
3065        mContext.enforceCallingOrSelfPermission(
3066                android.Manifest.permission.CLEAR_APP_CACHE, null);
3067        // Queue up an async operation since clearing cache may take a little while.
3068        mHandler.post(new Runnable() {
3069            public void run() {
3070                mHandler.removeCallbacks(this);
3071                boolean success = true;
3072                synchronized (mInstallLock) {
3073                    try {
3074                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3075                    } catch (InstallerException e) {
3076                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3077                        success = false;
3078                    }
3079                }
3080                if(pi != null) {
3081                    try {
3082                        // Callback via pending intent
3083                        int code = success ? 1 : 0;
3084                        pi.sendIntent(null, code, null,
3085                                null, null);
3086                    } catch (SendIntentException e1) {
3087                        Slog.i(TAG, "Failed to send pending intent");
3088                    }
3089                }
3090            }
3091        });
3092    }
3093
3094    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3095        synchronized (mInstallLock) {
3096            try {
3097                mInstaller.freeCache(volumeUuid, freeStorageSize);
3098            } catch (InstallerException e) {
3099                throw new IOException("Failed to free enough space", e);
3100            }
3101        }
3102    }
3103
3104    /**
3105     * Return if the user key is currently unlocked.
3106     */
3107    private boolean isUserKeyUnlocked(int userId) {
3108        if (StorageManager.isFileBasedEncryptionEnabled()) {
3109            final IMountService mount = IMountService.Stub
3110                    .asInterface(ServiceManager.getService("mount"));
3111            if (mount == null) {
3112                Slog.w(TAG, "Early during boot, assuming locked");
3113                return false;
3114            }
3115            final long token = Binder.clearCallingIdentity();
3116            try {
3117                return mount.isUserKeyUnlocked(userId);
3118            } catch (RemoteException e) {
3119                throw e.rethrowAsRuntimeException();
3120            } finally {
3121                Binder.restoreCallingIdentity(token);
3122            }
3123        } else {
3124            return true;
3125        }
3126    }
3127
3128    /**
3129     * Update given flags based on encryption status of current user.
3130     */
3131    private int updateFlags(int flags, int userId) {
3132        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3133                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3134            // Caller expressed an explicit opinion about what encryption
3135            // aware/unaware components they want to see, so fall through and
3136            // give them what they want
3137        } else {
3138            // Caller expressed no opinion, so match based on user state
3139            if (isUserKeyUnlocked(userId)) {
3140                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3141            } else {
3142                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3143            }
3144        }
3145
3146        // Safe mode means we should ignore any third-party apps
3147        if (mSafeMode) {
3148            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3149        }
3150
3151        return flags;
3152    }
3153
3154    /**
3155     * Update given flags when being used to request {@link PackageInfo}.
3156     */
3157    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3158        boolean triaged = true;
3159        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3160                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3161            // Caller is asking for component details, so they'd better be
3162            // asking for specific encryption matching behavior, or be triaged
3163            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3164                    | PackageManager.MATCH_ENCRYPTION_AWARE
3165                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3166                triaged = false;
3167            }
3168        }
3169        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3170                | PackageManager.MATCH_SYSTEM_ONLY
3171                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3172            triaged = false;
3173        }
3174        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3175            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3176                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3177        }
3178        return updateFlags(flags, userId);
3179    }
3180
3181    /**
3182     * Update given flags when being used to request {@link ApplicationInfo}.
3183     */
3184    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3185        return updateFlagsForPackage(flags, userId, cookie);
3186    }
3187
3188    /**
3189     * Update given flags when being used to request {@link ComponentInfo}.
3190     */
3191    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3192        if (cookie instanceof Intent) {
3193            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3194                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3195            }
3196        }
3197
3198        boolean triaged = true;
3199        // Caller is asking for component details, so they'd better be
3200        // asking for specific encryption matching behavior, or be triaged
3201        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3202                | PackageManager.MATCH_ENCRYPTION_AWARE
3203                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3204            triaged = false;
3205        }
3206        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3207            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3208                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3209        }
3210        return updateFlags(flags, userId);
3211    }
3212
3213    /**
3214     * Update given flags when being used to request {@link ResolveInfo}.
3215     */
3216    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3217        return updateFlagsForComponent(flags, userId, cookie);
3218    }
3219
3220    @Override
3221    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3222        if (!sUserManager.exists(userId)) return null;
3223        flags = updateFlagsForComponent(flags, userId, component);
3224        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3225        synchronized (mPackages) {
3226            PackageParser.Activity a = mActivities.mActivities.get(component);
3227
3228            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3229            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3230                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3231                if (ps == null) return null;
3232                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3233                        userId);
3234            }
3235            if (mResolveComponentName.equals(component)) {
3236                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3237                        new PackageUserState(), userId);
3238            }
3239        }
3240        return null;
3241    }
3242
3243    @Override
3244    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3245            String resolvedType) {
3246        synchronized (mPackages) {
3247            if (component.equals(mResolveComponentName)) {
3248                // The resolver supports EVERYTHING!
3249                return true;
3250            }
3251            PackageParser.Activity a = mActivities.mActivities.get(component);
3252            if (a == null) {
3253                return false;
3254            }
3255            for (int i=0; i<a.intents.size(); i++) {
3256                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3257                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3258                    return true;
3259                }
3260            }
3261            return false;
3262        }
3263    }
3264
3265    @Override
3266    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3267        if (!sUserManager.exists(userId)) return null;
3268        flags = updateFlagsForComponent(flags, userId, component);
3269        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3270        synchronized (mPackages) {
3271            PackageParser.Activity a = mReceivers.mActivities.get(component);
3272            if (DEBUG_PACKAGE_INFO) Log.v(
3273                TAG, "getReceiverInfo " + component + ": " + a);
3274            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3275                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3276                if (ps == null) return null;
3277                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3278                        userId);
3279            }
3280        }
3281        return null;
3282    }
3283
3284    @Override
3285    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3286        if (!sUserManager.exists(userId)) return null;
3287        flags = updateFlagsForComponent(flags, userId, component);
3288        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3289        synchronized (mPackages) {
3290            PackageParser.Service s = mServices.mServices.get(component);
3291            if (DEBUG_PACKAGE_INFO) Log.v(
3292                TAG, "getServiceInfo " + component + ": " + s);
3293            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3294                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3295                if (ps == null) return null;
3296                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3297                        userId);
3298            }
3299        }
3300        return null;
3301    }
3302
3303    @Override
3304    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3305        if (!sUserManager.exists(userId)) return null;
3306        flags = updateFlagsForComponent(flags, userId, component);
3307        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3308        synchronized (mPackages) {
3309            PackageParser.Provider p = mProviders.mProviders.get(component);
3310            if (DEBUG_PACKAGE_INFO) Log.v(
3311                TAG, "getProviderInfo " + component + ": " + p);
3312            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3313                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3314                if (ps == null) return null;
3315                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3316                        userId);
3317            }
3318        }
3319        return null;
3320    }
3321
3322    @Override
3323    public String[] getSystemSharedLibraryNames() {
3324        Set<String> libSet;
3325        synchronized (mPackages) {
3326            libSet = mSharedLibraries.keySet();
3327            int size = libSet.size();
3328            if (size > 0) {
3329                String[] libs = new String[size];
3330                libSet.toArray(libs);
3331                return libs;
3332            }
3333        }
3334        return null;
3335    }
3336
3337    /**
3338     * @hide
3339     */
3340    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3341        synchronized (mPackages) {
3342            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3343            if (lib != null && lib.apk != null) {
3344                return mPackages.get(lib.apk);
3345            }
3346        }
3347        return null;
3348    }
3349
3350    @Override
3351    public FeatureInfo[] getSystemAvailableFeatures() {
3352        Collection<FeatureInfo> featSet;
3353        synchronized (mPackages) {
3354            featSet = mAvailableFeatures.values();
3355            int size = featSet.size();
3356            if (size > 0) {
3357                FeatureInfo[] features = new FeatureInfo[size+1];
3358                featSet.toArray(features);
3359                FeatureInfo fi = new FeatureInfo();
3360                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3361                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3362                features[size] = fi;
3363                return features;
3364            }
3365        }
3366        return null;
3367    }
3368
3369    @Override
3370    public boolean hasSystemFeature(String name) {
3371        synchronized (mPackages) {
3372            return mAvailableFeatures.containsKey(name);
3373        }
3374    }
3375
3376    @Override
3377    public int checkPermission(String permName, String pkgName, int userId) {
3378        if (!sUserManager.exists(userId)) {
3379            return PackageManager.PERMISSION_DENIED;
3380        }
3381
3382        synchronized (mPackages) {
3383            final PackageParser.Package p = mPackages.get(pkgName);
3384            if (p != null && p.mExtras != null) {
3385                final PackageSetting ps = (PackageSetting) p.mExtras;
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            }
3396        }
3397
3398        return PackageManager.PERMISSION_DENIED;
3399    }
3400
3401    @Override
3402    public int checkUidPermission(String permName, int uid) {
3403        final int userId = UserHandle.getUserId(uid);
3404
3405        if (!sUserManager.exists(userId)) {
3406            return PackageManager.PERMISSION_DENIED;
3407        }
3408
3409        synchronized (mPackages) {
3410            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3411            if (obj != null) {
3412                final SettingBase ps = (SettingBase) obj;
3413                final PermissionsState permissionsState = ps.getPermissionsState();
3414                if (permissionsState.hasPermission(permName, userId)) {
3415                    return PackageManager.PERMISSION_GRANTED;
3416                }
3417                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3418                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3419                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3420                    return PackageManager.PERMISSION_GRANTED;
3421                }
3422            } else {
3423                ArraySet<String> perms = mSystemPermissions.get(uid);
3424                if (perms != null) {
3425                    if (perms.contains(permName)) {
3426                        return PackageManager.PERMISSION_GRANTED;
3427                    }
3428                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3429                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3430                        return PackageManager.PERMISSION_GRANTED;
3431                    }
3432                }
3433            }
3434        }
3435
3436        return PackageManager.PERMISSION_DENIED;
3437    }
3438
3439    @Override
3440    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3441        if (UserHandle.getCallingUserId() != userId) {
3442            mContext.enforceCallingPermission(
3443                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3444                    "isPermissionRevokedByPolicy for user " + userId);
3445        }
3446
3447        if (checkPermission(permission, packageName, userId)
3448                == PackageManager.PERMISSION_GRANTED) {
3449            return false;
3450        }
3451
3452        final long identity = Binder.clearCallingIdentity();
3453        try {
3454            final int flags = getPermissionFlags(permission, packageName, userId);
3455            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3456        } finally {
3457            Binder.restoreCallingIdentity(identity);
3458        }
3459    }
3460
3461    @Override
3462    public String getPermissionControllerPackageName() {
3463        synchronized (mPackages) {
3464            return mRequiredInstallerPackage;
3465        }
3466    }
3467
3468    /**
3469     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3470     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3471     * @param checkShell TODO(yamasani):
3472     * @param message the message to log on security exception
3473     */
3474    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3475            boolean checkShell, String message) {
3476        if (userId < 0) {
3477            throw new IllegalArgumentException("Invalid userId " + userId);
3478        }
3479        if (checkShell) {
3480            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3481        }
3482        if (userId == UserHandle.getUserId(callingUid)) return;
3483        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3484            if (requireFullPermission) {
3485                mContext.enforceCallingOrSelfPermission(
3486                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3487            } else {
3488                try {
3489                    mContext.enforceCallingOrSelfPermission(
3490                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3491                } catch (SecurityException se) {
3492                    mContext.enforceCallingOrSelfPermission(
3493                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3494                }
3495            }
3496        }
3497    }
3498
3499    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3500        if (callingUid == Process.SHELL_UID) {
3501            if (userHandle >= 0
3502                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3503                throw new SecurityException("Shell does not have permission to access user "
3504                        + userHandle);
3505            } else if (userHandle < 0) {
3506                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3507                        + Debug.getCallers(3));
3508            }
3509        }
3510    }
3511
3512    private BasePermission findPermissionTreeLP(String permName) {
3513        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3514            if (permName.startsWith(bp.name) &&
3515                    permName.length() > bp.name.length() &&
3516                    permName.charAt(bp.name.length()) == '.') {
3517                return bp;
3518            }
3519        }
3520        return null;
3521    }
3522
3523    private BasePermission checkPermissionTreeLP(String permName) {
3524        if (permName != null) {
3525            BasePermission bp = findPermissionTreeLP(permName);
3526            if (bp != null) {
3527                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3528                    return bp;
3529                }
3530                throw new SecurityException("Calling uid "
3531                        + Binder.getCallingUid()
3532                        + " is not allowed to add to permission tree "
3533                        + bp.name + " owned by uid " + bp.uid);
3534            }
3535        }
3536        throw new SecurityException("No permission tree found for " + permName);
3537    }
3538
3539    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3540        if (s1 == null) {
3541            return s2 == null;
3542        }
3543        if (s2 == null) {
3544            return false;
3545        }
3546        if (s1.getClass() != s2.getClass()) {
3547            return false;
3548        }
3549        return s1.equals(s2);
3550    }
3551
3552    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3553        if (pi1.icon != pi2.icon) return false;
3554        if (pi1.logo != pi2.logo) return false;
3555        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3556        if (!compareStrings(pi1.name, pi2.name)) return false;
3557        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3558        // We'll take care of setting this one.
3559        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3560        // These are not currently stored in settings.
3561        //if (!compareStrings(pi1.group, pi2.group)) return false;
3562        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3563        //if (pi1.labelRes != pi2.labelRes) return false;
3564        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3565        return true;
3566    }
3567
3568    int permissionInfoFootprint(PermissionInfo info) {
3569        int size = info.name.length();
3570        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3571        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3572        return size;
3573    }
3574
3575    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3576        int size = 0;
3577        for (BasePermission perm : mSettings.mPermissions.values()) {
3578            if (perm.uid == tree.uid) {
3579                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3580            }
3581        }
3582        return size;
3583    }
3584
3585    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3586        // We calculate the max size of permissions defined by this uid and throw
3587        // if that plus the size of 'info' would exceed our stated maximum.
3588        if (tree.uid != Process.SYSTEM_UID) {
3589            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3590            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3591                throw new SecurityException("Permission tree size cap exceeded");
3592            }
3593        }
3594    }
3595
3596    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3597        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3598            throw new SecurityException("Label must be specified in permission");
3599        }
3600        BasePermission tree = checkPermissionTreeLP(info.name);
3601        BasePermission bp = mSettings.mPermissions.get(info.name);
3602        boolean added = bp == null;
3603        boolean changed = true;
3604        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3605        if (added) {
3606            enforcePermissionCapLocked(info, tree);
3607            bp = new BasePermission(info.name, tree.sourcePackage,
3608                    BasePermission.TYPE_DYNAMIC);
3609        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3610            throw new SecurityException(
3611                    "Not allowed to modify non-dynamic permission "
3612                    + info.name);
3613        } else {
3614            if (bp.protectionLevel == fixedLevel
3615                    && bp.perm.owner.equals(tree.perm.owner)
3616                    && bp.uid == tree.uid
3617                    && comparePermissionInfos(bp.perm.info, info)) {
3618                changed = false;
3619            }
3620        }
3621        bp.protectionLevel = fixedLevel;
3622        info = new PermissionInfo(info);
3623        info.protectionLevel = fixedLevel;
3624        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3625        bp.perm.info.packageName = tree.perm.info.packageName;
3626        bp.uid = tree.uid;
3627        if (added) {
3628            mSettings.mPermissions.put(info.name, bp);
3629        }
3630        if (changed) {
3631            if (!async) {
3632                mSettings.writeLPr();
3633            } else {
3634                scheduleWriteSettingsLocked();
3635            }
3636        }
3637        return added;
3638    }
3639
3640    @Override
3641    public boolean addPermission(PermissionInfo info) {
3642        synchronized (mPackages) {
3643            return addPermissionLocked(info, false);
3644        }
3645    }
3646
3647    @Override
3648    public boolean addPermissionAsync(PermissionInfo info) {
3649        synchronized (mPackages) {
3650            return addPermissionLocked(info, true);
3651        }
3652    }
3653
3654    @Override
3655    public void removePermission(String name) {
3656        synchronized (mPackages) {
3657            checkPermissionTreeLP(name);
3658            BasePermission bp = mSettings.mPermissions.get(name);
3659            if (bp != null) {
3660                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3661                    throw new SecurityException(
3662                            "Not allowed to modify non-dynamic permission "
3663                            + name);
3664                }
3665                mSettings.mPermissions.remove(name);
3666                mSettings.writeLPr();
3667            }
3668        }
3669    }
3670
3671    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3672            BasePermission bp) {
3673        int index = pkg.requestedPermissions.indexOf(bp.name);
3674        if (index == -1) {
3675            throw new SecurityException("Package " + pkg.packageName
3676                    + " has not requested permission " + bp.name);
3677        }
3678        if (!bp.isRuntime() && !bp.isDevelopment()) {
3679            throw new SecurityException("Permission " + bp.name
3680                    + " is not a changeable permission type");
3681        }
3682    }
3683
3684    @Override
3685    public void grantRuntimePermission(String packageName, String name, final int userId) {
3686        if (!sUserManager.exists(userId)) {
3687            Log.e(TAG, "No such user:" + userId);
3688            return;
3689        }
3690
3691        mContext.enforceCallingOrSelfPermission(
3692                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3693                "grantRuntimePermission");
3694
3695        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3696                "grantRuntimePermission");
3697
3698        final int uid;
3699        final SettingBase sb;
3700
3701        synchronized (mPackages) {
3702            final PackageParser.Package pkg = mPackages.get(packageName);
3703            if (pkg == null) {
3704                throw new IllegalArgumentException("Unknown package: " + packageName);
3705            }
3706
3707            final BasePermission bp = mSettings.mPermissions.get(name);
3708            if (bp == null) {
3709                throw new IllegalArgumentException("Unknown permission: " + name);
3710            }
3711
3712            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3713
3714            // If a permission review is required for legacy apps we represent
3715            // their permissions as always granted runtime ones since we need
3716            // to keep the review required permission flag per user while an
3717            // install permission's state is shared across all users.
3718            if (Build.PERMISSIONS_REVIEW_REQUIRED
3719                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3720                    && bp.isRuntime()) {
3721                return;
3722            }
3723
3724            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3725            sb = (SettingBase) pkg.mExtras;
3726            if (sb == null) {
3727                throw new IllegalArgumentException("Unknown package: " + packageName);
3728            }
3729
3730            final PermissionsState permissionsState = sb.getPermissionsState();
3731
3732            final int flags = permissionsState.getPermissionFlags(name, userId);
3733            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3734                throw new SecurityException("Cannot grant system fixed permission "
3735                        + name + " for package " + packageName);
3736            }
3737
3738            if (bp.isDevelopment()) {
3739                // Development permissions must be handled specially, since they are not
3740                // normal runtime permissions.  For now they apply to all users.
3741                if (permissionsState.grantInstallPermission(bp) !=
3742                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3743                    scheduleWriteSettingsLocked();
3744                }
3745                return;
3746            }
3747
3748            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3749                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3750                return;
3751            }
3752
3753            final int result = permissionsState.grantRuntimePermission(bp, userId);
3754            switch (result) {
3755                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3756                    return;
3757                }
3758
3759                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3760                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3761                    mHandler.post(new Runnable() {
3762                        @Override
3763                        public void run() {
3764                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3765                        }
3766                    });
3767                }
3768                break;
3769            }
3770
3771            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3772
3773            // Not critical if that is lost - app has to request again.
3774            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3775        }
3776
3777        // Only need to do this if user is initialized. Otherwise it's a new user
3778        // and there are no processes running as the user yet and there's no need
3779        // to make an expensive call to remount processes for the changed permissions.
3780        if (READ_EXTERNAL_STORAGE.equals(name)
3781                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3782            final long token = Binder.clearCallingIdentity();
3783            try {
3784                if (sUserManager.isInitialized(userId)) {
3785                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3786                            MountServiceInternal.class);
3787                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3788                }
3789            } finally {
3790                Binder.restoreCallingIdentity(token);
3791            }
3792        }
3793    }
3794
3795    @Override
3796    public void revokeRuntimePermission(String packageName, String name, int userId) {
3797        if (!sUserManager.exists(userId)) {
3798            Log.e(TAG, "No such user:" + userId);
3799            return;
3800        }
3801
3802        mContext.enforceCallingOrSelfPermission(
3803                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3804                "revokeRuntimePermission");
3805
3806        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3807                "revokeRuntimePermission");
3808
3809        final int appId;
3810
3811        synchronized (mPackages) {
3812            final PackageParser.Package pkg = mPackages.get(packageName);
3813            if (pkg == null) {
3814                throw new IllegalArgumentException("Unknown package: " + packageName);
3815            }
3816
3817            final BasePermission bp = mSettings.mPermissions.get(name);
3818            if (bp == null) {
3819                throw new IllegalArgumentException("Unknown permission: " + name);
3820            }
3821
3822            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3823
3824            // If a permission review is required for legacy apps we represent
3825            // their permissions as always granted runtime ones since we need
3826            // to keep the review required permission flag per user while an
3827            // install permission's state is shared across all users.
3828            if (Build.PERMISSIONS_REVIEW_REQUIRED
3829                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3830                    && bp.isRuntime()) {
3831                return;
3832            }
3833
3834            SettingBase sb = (SettingBase) pkg.mExtras;
3835            if (sb == null) {
3836                throw new IllegalArgumentException("Unknown package: " + packageName);
3837            }
3838
3839            final PermissionsState permissionsState = sb.getPermissionsState();
3840
3841            final int flags = permissionsState.getPermissionFlags(name, userId);
3842            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3843                throw new SecurityException("Cannot revoke system fixed permission "
3844                        + name + " for package " + packageName);
3845            }
3846
3847            if (bp.isDevelopment()) {
3848                // Development permissions must be handled specially, since they are not
3849                // normal runtime permissions.  For now they apply to all users.
3850                if (permissionsState.revokeInstallPermission(bp) !=
3851                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3852                    scheduleWriteSettingsLocked();
3853                }
3854                return;
3855            }
3856
3857            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3858                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3859                return;
3860            }
3861
3862            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3863
3864            // Critical, after this call app should never have the permission.
3865            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3866
3867            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3868        }
3869
3870        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3871    }
3872
3873    @Override
3874    public void resetRuntimePermissions() {
3875        mContext.enforceCallingOrSelfPermission(
3876                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3877                "revokeRuntimePermission");
3878
3879        int callingUid = Binder.getCallingUid();
3880        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3881            mContext.enforceCallingOrSelfPermission(
3882                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3883                    "resetRuntimePermissions");
3884        }
3885
3886        synchronized (mPackages) {
3887            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3888            for (int userId : UserManagerService.getInstance().getUserIds()) {
3889                final int packageCount = mPackages.size();
3890                for (int i = 0; i < packageCount; i++) {
3891                    PackageParser.Package pkg = mPackages.valueAt(i);
3892                    if (!(pkg.mExtras instanceof PackageSetting)) {
3893                        continue;
3894                    }
3895                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3896                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3897                }
3898            }
3899        }
3900    }
3901
3902    @Override
3903    public int getPermissionFlags(String name, String packageName, int userId) {
3904        if (!sUserManager.exists(userId)) {
3905            return 0;
3906        }
3907
3908        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3909
3910        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3911                "getPermissionFlags");
3912
3913        synchronized (mPackages) {
3914            final PackageParser.Package pkg = mPackages.get(packageName);
3915            if (pkg == null) {
3916                throw new IllegalArgumentException("Unknown package: " + packageName);
3917            }
3918
3919            final BasePermission bp = mSettings.mPermissions.get(name);
3920            if (bp == null) {
3921                throw new IllegalArgumentException("Unknown permission: " + name);
3922            }
3923
3924            SettingBase sb = (SettingBase) pkg.mExtras;
3925            if (sb == null) {
3926                throw new IllegalArgumentException("Unknown package: " + packageName);
3927            }
3928
3929            PermissionsState permissionsState = sb.getPermissionsState();
3930            return permissionsState.getPermissionFlags(name, userId);
3931        }
3932    }
3933
3934    @Override
3935    public void updatePermissionFlags(String name, String packageName, int flagMask,
3936            int flagValues, int userId) {
3937        if (!sUserManager.exists(userId)) {
3938            return;
3939        }
3940
3941        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3942
3943        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3944                "updatePermissionFlags");
3945
3946        // Only the system can change these flags and nothing else.
3947        if (getCallingUid() != Process.SYSTEM_UID) {
3948            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3949            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3950            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3951            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3952            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3953        }
3954
3955        synchronized (mPackages) {
3956            final PackageParser.Package pkg = mPackages.get(packageName);
3957            if (pkg == null) {
3958                throw new IllegalArgumentException("Unknown package: " + packageName);
3959            }
3960
3961            final BasePermission bp = mSettings.mPermissions.get(name);
3962            if (bp == null) {
3963                throw new IllegalArgumentException("Unknown permission: " + name);
3964            }
3965
3966            SettingBase sb = (SettingBase) pkg.mExtras;
3967            if (sb == null) {
3968                throw new IllegalArgumentException("Unknown package: " + packageName);
3969            }
3970
3971            PermissionsState permissionsState = sb.getPermissionsState();
3972
3973            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3974
3975            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3976                // Install and runtime permissions are stored in different places,
3977                // so figure out what permission changed and persist the change.
3978                if (permissionsState.getInstallPermissionState(name) != null) {
3979                    scheduleWriteSettingsLocked();
3980                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3981                        || hadState) {
3982                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3983                }
3984            }
3985        }
3986    }
3987
3988    /**
3989     * Update the permission flags for all packages and runtime permissions of a user in order
3990     * to allow device or profile owner to remove POLICY_FIXED.
3991     */
3992    @Override
3993    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3994        if (!sUserManager.exists(userId)) {
3995            return;
3996        }
3997
3998        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3999
4000        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4001                "updatePermissionFlagsForAllApps");
4002
4003        // Only the system can change system fixed flags.
4004        if (getCallingUid() != Process.SYSTEM_UID) {
4005            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4006            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4007        }
4008
4009        synchronized (mPackages) {
4010            boolean changed = false;
4011            final int packageCount = mPackages.size();
4012            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4013                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4014                SettingBase sb = (SettingBase) pkg.mExtras;
4015                if (sb == null) {
4016                    continue;
4017                }
4018                PermissionsState permissionsState = sb.getPermissionsState();
4019                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4020                        userId, flagMask, flagValues);
4021            }
4022            if (changed) {
4023                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4024            }
4025        }
4026    }
4027
4028    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4029        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4030                != PackageManager.PERMISSION_GRANTED
4031            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4032                != PackageManager.PERMISSION_GRANTED) {
4033            throw new SecurityException(message + " requires "
4034                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4035                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4036        }
4037    }
4038
4039    @Override
4040    public boolean shouldShowRequestPermissionRationale(String permissionName,
4041            String packageName, int userId) {
4042        if (UserHandle.getCallingUserId() != userId) {
4043            mContext.enforceCallingPermission(
4044                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4045                    "canShowRequestPermissionRationale for user " + userId);
4046        }
4047
4048        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4049        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4050            return false;
4051        }
4052
4053        if (checkPermission(permissionName, packageName, userId)
4054                == PackageManager.PERMISSION_GRANTED) {
4055            return false;
4056        }
4057
4058        final int flags;
4059
4060        final long identity = Binder.clearCallingIdentity();
4061        try {
4062            flags = getPermissionFlags(permissionName,
4063                    packageName, userId);
4064        } finally {
4065            Binder.restoreCallingIdentity(identity);
4066        }
4067
4068        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4069                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4070                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4071
4072        if ((flags & fixedFlags) != 0) {
4073            return false;
4074        }
4075
4076        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4077    }
4078
4079    @Override
4080    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4081        mContext.enforceCallingOrSelfPermission(
4082                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4083                "addOnPermissionsChangeListener");
4084
4085        synchronized (mPackages) {
4086            mOnPermissionChangeListeners.addListenerLocked(listener);
4087        }
4088    }
4089
4090    @Override
4091    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4092        synchronized (mPackages) {
4093            mOnPermissionChangeListeners.removeListenerLocked(listener);
4094        }
4095    }
4096
4097    @Override
4098    public boolean isProtectedBroadcast(String actionName) {
4099        synchronized (mPackages) {
4100            if (mProtectedBroadcasts.contains(actionName)) {
4101                return true;
4102            } else if (actionName != null) {
4103                // TODO: remove these terrible hacks
4104                if (actionName.startsWith("android.net.netmon.lingerExpired")
4105                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4106                    return true;
4107                }
4108            }
4109        }
4110        return false;
4111    }
4112
4113    @Override
4114    public int checkSignatures(String pkg1, String pkg2) {
4115        synchronized (mPackages) {
4116            final PackageParser.Package p1 = mPackages.get(pkg1);
4117            final PackageParser.Package p2 = mPackages.get(pkg2);
4118            if (p1 == null || p1.mExtras == null
4119                    || p2 == null || p2.mExtras == null) {
4120                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4121            }
4122            return compareSignatures(p1.mSignatures, p2.mSignatures);
4123        }
4124    }
4125
4126    @Override
4127    public int checkUidSignatures(int uid1, int uid2) {
4128        // Map to base uids.
4129        uid1 = UserHandle.getAppId(uid1);
4130        uid2 = UserHandle.getAppId(uid2);
4131        // reader
4132        synchronized (mPackages) {
4133            Signature[] s1;
4134            Signature[] s2;
4135            Object obj = mSettings.getUserIdLPr(uid1);
4136            if (obj != null) {
4137                if (obj instanceof SharedUserSetting) {
4138                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4139                } else if (obj instanceof PackageSetting) {
4140                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4141                } else {
4142                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4143                }
4144            } else {
4145                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4146            }
4147            obj = mSettings.getUserIdLPr(uid2);
4148            if (obj != null) {
4149                if (obj instanceof SharedUserSetting) {
4150                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4151                } else if (obj instanceof PackageSetting) {
4152                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4153                } else {
4154                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4155                }
4156            } else {
4157                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4158            }
4159            return compareSignatures(s1, s2);
4160        }
4161    }
4162
4163    private void killUid(int appId, int userId, String reason) {
4164        final long identity = Binder.clearCallingIdentity();
4165        try {
4166            IActivityManager am = ActivityManagerNative.getDefault();
4167            if (am != null) {
4168                try {
4169                    am.killUid(appId, userId, reason);
4170                } catch (RemoteException e) {
4171                    /* ignore - same process */
4172                }
4173            }
4174        } finally {
4175            Binder.restoreCallingIdentity(identity);
4176        }
4177    }
4178
4179    /**
4180     * Compares two sets of signatures. Returns:
4181     * <br />
4182     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4183     * <br />
4184     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4185     * <br />
4186     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4187     * <br />
4188     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4189     * <br />
4190     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4191     */
4192    static int compareSignatures(Signature[] s1, Signature[] s2) {
4193        if (s1 == null) {
4194            return s2 == null
4195                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4196                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4197        }
4198
4199        if (s2 == null) {
4200            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4201        }
4202
4203        if (s1.length != s2.length) {
4204            return PackageManager.SIGNATURE_NO_MATCH;
4205        }
4206
4207        // Since both signature sets are of size 1, we can compare without HashSets.
4208        if (s1.length == 1) {
4209            return s1[0].equals(s2[0]) ?
4210                    PackageManager.SIGNATURE_MATCH :
4211                    PackageManager.SIGNATURE_NO_MATCH;
4212        }
4213
4214        ArraySet<Signature> set1 = new ArraySet<Signature>();
4215        for (Signature sig : s1) {
4216            set1.add(sig);
4217        }
4218        ArraySet<Signature> set2 = new ArraySet<Signature>();
4219        for (Signature sig : s2) {
4220            set2.add(sig);
4221        }
4222        // Make sure s2 contains all signatures in s1.
4223        if (set1.equals(set2)) {
4224            return PackageManager.SIGNATURE_MATCH;
4225        }
4226        return PackageManager.SIGNATURE_NO_MATCH;
4227    }
4228
4229    /**
4230     * If the database version for this type of package (internal storage or
4231     * external storage) is less than the version where package signatures
4232     * were updated, return true.
4233     */
4234    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4235        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4236        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4237    }
4238
4239    /**
4240     * Used for backward compatibility to make sure any packages with
4241     * certificate chains get upgraded to the new style. {@code existingSigs}
4242     * will be in the old format (since they were stored on disk from before the
4243     * system upgrade) and {@code scannedSigs} will be in the newer format.
4244     */
4245    private int compareSignaturesCompat(PackageSignatures existingSigs,
4246            PackageParser.Package scannedPkg) {
4247        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4248            return PackageManager.SIGNATURE_NO_MATCH;
4249        }
4250
4251        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4252        for (Signature sig : existingSigs.mSignatures) {
4253            existingSet.add(sig);
4254        }
4255        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4256        for (Signature sig : scannedPkg.mSignatures) {
4257            try {
4258                Signature[] chainSignatures = sig.getChainSignatures();
4259                for (Signature chainSig : chainSignatures) {
4260                    scannedCompatSet.add(chainSig);
4261                }
4262            } catch (CertificateEncodingException e) {
4263                scannedCompatSet.add(sig);
4264            }
4265        }
4266        /*
4267         * Make sure the expanded scanned set contains all signatures in the
4268         * existing one.
4269         */
4270        if (scannedCompatSet.equals(existingSet)) {
4271            // Migrate the old signatures to the new scheme.
4272            existingSigs.assignSignatures(scannedPkg.mSignatures);
4273            // The new KeySets will be re-added later in the scanning process.
4274            synchronized (mPackages) {
4275                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4276            }
4277            return PackageManager.SIGNATURE_MATCH;
4278        }
4279        return PackageManager.SIGNATURE_NO_MATCH;
4280    }
4281
4282    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4283        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4284        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4285    }
4286
4287    private int compareSignaturesRecover(PackageSignatures existingSigs,
4288            PackageParser.Package scannedPkg) {
4289        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4290            return PackageManager.SIGNATURE_NO_MATCH;
4291        }
4292
4293        String msg = null;
4294        try {
4295            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4296                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4297                        + scannedPkg.packageName);
4298                return PackageManager.SIGNATURE_MATCH;
4299            }
4300        } catch (CertificateException e) {
4301            msg = e.getMessage();
4302        }
4303
4304        logCriticalInfo(Log.INFO,
4305                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4306        return PackageManager.SIGNATURE_NO_MATCH;
4307    }
4308
4309    @Override
4310    public String[] getPackagesForUid(int uid) {
4311        uid = UserHandle.getAppId(uid);
4312        // reader
4313        synchronized (mPackages) {
4314            Object obj = mSettings.getUserIdLPr(uid);
4315            if (obj instanceof SharedUserSetting) {
4316                final SharedUserSetting sus = (SharedUserSetting) obj;
4317                final int N = sus.packages.size();
4318                final String[] res = new String[N];
4319                final Iterator<PackageSetting> it = sus.packages.iterator();
4320                int i = 0;
4321                while (it.hasNext()) {
4322                    res[i++] = it.next().name;
4323                }
4324                return res;
4325            } else if (obj instanceof PackageSetting) {
4326                final PackageSetting ps = (PackageSetting) obj;
4327                return new String[] { ps.name };
4328            }
4329        }
4330        return null;
4331    }
4332
4333    @Override
4334    public String getNameForUid(int uid) {
4335        // reader
4336        synchronized (mPackages) {
4337            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4338            if (obj instanceof SharedUserSetting) {
4339                final SharedUserSetting sus = (SharedUserSetting) obj;
4340                return sus.name + ":" + sus.userId;
4341            } else if (obj instanceof PackageSetting) {
4342                final PackageSetting ps = (PackageSetting) obj;
4343                return ps.name;
4344            }
4345        }
4346        return null;
4347    }
4348
4349    @Override
4350    public int getUidForSharedUser(String sharedUserName) {
4351        if(sharedUserName == null) {
4352            return -1;
4353        }
4354        // reader
4355        synchronized (mPackages) {
4356            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4357            if (suid == null) {
4358                return -1;
4359            }
4360            return suid.userId;
4361        }
4362    }
4363
4364    @Override
4365    public int getFlagsForUid(int uid) {
4366        synchronized (mPackages) {
4367            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4368            if (obj instanceof SharedUserSetting) {
4369                final SharedUserSetting sus = (SharedUserSetting) obj;
4370                return sus.pkgFlags;
4371            } else if (obj instanceof PackageSetting) {
4372                final PackageSetting ps = (PackageSetting) obj;
4373                return ps.pkgFlags;
4374            }
4375        }
4376        return 0;
4377    }
4378
4379    @Override
4380    public int getPrivateFlagsForUid(int uid) {
4381        synchronized (mPackages) {
4382            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4383            if (obj instanceof SharedUserSetting) {
4384                final SharedUserSetting sus = (SharedUserSetting) obj;
4385                return sus.pkgPrivateFlags;
4386            } else if (obj instanceof PackageSetting) {
4387                final PackageSetting ps = (PackageSetting) obj;
4388                return ps.pkgPrivateFlags;
4389            }
4390        }
4391        return 0;
4392    }
4393
4394    @Override
4395    public boolean isUidPrivileged(int uid) {
4396        uid = UserHandle.getAppId(uid);
4397        // reader
4398        synchronized (mPackages) {
4399            Object obj = mSettings.getUserIdLPr(uid);
4400            if (obj instanceof SharedUserSetting) {
4401                final SharedUserSetting sus = (SharedUserSetting) obj;
4402                final Iterator<PackageSetting> it = sus.packages.iterator();
4403                while (it.hasNext()) {
4404                    if (it.next().isPrivileged()) {
4405                        return true;
4406                    }
4407                }
4408            } else if (obj instanceof PackageSetting) {
4409                final PackageSetting ps = (PackageSetting) obj;
4410                return ps.isPrivileged();
4411            }
4412        }
4413        return false;
4414    }
4415
4416    @Override
4417    public String[] getAppOpPermissionPackages(String permissionName) {
4418        synchronized (mPackages) {
4419            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4420            if (pkgs == null) {
4421                return null;
4422            }
4423            return pkgs.toArray(new String[pkgs.size()]);
4424        }
4425    }
4426
4427    @Override
4428    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4429            int flags, int userId) {
4430        if (!sUserManager.exists(userId)) return null;
4431        flags = updateFlagsForResolve(flags, userId, intent);
4432        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4433        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4434        final ResolveInfo bestChoice =
4435                chooseBestActivity(intent, resolvedType, flags, query, userId);
4436
4437        if (isEphemeralAllowed(intent, query, userId)) {
4438            final EphemeralResolveInfo ai =
4439                    getEphemeralResolveInfo(intent, resolvedType, userId);
4440            if (ai != null) {
4441                if (DEBUG_EPHEMERAL) {
4442                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4443                }
4444                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4445                bestChoice.ephemeralResolveInfo = ai;
4446            }
4447        }
4448        return bestChoice;
4449    }
4450
4451    @Override
4452    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4453            IntentFilter filter, int match, ComponentName activity) {
4454        final int userId = UserHandle.getCallingUserId();
4455        if (DEBUG_PREFERRED) {
4456            Log.v(TAG, "setLastChosenActivity intent=" + intent
4457                + " resolvedType=" + resolvedType
4458                + " flags=" + flags
4459                + " filter=" + filter
4460                + " match=" + match
4461                + " activity=" + activity);
4462            filter.dump(new PrintStreamPrinter(System.out), "    ");
4463        }
4464        intent.setComponent(null);
4465        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4466        // Find any earlier preferred or last chosen entries and nuke them
4467        findPreferredActivity(intent, resolvedType,
4468                flags, query, 0, false, true, false, userId);
4469        // Add the new activity as the last chosen for this filter
4470        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4471                "Setting last chosen");
4472    }
4473
4474    @Override
4475    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4476        final int userId = UserHandle.getCallingUserId();
4477        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4478        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4479        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4480                false, false, false, userId);
4481    }
4482
4483
4484    private boolean isEphemeralAllowed(
4485            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4486        // Short circuit and return early if possible.
4487        if (DISABLE_EPHEMERAL_APPS) {
4488            return false;
4489        }
4490        final int callingUser = UserHandle.getCallingUserId();
4491        if (callingUser != UserHandle.USER_SYSTEM) {
4492            return false;
4493        }
4494        if (mEphemeralResolverConnection == null) {
4495            return false;
4496        }
4497        if (intent.getComponent() != null) {
4498            return false;
4499        }
4500        if (intent.getPackage() != null) {
4501            return false;
4502        }
4503        final boolean isWebUri = hasWebURI(intent);
4504        if (!isWebUri) {
4505            return false;
4506        }
4507        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4508        synchronized (mPackages) {
4509            final int count = resolvedActivites.size();
4510            for (int n = 0; n < count; n++) {
4511                ResolveInfo info = resolvedActivites.get(n);
4512                String packageName = info.activityInfo.packageName;
4513                PackageSetting ps = mSettings.mPackages.get(packageName);
4514                if (ps != null) {
4515                    // Try to get the status from User settings first
4516                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4517                    int status = (int) (packedStatus >> 32);
4518                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4519                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4520                        if (DEBUG_EPHEMERAL) {
4521                            Slog.v(TAG, "DENY ephemeral apps;"
4522                                + " pkg: " + packageName + ", status: " + status);
4523                        }
4524                        return false;
4525                    }
4526                }
4527            }
4528        }
4529        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4530        return true;
4531    }
4532
4533    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4534            int userId) {
4535        MessageDigest digest = null;
4536        try {
4537            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4538        } catch (NoSuchAlgorithmException e) {
4539            // If we can't create a digest, ignore ephemeral apps.
4540            return null;
4541        }
4542
4543        final byte[] hostBytes = intent.getData().getHost().getBytes();
4544        final byte[] digestBytes = digest.digest(hostBytes);
4545        int shaPrefix =
4546                digestBytes[0] << 24
4547                | digestBytes[1] << 16
4548                | digestBytes[2] << 8
4549                | digestBytes[3] << 0;
4550        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4551                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4552        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4553            // No hash prefix match; there are no ephemeral apps for this domain.
4554            return null;
4555        }
4556        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4557            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4558            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4559                continue;
4560            }
4561            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4562            // No filters; this should never happen.
4563            if (filters.isEmpty()) {
4564                continue;
4565            }
4566            // We have a domain match; resolve the filters to see if anything matches.
4567            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4568            for (int j = filters.size() - 1; j >= 0; --j) {
4569                final EphemeralResolveIntentInfo intentInfo =
4570                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4571                ephemeralResolver.addFilter(intentInfo);
4572            }
4573            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4574                    intent, resolvedType, false /*defaultOnly*/, userId);
4575            if (!matchedResolveInfoList.isEmpty()) {
4576                return matchedResolveInfoList.get(0);
4577            }
4578        }
4579        // Hash or filter mis-match; no ephemeral apps for this domain.
4580        return null;
4581    }
4582
4583    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4584            int flags, List<ResolveInfo> query, int userId) {
4585        if (query != null) {
4586            final int N = query.size();
4587            if (N == 1) {
4588                return query.get(0);
4589            } else if (N > 1) {
4590                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4591                // If there is more than one activity with the same priority,
4592                // then let the user decide between them.
4593                ResolveInfo r0 = query.get(0);
4594                ResolveInfo r1 = query.get(1);
4595                if (DEBUG_INTENT_MATCHING || debug) {
4596                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4597                            + r1.activityInfo.name + "=" + r1.priority);
4598                }
4599                // If the first activity has a higher priority, or a different
4600                // default, then it is always desirable to pick it.
4601                if (r0.priority != r1.priority
4602                        || r0.preferredOrder != r1.preferredOrder
4603                        || r0.isDefault != r1.isDefault) {
4604                    return query.get(0);
4605                }
4606                // If we have saved a preference for a preferred activity for
4607                // this Intent, use that.
4608                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4609                        flags, query, r0.priority, true, false, debug, userId);
4610                if (ri != null) {
4611                    return ri;
4612                }
4613                ri = new ResolveInfo(mResolveInfo);
4614                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4615                ri.activityInfo.applicationInfo = new ApplicationInfo(
4616                        ri.activityInfo.applicationInfo);
4617                if (userId != 0) {
4618                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4619                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4620                }
4621                // Make sure that the resolver is displayable in car mode
4622                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4623                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4624                return ri;
4625            }
4626        }
4627        return null;
4628    }
4629
4630    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4631            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4632        final int N = query.size();
4633        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4634                .get(userId);
4635        // Get the list of persistent preferred activities that handle the intent
4636        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4637        List<PersistentPreferredActivity> pprefs = ppir != null
4638                ? ppir.queryIntent(intent, resolvedType,
4639                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4640                : null;
4641        if (pprefs != null && pprefs.size() > 0) {
4642            final int M = pprefs.size();
4643            for (int i=0; i<M; i++) {
4644                final PersistentPreferredActivity ppa = pprefs.get(i);
4645                if (DEBUG_PREFERRED || debug) {
4646                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4647                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4648                            + "\n  component=" + ppa.mComponent);
4649                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4650                }
4651                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4652                        flags | MATCH_DISABLED_COMPONENTS, userId);
4653                if (DEBUG_PREFERRED || debug) {
4654                    Slog.v(TAG, "Found persistent preferred activity:");
4655                    if (ai != null) {
4656                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4657                    } else {
4658                        Slog.v(TAG, "  null");
4659                    }
4660                }
4661                if (ai == null) {
4662                    // This previously registered persistent preferred activity
4663                    // component is no longer known. Ignore it and do NOT remove it.
4664                    continue;
4665                }
4666                for (int j=0; j<N; j++) {
4667                    final ResolveInfo ri = query.get(j);
4668                    if (!ri.activityInfo.applicationInfo.packageName
4669                            .equals(ai.applicationInfo.packageName)) {
4670                        continue;
4671                    }
4672                    if (!ri.activityInfo.name.equals(ai.name)) {
4673                        continue;
4674                    }
4675                    //  Found a persistent preference that can handle the intent.
4676                    if (DEBUG_PREFERRED || debug) {
4677                        Slog.v(TAG, "Returning persistent preferred activity: " +
4678                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4679                    }
4680                    return ri;
4681                }
4682            }
4683        }
4684        return null;
4685    }
4686
4687    // TODO: handle preferred activities missing while user has amnesia
4688    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4689            List<ResolveInfo> query, int priority, boolean always,
4690            boolean removeMatches, boolean debug, int userId) {
4691        if (!sUserManager.exists(userId)) return null;
4692        flags = updateFlagsForResolve(flags, userId, intent);
4693        // writer
4694        synchronized (mPackages) {
4695            if (intent.getSelector() != null) {
4696                intent = intent.getSelector();
4697            }
4698            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4699
4700            // Try to find a matching persistent preferred activity.
4701            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4702                    debug, userId);
4703
4704            // If a persistent preferred activity matched, use it.
4705            if (pri != null) {
4706                return pri;
4707            }
4708
4709            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4710            // Get the list of preferred activities that handle the intent
4711            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4712            List<PreferredActivity> prefs = pir != null
4713                    ? pir.queryIntent(intent, resolvedType,
4714                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4715                    : null;
4716            if (prefs != null && prefs.size() > 0) {
4717                boolean changed = false;
4718                try {
4719                    // First figure out how good the original match set is.
4720                    // We will only allow preferred activities that came
4721                    // from the same match quality.
4722                    int match = 0;
4723
4724                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4725
4726                    final int N = query.size();
4727                    for (int j=0; j<N; j++) {
4728                        final ResolveInfo ri = query.get(j);
4729                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4730                                + ": 0x" + Integer.toHexString(match));
4731                        if (ri.match > match) {
4732                            match = ri.match;
4733                        }
4734                    }
4735
4736                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4737                            + Integer.toHexString(match));
4738
4739                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4740                    final int M = prefs.size();
4741                    for (int i=0; i<M; i++) {
4742                        final PreferredActivity pa = prefs.get(i);
4743                        if (DEBUG_PREFERRED || debug) {
4744                            Slog.v(TAG, "Checking PreferredActivity ds="
4745                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4746                                    + "\n  component=" + pa.mPref.mComponent);
4747                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4748                        }
4749                        if (pa.mPref.mMatch != match) {
4750                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4751                                    + Integer.toHexString(pa.mPref.mMatch));
4752                            continue;
4753                        }
4754                        // If it's not an "always" type preferred activity and that's what we're
4755                        // looking for, skip it.
4756                        if (always && !pa.mPref.mAlways) {
4757                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4758                            continue;
4759                        }
4760                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4761                                flags | MATCH_DISABLED_COMPONENTS, userId);
4762                        if (DEBUG_PREFERRED || debug) {
4763                            Slog.v(TAG, "Found preferred activity:");
4764                            if (ai != null) {
4765                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4766                            } else {
4767                                Slog.v(TAG, "  null");
4768                            }
4769                        }
4770                        if (ai == null) {
4771                            // This previously registered preferred activity
4772                            // component is no longer known.  Most likely an update
4773                            // to the app was installed and in the new version this
4774                            // component no longer exists.  Clean it up by removing
4775                            // it from the preferred activities list, and skip it.
4776                            Slog.w(TAG, "Removing dangling preferred activity: "
4777                                    + pa.mPref.mComponent);
4778                            pir.removeFilter(pa);
4779                            changed = true;
4780                            continue;
4781                        }
4782                        for (int j=0; j<N; j++) {
4783                            final ResolveInfo ri = query.get(j);
4784                            if (!ri.activityInfo.applicationInfo.packageName
4785                                    .equals(ai.applicationInfo.packageName)) {
4786                                continue;
4787                            }
4788                            if (!ri.activityInfo.name.equals(ai.name)) {
4789                                continue;
4790                            }
4791
4792                            if (removeMatches) {
4793                                pir.removeFilter(pa);
4794                                changed = true;
4795                                if (DEBUG_PREFERRED) {
4796                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4797                                }
4798                                break;
4799                            }
4800
4801                            // Okay we found a previously set preferred or last chosen app.
4802                            // If the result set is different from when this
4803                            // was created, we need to clear it and re-ask the
4804                            // user their preference, if we're looking for an "always" type entry.
4805                            if (always && !pa.mPref.sameSet(query)) {
4806                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4807                                        + intent + " type " + resolvedType);
4808                                if (DEBUG_PREFERRED) {
4809                                    Slog.v(TAG, "Removing preferred activity since set changed "
4810                                            + pa.mPref.mComponent);
4811                                }
4812                                pir.removeFilter(pa);
4813                                // Re-add the filter as a "last chosen" entry (!always)
4814                                PreferredActivity lastChosen = new PreferredActivity(
4815                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4816                                pir.addFilter(lastChosen);
4817                                changed = true;
4818                                return null;
4819                            }
4820
4821                            // Yay! Either the set matched or we're looking for the last chosen
4822                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4823                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4824                            return ri;
4825                        }
4826                    }
4827                } finally {
4828                    if (changed) {
4829                        if (DEBUG_PREFERRED) {
4830                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4831                        }
4832                        scheduleWritePackageRestrictionsLocked(userId);
4833                    }
4834                }
4835            }
4836        }
4837        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4838        return null;
4839    }
4840
4841    /*
4842     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4843     */
4844    @Override
4845    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4846            int targetUserId) {
4847        mContext.enforceCallingOrSelfPermission(
4848                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4849        List<CrossProfileIntentFilter> matches =
4850                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4851        if (matches != null) {
4852            int size = matches.size();
4853            for (int i = 0; i < size; i++) {
4854                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4855            }
4856        }
4857        if (hasWebURI(intent)) {
4858            // cross-profile app linking works only towards the parent.
4859            final UserInfo parent = getProfileParent(sourceUserId);
4860            synchronized(mPackages) {
4861                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4862                        intent, resolvedType, 0, sourceUserId, parent.id);
4863                return xpDomainInfo != null;
4864            }
4865        }
4866        return false;
4867    }
4868
4869    private UserInfo getProfileParent(int userId) {
4870        final long identity = Binder.clearCallingIdentity();
4871        try {
4872            return sUserManager.getProfileParent(userId);
4873        } finally {
4874            Binder.restoreCallingIdentity(identity);
4875        }
4876    }
4877
4878    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4879            String resolvedType, int userId) {
4880        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4881        if (resolver != null) {
4882            return resolver.queryIntent(intent, resolvedType, false, userId);
4883        }
4884        return null;
4885    }
4886
4887    @Override
4888    public List<ResolveInfo> queryIntentActivities(Intent intent,
4889            String resolvedType, int flags, int userId) {
4890        if (!sUserManager.exists(userId)) return Collections.emptyList();
4891        flags = updateFlagsForResolve(flags, userId, intent);
4892        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4893        ComponentName comp = intent.getComponent();
4894        if (comp == null) {
4895            if (intent.getSelector() != null) {
4896                intent = intent.getSelector();
4897                comp = intent.getComponent();
4898            }
4899        }
4900
4901        if (comp != null) {
4902            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4903            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4904            if (ai != null) {
4905                final ResolveInfo ri = new ResolveInfo();
4906                ri.activityInfo = ai;
4907                list.add(ri);
4908            }
4909            return list;
4910        }
4911
4912        // reader
4913        synchronized (mPackages) {
4914            final String pkgName = intent.getPackage();
4915            if (pkgName == null) {
4916                List<CrossProfileIntentFilter> matchingFilters =
4917                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4918                // Check for results that need to skip the current profile.
4919                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4920                        resolvedType, flags, userId);
4921                if (xpResolveInfo != null) {
4922                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4923                    result.add(xpResolveInfo);
4924                    return filterIfNotSystemUser(result, userId);
4925                }
4926
4927                // Check for results in the current profile.
4928                List<ResolveInfo> result = mActivities.queryIntent(
4929                        intent, resolvedType, flags, userId);
4930                result = filterIfNotSystemUser(result, userId);
4931
4932                // Check for cross profile results.
4933                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4934                xpResolveInfo = queryCrossProfileIntents(
4935                        matchingFilters, intent, resolvedType, flags, userId,
4936                        hasNonNegativePriorityResult);
4937                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4938                    boolean isVisibleToUser = filterIfNotSystemUser(
4939                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4940                    if (isVisibleToUser) {
4941                        result.add(xpResolveInfo);
4942                        Collections.sort(result, mResolvePrioritySorter);
4943                    }
4944                }
4945                if (hasWebURI(intent)) {
4946                    CrossProfileDomainInfo xpDomainInfo = null;
4947                    final UserInfo parent = getProfileParent(userId);
4948                    if (parent != null) {
4949                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4950                                flags, userId, parent.id);
4951                    }
4952                    if (xpDomainInfo != null) {
4953                        if (xpResolveInfo != null) {
4954                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4955                            // in the result.
4956                            result.remove(xpResolveInfo);
4957                        }
4958                        if (result.size() == 0) {
4959                            result.add(xpDomainInfo.resolveInfo);
4960                            return result;
4961                        }
4962                    } else if (result.size() <= 1) {
4963                        return result;
4964                    }
4965                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4966                            xpDomainInfo, userId);
4967                    Collections.sort(result, mResolvePrioritySorter);
4968                }
4969                return result;
4970            }
4971            final PackageParser.Package pkg = mPackages.get(pkgName);
4972            if (pkg != null) {
4973                return filterIfNotSystemUser(
4974                        mActivities.queryIntentForPackage(
4975                                intent, resolvedType, flags, pkg.activities, userId),
4976                        userId);
4977            }
4978            return new ArrayList<ResolveInfo>();
4979        }
4980    }
4981
4982    private static class CrossProfileDomainInfo {
4983        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4984        ResolveInfo resolveInfo;
4985        /* Best domain verification status of the activities found in the other profile */
4986        int bestDomainVerificationStatus;
4987    }
4988
4989    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4990            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4991        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4992                sourceUserId)) {
4993            return null;
4994        }
4995        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4996                resolvedType, flags, parentUserId);
4997
4998        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4999            return null;
5000        }
5001        CrossProfileDomainInfo result = null;
5002        int size = resultTargetUser.size();
5003        for (int i = 0; i < size; i++) {
5004            ResolveInfo riTargetUser = resultTargetUser.get(i);
5005            // Intent filter verification is only for filters that specify a host. So don't return
5006            // those that handle all web uris.
5007            if (riTargetUser.handleAllWebDataURI) {
5008                continue;
5009            }
5010            String packageName = riTargetUser.activityInfo.packageName;
5011            PackageSetting ps = mSettings.mPackages.get(packageName);
5012            if (ps == null) {
5013                continue;
5014            }
5015            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5016            int status = (int)(verificationState >> 32);
5017            if (result == null) {
5018                result = new CrossProfileDomainInfo();
5019                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5020                        sourceUserId, parentUserId);
5021                result.bestDomainVerificationStatus = status;
5022            } else {
5023                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5024                        result.bestDomainVerificationStatus);
5025            }
5026        }
5027        // Don't consider matches with status NEVER across profiles.
5028        if (result != null && result.bestDomainVerificationStatus
5029                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5030            return null;
5031        }
5032        return result;
5033    }
5034
5035    /**
5036     * Verification statuses are ordered from the worse to the best, except for
5037     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5038     */
5039    private int bestDomainVerificationStatus(int status1, int status2) {
5040        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5041            return status2;
5042        }
5043        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5044            return status1;
5045        }
5046        return (int) MathUtils.max(status1, status2);
5047    }
5048
5049    private boolean isUserEnabled(int userId) {
5050        long callingId = Binder.clearCallingIdentity();
5051        try {
5052            UserInfo userInfo = sUserManager.getUserInfo(userId);
5053            return userInfo != null && userInfo.isEnabled();
5054        } finally {
5055            Binder.restoreCallingIdentity(callingId);
5056        }
5057    }
5058
5059    /**
5060     * Filter out activities with systemUserOnly flag set, when current user is not System.
5061     *
5062     * @return filtered list
5063     */
5064    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5065        if (userId == UserHandle.USER_SYSTEM) {
5066            return resolveInfos;
5067        }
5068        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5069            ResolveInfo info = resolveInfos.get(i);
5070            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5071                resolveInfos.remove(i);
5072            }
5073        }
5074        return resolveInfos;
5075    }
5076
5077    /**
5078     * @param resolveInfos list of resolve infos in descending priority order
5079     * @return if the list contains a resolve info with non-negative priority
5080     */
5081    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5082        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5083    }
5084
5085    private static boolean hasWebURI(Intent intent) {
5086        if (intent.getData() == null) {
5087            return false;
5088        }
5089        final String scheme = intent.getScheme();
5090        if (TextUtils.isEmpty(scheme)) {
5091            return false;
5092        }
5093        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5094    }
5095
5096    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5097            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5098            int userId) {
5099        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5100
5101        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5102            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5103                    candidates.size());
5104        }
5105
5106        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5107        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5108        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5109        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5110        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5111        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5112
5113        synchronized (mPackages) {
5114            final int count = candidates.size();
5115            // First, try to use linked apps. Partition the candidates into four lists:
5116            // one for the final results, one for the "do not use ever", one for "undefined status"
5117            // and finally one for "browser app type".
5118            for (int n=0; n<count; n++) {
5119                ResolveInfo info = candidates.get(n);
5120                String packageName = info.activityInfo.packageName;
5121                PackageSetting ps = mSettings.mPackages.get(packageName);
5122                if (ps != null) {
5123                    // Add to the special match all list (Browser use case)
5124                    if (info.handleAllWebDataURI) {
5125                        matchAllList.add(info);
5126                        continue;
5127                    }
5128                    // Try to get the status from User settings first
5129                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5130                    int status = (int)(packedStatus >> 32);
5131                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5132                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5133                        if (DEBUG_DOMAIN_VERIFICATION) {
5134                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5135                                    + " : linkgen=" + linkGeneration);
5136                        }
5137                        // Use link-enabled generation as preferredOrder, i.e.
5138                        // prefer newly-enabled over earlier-enabled.
5139                        info.preferredOrder = linkGeneration;
5140                        alwaysList.add(info);
5141                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5142                        if (DEBUG_DOMAIN_VERIFICATION) {
5143                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5144                        }
5145                        neverList.add(info);
5146                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5147                        if (DEBUG_DOMAIN_VERIFICATION) {
5148                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5149                        }
5150                        alwaysAskList.add(info);
5151                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5152                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5153                        if (DEBUG_DOMAIN_VERIFICATION) {
5154                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5155                        }
5156                        undefinedList.add(info);
5157                    }
5158                }
5159            }
5160
5161            // We'll want to include browser possibilities in a few cases
5162            boolean includeBrowser = false;
5163
5164            // First try to add the "always" resolution(s) for the current user, if any
5165            if (alwaysList.size() > 0) {
5166                result.addAll(alwaysList);
5167            } else {
5168                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5169                result.addAll(undefinedList);
5170                // Maybe add one for the other profile.
5171                if (xpDomainInfo != null && (
5172                        xpDomainInfo.bestDomainVerificationStatus
5173                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5174                    result.add(xpDomainInfo.resolveInfo);
5175                }
5176                includeBrowser = true;
5177            }
5178
5179            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5180            // If there were 'always' entries their preferred order has been set, so we also
5181            // back that off to make the alternatives equivalent
5182            if (alwaysAskList.size() > 0) {
5183                for (ResolveInfo i : result) {
5184                    i.preferredOrder = 0;
5185                }
5186                result.addAll(alwaysAskList);
5187                includeBrowser = true;
5188            }
5189
5190            if (includeBrowser) {
5191                // Also add browsers (all of them or only the default one)
5192                if (DEBUG_DOMAIN_VERIFICATION) {
5193                    Slog.v(TAG, "   ...including browsers in candidate set");
5194                }
5195                if ((matchFlags & MATCH_ALL) != 0) {
5196                    result.addAll(matchAllList);
5197                } else {
5198                    // Browser/generic handling case.  If there's a default browser, go straight
5199                    // to that (but only if there is no other higher-priority match).
5200                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5201                    int maxMatchPrio = 0;
5202                    ResolveInfo defaultBrowserMatch = null;
5203                    final int numCandidates = matchAllList.size();
5204                    for (int n = 0; n < numCandidates; n++) {
5205                        ResolveInfo info = matchAllList.get(n);
5206                        // track the highest overall match priority...
5207                        if (info.priority > maxMatchPrio) {
5208                            maxMatchPrio = info.priority;
5209                        }
5210                        // ...and the highest-priority default browser match
5211                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5212                            if (defaultBrowserMatch == null
5213                                    || (defaultBrowserMatch.priority < info.priority)) {
5214                                if (debug) {
5215                                    Slog.v(TAG, "Considering default browser match " + info);
5216                                }
5217                                defaultBrowserMatch = info;
5218                            }
5219                        }
5220                    }
5221                    if (defaultBrowserMatch != null
5222                            && defaultBrowserMatch.priority >= maxMatchPrio
5223                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5224                    {
5225                        if (debug) {
5226                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5227                        }
5228                        result.add(defaultBrowserMatch);
5229                    } else {
5230                        result.addAll(matchAllList);
5231                    }
5232                }
5233
5234                // If there is nothing selected, add all candidates and remove the ones that the user
5235                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5236                if (result.size() == 0) {
5237                    result.addAll(candidates);
5238                    result.removeAll(neverList);
5239                }
5240            }
5241        }
5242        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5243            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5244                    result.size());
5245            for (ResolveInfo info : result) {
5246                Slog.v(TAG, "  + " + info.activityInfo);
5247            }
5248        }
5249        return result;
5250    }
5251
5252    // Returns a packed value as a long:
5253    //
5254    // high 'int'-sized word: link status: undefined/ask/never/always.
5255    // low 'int'-sized word: relative priority among 'always' results.
5256    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5257        long result = ps.getDomainVerificationStatusForUser(userId);
5258        // if none available, get the master status
5259        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5260            if (ps.getIntentFilterVerificationInfo() != null) {
5261                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5262            }
5263        }
5264        return result;
5265    }
5266
5267    private ResolveInfo querySkipCurrentProfileIntents(
5268            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5269            int flags, int sourceUserId) {
5270        if (matchingFilters != null) {
5271            int size = matchingFilters.size();
5272            for (int i = 0; i < size; i ++) {
5273                CrossProfileIntentFilter filter = matchingFilters.get(i);
5274                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5275                    // Checking if there are activities in the target user that can handle the
5276                    // intent.
5277                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5278                            resolvedType, flags, sourceUserId);
5279                    if (resolveInfo != null) {
5280                        return resolveInfo;
5281                    }
5282                }
5283            }
5284        }
5285        return null;
5286    }
5287
5288    // Return matching ResolveInfo in target user if any.
5289    private ResolveInfo queryCrossProfileIntents(
5290            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5291            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5292        if (matchingFilters != null) {
5293            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5294            // match the same intent. For performance reasons, it is better not to
5295            // run queryIntent twice for the same userId
5296            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5297            int size = matchingFilters.size();
5298            for (int i = 0; i < size; i++) {
5299                CrossProfileIntentFilter filter = matchingFilters.get(i);
5300                int targetUserId = filter.getTargetUserId();
5301                boolean skipCurrentProfile =
5302                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5303                boolean skipCurrentProfileIfNoMatchFound =
5304                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5305                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5306                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5307                    // Checking if there are activities in the target user that can handle the
5308                    // intent.
5309                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5310                            resolvedType, flags, sourceUserId);
5311                    if (resolveInfo != null) return resolveInfo;
5312                    alreadyTriedUserIds.put(targetUserId, true);
5313                }
5314            }
5315        }
5316        return null;
5317    }
5318
5319    /**
5320     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5321     * will forward the intent to the filter's target user.
5322     * Otherwise, returns null.
5323     */
5324    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5325            String resolvedType, int flags, int sourceUserId) {
5326        int targetUserId = filter.getTargetUserId();
5327        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5328                resolvedType, flags, targetUserId);
5329        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5330                && isUserEnabled(targetUserId)) {
5331            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5332        }
5333        return null;
5334    }
5335
5336    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5337            int sourceUserId, int targetUserId) {
5338        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5339        long ident = Binder.clearCallingIdentity();
5340        boolean targetIsProfile;
5341        try {
5342            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5343        } finally {
5344            Binder.restoreCallingIdentity(ident);
5345        }
5346        String className;
5347        if (targetIsProfile) {
5348            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5349        } else {
5350            className = FORWARD_INTENT_TO_PARENT;
5351        }
5352        ComponentName forwardingActivityComponentName = new ComponentName(
5353                mAndroidApplication.packageName, className);
5354        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5355                sourceUserId);
5356        if (!targetIsProfile) {
5357            forwardingActivityInfo.showUserIcon = targetUserId;
5358            forwardingResolveInfo.noResourceId = true;
5359        }
5360        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5361        forwardingResolveInfo.priority = 0;
5362        forwardingResolveInfo.preferredOrder = 0;
5363        forwardingResolveInfo.match = 0;
5364        forwardingResolveInfo.isDefault = true;
5365        forwardingResolveInfo.filter = filter;
5366        forwardingResolveInfo.targetUserId = targetUserId;
5367        return forwardingResolveInfo;
5368    }
5369
5370    @Override
5371    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5372            Intent[] specifics, String[] specificTypes, Intent intent,
5373            String resolvedType, int flags, int userId) {
5374        if (!sUserManager.exists(userId)) return Collections.emptyList();
5375        flags = updateFlagsForResolve(flags, userId, intent);
5376        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5377                false, "query intent activity options");
5378        final String resultsAction = intent.getAction();
5379
5380        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5381                | PackageManager.GET_RESOLVED_FILTER, userId);
5382
5383        if (DEBUG_INTENT_MATCHING) {
5384            Log.v(TAG, "Query " + intent + ": " + results);
5385        }
5386
5387        int specificsPos = 0;
5388        int N;
5389
5390        // todo: note that the algorithm used here is O(N^2).  This
5391        // isn't a problem in our current environment, but if we start running
5392        // into situations where we have more than 5 or 10 matches then this
5393        // should probably be changed to something smarter...
5394
5395        // First we go through and resolve each of the specific items
5396        // that were supplied, taking care of removing any corresponding
5397        // duplicate items in the generic resolve list.
5398        if (specifics != null) {
5399            for (int i=0; i<specifics.length; i++) {
5400                final Intent sintent = specifics[i];
5401                if (sintent == null) {
5402                    continue;
5403                }
5404
5405                if (DEBUG_INTENT_MATCHING) {
5406                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5407                }
5408
5409                String action = sintent.getAction();
5410                if (resultsAction != null && resultsAction.equals(action)) {
5411                    // If this action was explicitly requested, then don't
5412                    // remove things that have it.
5413                    action = null;
5414                }
5415
5416                ResolveInfo ri = null;
5417                ActivityInfo ai = null;
5418
5419                ComponentName comp = sintent.getComponent();
5420                if (comp == null) {
5421                    ri = resolveIntent(
5422                        sintent,
5423                        specificTypes != null ? specificTypes[i] : null,
5424                            flags, userId);
5425                    if (ri == null) {
5426                        continue;
5427                    }
5428                    if (ri == mResolveInfo) {
5429                        // ACK!  Must do something better with this.
5430                    }
5431                    ai = ri.activityInfo;
5432                    comp = new ComponentName(ai.applicationInfo.packageName,
5433                            ai.name);
5434                } else {
5435                    ai = getActivityInfo(comp, flags, userId);
5436                    if (ai == null) {
5437                        continue;
5438                    }
5439                }
5440
5441                // Look for any generic query activities that are duplicates
5442                // of this specific one, and remove them from the results.
5443                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5444                N = results.size();
5445                int j;
5446                for (j=specificsPos; j<N; j++) {
5447                    ResolveInfo sri = results.get(j);
5448                    if ((sri.activityInfo.name.equals(comp.getClassName())
5449                            && sri.activityInfo.applicationInfo.packageName.equals(
5450                                    comp.getPackageName()))
5451                        || (action != null && sri.filter.matchAction(action))) {
5452                        results.remove(j);
5453                        if (DEBUG_INTENT_MATCHING) Log.v(
5454                            TAG, "Removing duplicate item from " + j
5455                            + " due to specific " + specificsPos);
5456                        if (ri == null) {
5457                            ri = sri;
5458                        }
5459                        j--;
5460                        N--;
5461                    }
5462                }
5463
5464                // Add this specific item to its proper place.
5465                if (ri == null) {
5466                    ri = new ResolveInfo();
5467                    ri.activityInfo = ai;
5468                }
5469                results.add(specificsPos, ri);
5470                ri.specificIndex = i;
5471                specificsPos++;
5472            }
5473        }
5474
5475        // Now we go through the remaining generic results and remove any
5476        // duplicate actions that are found here.
5477        N = results.size();
5478        for (int i=specificsPos; i<N-1; i++) {
5479            final ResolveInfo rii = results.get(i);
5480            if (rii.filter == null) {
5481                continue;
5482            }
5483
5484            // Iterate over all of the actions of this result's intent
5485            // filter...  typically this should be just one.
5486            final Iterator<String> it = rii.filter.actionsIterator();
5487            if (it == null) {
5488                continue;
5489            }
5490            while (it.hasNext()) {
5491                final String action = it.next();
5492                if (resultsAction != null && resultsAction.equals(action)) {
5493                    // If this action was explicitly requested, then don't
5494                    // remove things that have it.
5495                    continue;
5496                }
5497                for (int j=i+1; j<N; j++) {
5498                    final ResolveInfo rij = results.get(j);
5499                    if (rij.filter != null && rij.filter.hasAction(action)) {
5500                        results.remove(j);
5501                        if (DEBUG_INTENT_MATCHING) Log.v(
5502                            TAG, "Removing duplicate item from " + j
5503                            + " due to action " + action + " at " + i);
5504                        j--;
5505                        N--;
5506                    }
5507                }
5508            }
5509
5510            // If the caller didn't request filter information, drop it now
5511            // so we don't have to marshall/unmarshall it.
5512            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5513                rii.filter = null;
5514            }
5515        }
5516
5517        // Filter out the caller activity if so requested.
5518        if (caller != null) {
5519            N = results.size();
5520            for (int i=0; i<N; i++) {
5521                ActivityInfo ainfo = results.get(i).activityInfo;
5522                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5523                        && caller.getClassName().equals(ainfo.name)) {
5524                    results.remove(i);
5525                    break;
5526                }
5527            }
5528        }
5529
5530        // If the caller didn't request filter information,
5531        // drop them now so we don't have to
5532        // marshall/unmarshall it.
5533        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5534            N = results.size();
5535            for (int i=0; i<N; i++) {
5536                results.get(i).filter = null;
5537            }
5538        }
5539
5540        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5541        return results;
5542    }
5543
5544    @Override
5545    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5546            int userId) {
5547        if (!sUserManager.exists(userId)) return Collections.emptyList();
5548        flags = updateFlagsForResolve(flags, userId, intent);
5549        ComponentName comp = intent.getComponent();
5550        if (comp == null) {
5551            if (intent.getSelector() != null) {
5552                intent = intent.getSelector();
5553                comp = intent.getComponent();
5554            }
5555        }
5556        if (comp != null) {
5557            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5558            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5559            if (ai != null) {
5560                ResolveInfo ri = new ResolveInfo();
5561                ri.activityInfo = ai;
5562                list.add(ri);
5563            }
5564            return list;
5565        }
5566
5567        // reader
5568        synchronized (mPackages) {
5569            String pkgName = intent.getPackage();
5570            if (pkgName == null) {
5571                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5572            }
5573            final PackageParser.Package pkg = mPackages.get(pkgName);
5574            if (pkg != null) {
5575                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5576                        userId);
5577            }
5578            return null;
5579        }
5580    }
5581
5582    @Override
5583    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5584        if (!sUserManager.exists(userId)) return null;
5585        flags = updateFlagsForResolve(flags, userId, intent);
5586        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5587        if (query != null) {
5588            if (query.size() >= 1) {
5589                // If there is more than one service with the same priority,
5590                // just arbitrarily pick the first one.
5591                return query.get(0);
5592            }
5593        }
5594        return null;
5595    }
5596
5597    @Override
5598    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5599            int userId) {
5600        if (!sUserManager.exists(userId)) return Collections.emptyList();
5601        flags = updateFlagsForResolve(flags, userId, intent);
5602        ComponentName comp = intent.getComponent();
5603        if (comp == null) {
5604            if (intent.getSelector() != null) {
5605                intent = intent.getSelector();
5606                comp = intent.getComponent();
5607            }
5608        }
5609        if (comp != null) {
5610            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5611            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5612            if (si != null) {
5613                final ResolveInfo ri = new ResolveInfo();
5614                ri.serviceInfo = si;
5615                list.add(ri);
5616            }
5617            return list;
5618        }
5619
5620        // reader
5621        synchronized (mPackages) {
5622            String pkgName = intent.getPackage();
5623            if (pkgName == null) {
5624                return mServices.queryIntent(intent, resolvedType, flags, userId);
5625            }
5626            final PackageParser.Package pkg = mPackages.get(pkgName);
5627            if (pkg != null) {
5628                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5629                        userId);
5630            }
5631            return null;
5632        }
5633    }
5634
5635    @Override
5636    public List<ResolveInfo> queryIntentContentProviders(
5637            Intent intent, String resolvedType, int flags, int userId) {
5638        if (!sUserManager.exists(userId)) return Collections.emptyList();
5639        flags = updateFlagsForResolve(flags, userId, intent);
5640        ComponentName comp = intent.getComponent();
5641        if (comp == null) {
5642            if (intent.getSelector() != null) {
5643                intent = intent.getSelector();
5644                comp = intent.getComponent();
5645            }
5646        }
5647        if (comp != null) {
5648            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5649            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5650            if (pi != null) {
5651                final ResolveInfo ri = new ResolveInfo();
5652                ri.providerInfo = pi;
5653                list.add(ri);
5654            }
5655            return list;
5656        }
5657
5658        // reader
5659        synchronized (mPackages) {
5660            String pkgName = intent.getPackage();
5661            if (pkgName == null) {
5662                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5663            }
5664            final PackageParser.Package pkg = mPackages.get(pkgName);
5665            if (pkg != null) {
5666                return mProviders.queryIntentForPackage(
5667                        intent, resolvedType, flags, pkg.providers, userId);
5668            }
5669            return null;
5670        }
5671    }
5672
5673    @Override
5674    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5675        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5676        flags = updateFlagsForPackage(flags, userId, null);
5677        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5678        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5679
5680        // writer
5681        synchronized (mPackages) {
5682            ArrayList<PackageInfo> list;
5683            if (listUninstalled) {
5684                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5685                for (PackageSetting ps : mSettings.mPackages.values()) {
5686                    PackageInfo pi;
5687                    if (ps.pkg != null) {
5688                        pi = generatePackageInfo(ps.pkg, flags, userId);
5689                    } else {
5690                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5691                    }
5692                    if (pi != null) {
5693                        list.add(pi);
5694                    }
5695                }
5696            } else {
5697                list = new ArrayList<PackageInfo>(mPackages.size());
5698                for (PackageParser.Package p : mPackages.values()) {
5699                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5700                    if (pi != null) {
5701                        list.add(pi);
5702                    }
5703                }
5704            }
5705
5706            return new ParceledListSlice<PackageInfo>(list);
5707        }
5708    }
5709
5710    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5711            String[] permissions, boolean[] tmp, int flags, int userId) {
5712        int numMatch = 0;
5713        final PermissionsState permissionsState = ps.getPermissionsState();
5714        for (int i=0; i<permissions.length; i++) {
5715            final String permission = permissions[i];
5716            if (permissionsState.hasPermission(permission, userId)) {
5717                tmp[i] = true;
5718                numMatch++;
5719            } else {
5720                tmp[i] = false;
5721            }
5722        }
5723        if (numMatch == 0) {
5724            return;
5725        }
5726        PackageInfo pi;
5727        if (ps.pkg != null) {
5728            pi = generatePackageInfo(ps.pkg, flags, userId);
5729        } else {
5730            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5731        }
5732        // The above might return null in cases of uninstalled apps or install-state
5733        // skew across users/profiles.
5734        if (pi != null) {
5735            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5736                if (numMatch == permissions.length) {
5737                    pi.requestedPermissions = permissions;
5738                } else {
5739                    pi.requestedPermissions = new String[numMatch];
5740                    numMatch = 0;
5741                    for (int i=0; i<permissions.length; i++) {
5742                        if (tmp[i]) {
5743                            pi.requestedPermissions[numMatch] = permissions[i];
5744                            numMatch++;
5745                        }
5746                    }
5747                }
5748            }
5749            list.add(pi);
5750        }
5751    }
5752
5753    @Override
5754    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5755            String[] permissions, int flags, int userId) {
5756        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5757        flags = updateFlagsForPackage(flags, userId, permissions);
5758        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5759
5760        // writer
5761        synchronized (mPackages) {
5762            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5763            boolean[] tmpBools = new boolean[permissions.length];
5764            if (listUninstalled) {
5765                for (PackageSetting ps : mSettings.mPackages.values()) {
5766                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5767                }
5768            } else {
5769                for (PackageParser.Package pkg : mPackages.values()) {
5770                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5771                    if (ps != null) {
5772                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5773                                userId);
5774                    }
5775                }
5776            }
5777
5778            return new ParceledListSlice<PackageInfo>(list);
5779        }
5780    }
5781
5782    @Override
5783    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5784        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5785        flags = updateFlagsForApplication(flags, userId, null);
5786        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5787
5788        // writer
5789        synchronized (mPackages) {
5790            ArrayList<ApplicationInfo> list;
5791            if (listUninstalled) {
5792                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5793                for (PackageSetting ps : mSettings.mPackages.values()) {
5794                    ApplicationInfo ai;
5795                    if (ps.pkg != null) {
5796                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5797                                ps.readUserState(userId), userId);
5798                    } else {
5799                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5800                    }
5801                    if (ai != null) {
5802                        list.add(ai);
5803                    }
5804                }
5805            } else {
5806                list = new ArrayList<ApplicationInfo>(mPackages.size());
5807                for (PackageParser.Package p : mPackages.values()) {
5808                    if (p.mExtras != null) {
5809                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5810                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5811                        if (ai != null) {
5812                            list.add(ai);
5813                        }
5814                    }
5815                }
5816            }
5817
5818            return new ParceledListSlice<ApplicationInfo>(list);
5819        }
5820    }
5821
5822    @Override
5823    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5824        if (DISABLE_EPHEMERAL_APPS) {
5825            return null;
5826        }
5827
5828        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5829                "getEphemeralApplications");
5830        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5831                "getEphemeralApplications");
5832        synchronized (mPackages) {
5833            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5834                    .getEphemeralApplicationsLPw(userId);
5835            if (ephemeralApps != null) {
5836                return new ParceledListSlice<>(ephemeralApps);
5837            }
5838        }
5839        return null;
5840    }
5841
5842    @Override
5843    public boolean isEphemeralApplication(String packageName, int userId) {
5844        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5845                "isEphemeral");
5846        if (DISABLE_EPHEMERAL_APPS) {
5847            return false;
5848        }
5849
5850        if (!isCallerSameApp(packageName)) {
5851            return false;
5852        }
5853        synchronized (mPackages) {
5854            PackageParser.Package pkg = mPackages.get(packageName);
5855            if (pkg != null) {
5856                return pkg.applicationInfo.isEphemeralApp();
5857            }
5858        }
5859        return false;
5860    }
5861
5862    @Override
5863    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5864        if (DISABLE_EPHEMERAL_APPS) {
5865            return null;
5866        }
5867
5868        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5869                "getCookie");
5870        if (!isCallerSameApp(packageName)) {
5871            return null;
5872        }
5873        synchronized (mPackages) {
5874            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5875                    packageName, userId);
5876        }
5877    }
5878
5879    @Override
5880    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5881        if (DISABLE_EPHEMERAL_APPS) {
5882            return true;
5883        }
5884
5885        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5886                "setCookie");
5887        if (!isCallerSameApp(packageName)) {
5888            return false;
5889        }
5890        synchronized (mPackages) {
5891            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5892                    packageName, cookie, userId);
5893        }
5894    }
5895
5896    @Override
5897    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5898        if (DISABLE_EPHEMERAL_APPS) {
5899            return null;
5900        }
5901
5902        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5903                "getEphemeralApplicationIcon");
5904        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5905                "getEphemeralApplicationIcon");
5906        synchronized (mPackages) {
5907            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5908                    packageName, userId);
5909        }
5910    }
5911
5912    private boolean isCallerSameApp(String packageName) {
5913        PackageParser.Package pkg = mPackages.get(packageName);
5914        return pkg != null
5915                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5916    }
5917
5918    public List<ApplicationInfo> getPersistentApplications(int flags) {
5919        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5920
5921        // reader
5922        synchronized (mPackages) {
5923            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5924            final int userId = UserHandle.getCallingUserId();
5925            while (i.hasNext()) {
5926                final PackageParser.Package p = i.next();
5927                if (p.applicationInfo != null
5928                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5929                        && (!mSafeMode || isSystemApp(p))) {
5930                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5931                    if (ps != null) {
5932                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5933                                ps.readUserState(userId), userId);
5934                        if (ai != null) {
5935                            finalList.add(ai);
5936                        }
5937                    }
5938                }
5939            }
5940        }
5941
5942        return finalList;
5943    }
5944
5945    @Override
5946    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5947        if (!sUserManager.exists(userId)) return null;
5948        flags = updateFlagsForComponent(flags, userId, name);
5949        // reader
5950        synchronized (mPackages) {
5951            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5952            PackageSetting ps = provider != null
5953                    ? mSettings.mPackages.get(provider.owner.packageName)
5954                    : null;
5955            return ps != null
5956                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5957                    ? PackageParser.generateProviderInfo(provider, flags,
5958                            ps.readUserState(userId), userId)
5959                    : null;
5960        }
5961    }
5962
5963    /**
5964     * @deprecated
5965     */
5966    @Deprecated
5967    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5968        // reader
5969        synchronized (mPackages) {
5970            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5971                    .entrySet().iterator();
5972            final int userId = UserHandle.getCallingUserId();
5973            while (i.hasNext()) {
5974                Map.Entry<String, PackageParser.Provider> entry = i.next();
5975                PackageParser.Provider p = entry.getValue();
5976                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5977
5978                if (ps != null && p.syncable
5979                        && (!mSafeMode || (p.info.applicationInfo.flags
5980                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5981                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5982                            ps.readUserState(userId), userId);
5983                    if (info != null) {
5984                        outNames.add(entry.getKey());
5985                        outInfo.add(info);
5986                    }
5987                }
5988            }
5989        }
5990    }
5991
5992    @Override
5993    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5994            int uid, int flags) {
5995        final int userId = processName != null ? UserHandle.getUserId(uid)
5996                : UserHandle.getCallingUserId();
5997        if (!sUserManager.exists(userId)) return null;
5998        flags = updateFlagsForComponent(flags, userId, processName);
5999
6000        ArrayList<ProviderInfo> finalList = null;
6001        // reader
6002        synchronized (mPackages) {
6003            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6004            while (i.hasNext()) {
6005                final PackageParser.Provider p = i.next();
6006                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6007                if (ps != null && p.info.authority != null
6008                        && (processName == null
6009                                || (p.info.processName.equals(processName)
6010                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6011                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6012                    if (finalList == null) {
6013                        finalList = new ArrayList<ProviderInfo>(3);
6014                    }
6015                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6016                            ps.readUserState(userId), userId);
6017                    if (info != null) {
6018                        finalList.add(info);
6019                    }
6020                }
6021            }
6022        }
6023
6024        if (finalList != null) {
6025            Collections.sort(finalList, mProviderInitOrderSorter);
6026            return new ParceledListSlice<ProviderInfo>(finalList);
6027        }
6028
6029        return null;
6030    }
6031
6032    @Override
6033    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6034        // reader
6035        synchronized (mPackages) {
6036            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6037            return PackageParser.generateInstrumentationInfo(i, flags);
6038        }
6039    }
6040
6041    @Override
6042    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6043            int flags) {
6044        ArrayList<InstrumentationInfo> finalList =
6045            new ArrayList<InstrumentationInfo>();
6046
6047        // reader
6048        synchronized (mPackages) {
6049            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6050            while (i.hasNext()) {
6051                final PackageParser.Instrumentation p = i.next();
6052                if (targetPackage == null
6053                        || targetPackage.equals(p.info.targetPackage)) {
6054                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6055                            flags);
6056                    if (ii != null) {
6057                        finalList.add(ii);
6058                    }
6059                }
6060            }
6061        }
6062
6063        return finalList;
6064    }
6065
6066    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6067        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6068        if (overlays == null) {
6069            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6070            return;
6071        }
6072        for (PackageParser.Package opkg : overlays.values()) {
6073            // Not much to do if idmap fails: we already logged the error
6074            // and we certainly don't want to abort installation of pkg simply
6075            // because an overlay didn't fit properly. For these reasons,
6076            // ignore the return value of createIdmapForPackagePairLI.
6077            createIdmapForPackagePairLI(pkg, opkg);
6078        }
6079    }
6080
6081    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6082            PackageParser.Package opkg) {
6083        if (!opkg.mTrustedOverlay) {
6084            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6085                    opkg.baseCodePath + ": overlay not trusted");
6086            return false;
6087        }
6088        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6089        if (overlaySet == null) {
6090            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6091                    opkg.baseCodePath + " but target package has no known overlays");
6092            return false;
6093        }
6094        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6095        // TODO: generate idmap for split APKs
6096        try {
6097            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6098        } catch (InstallerException e) {
6099            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6100                    + opkg.baseCodePath);
6101            return false;
6102        }
6103        PackageParser.Package[] overlayArray =
6104            overlaySet.values().toArray(new PackageParser.Package[0]);
6105        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6106            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6107                return p1.mOverlayPriority - p2.mOverlayPriority;
6108            }
6109        };
6110        Arrays.sort(overlayArray, cmp);
6111
6112        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6113        int i = 0;
6114        for (PackageParser.Package p : overlayArray) {
6115            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6116        }
6117        return true;
6118    }
6119
6120    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6121        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6122        try {
6123            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6124        } finally {
6125            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6126        }
6127    }
6128
6129    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6130        final File[] files = dir.listFiles();
6131        if (ArrayUtils.isEmpty(files)) {
6132            Log.d(TAG, "No files in app dir " + dir);
6133            return;
6134        }
6135
6136        if (DEBUG_PACKAGE_SCANNING) {
6137            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6138                    + " flags=0x" + Integer.toHexString(parseFlags));
6139        }
6140
6141        for (File file : files) {
6142            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6143                    && !PackageInstallerService.isStageName(file.getName());
6144            if (!isPackage) {
6145                // Ignore entries which are not packages
6146                continue;
6147            }
6148            try {
6149                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6150                        scanFlags, currentTime, null);
6151            } catch (PackageManagerException e) {
6152                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6153
6154                // Delete invalid userdata apps
6155                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6156                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6157                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6158                    removeCodePathLI(file);
6159                }
6160            }
6161        }
6162    }
6163
6164    private static File getSettingsProblemFile() {
6165        File dataDir = Environment.getDataDirectory();
6166        File systemDir = new File(dataDir, "system");
6167        File fname = new File(systemDir, "uiderrors.txt");
6168        return fname;
6169    }
6170
6171    static void reportSettingsProblem(int priority, String msg) {
6172        logCriticalInfo(priority, msg);
6173    }
6174
6175    static void logCriticalInfo(int priority, String msg) {
6176        Slog.println(priority, TAG, msg);
6177        EventLogTags.writePmCriticalInfo(msg);
6178        try {
6179            File fname = getSettingsProblemFile();
6180            FileOutputStream out = new FileOutputStream(fname, true);
6181            PrintWriter pw = new FastPrintWriter(out);
6182            SimpleDateFormat formatter = new SimpleDateFormat();
6183            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6184            pw.println(dateString + ": " + msg);
6185            pw.close();
6186            FileUtils.setPermissions(
6187                    fname.toString(),
6188                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6189                    -1, -1);
6190        } catch (java.io.IOException e) {
6191        }
6192    }
6193
6194    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6195            PackageParser.Package pkg, File srcFile, int parseFlags)
6196            throws PackageManagerException {
6197        if (ps != null
6198                && ps.codePath.equals(srcFile)
6199                && ps.timeStamp == srcFile.lastModified()
6200                && !isCompatSignatureUpdateNeeded(pkg)
6201                && !isRecoverSignatureUpdateNeeded(pkg)) {
6202            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6203            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6204            ArraySet<PublicKey> signingKs;
6205            synchronized (mPackages) {
6206                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6207            }
6208            if (ps.signatures.mSignatures != null
6209                    && ps.signatures.mSignatures.length != 0
6210                    && signingKs != null) {
6211                // Optimization: reuse the existing cached certificates
6212                // if the package appears to be unchanged.
6213                pkg.mSignatures = ps.signatures.mSignatures;
6214                pkg.mSigningKeys = signingKs;
6215                return;
6216            }
6217
6218            Slog.w(TAG, "PackageSetting for " + ps.name
6219                    + " is missing signatures.  Collecting certs again to recover them.");
6220        } else {
6221            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6222        }
6223
6224        try {
6225            pp.collectCertificates(pkg, parseFlags);
6226        } catch (PackageParserException e) {
6227            throw PackageManagerException.from(e);
6228        }
6229    }
6230
6231    /**
6232     *  Traces a package scan.
6233     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6234     */
6235    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6236            long currentTime, UserHandle user) throws PackageManagerException {
6237        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6238        try {
6239            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6240        } finally {
6241            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6242        }
6243    }
6244
6245    /**
6246     *  Scans a package and returns the newly parsed package.
6247     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6248     */
6249    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6250            long currentTime, UserHandle user) throws PackageManagerException {
6251        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6252        parseFlags |= mDefParseFlags;
6253        PackageParser pp = new PackageParser();
6254        pp.setSeparateProcesses(mSeparateProcesses);
6255        pp.setOnlyCoreApps(mOnlyCore);
6256        pp.setDisplayMetrics(mMetrics);
6257
6258        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6259            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6260        }
6261
6262        final PackageParser.Package pkg;
6263        try {
6264            pkg = pp.parsePackage(scanFile, parseFlags);
6265        } catch (PackageParserException e) {
6266            throw PackageManagerException.from(e);
6267        }
6268
6269        PackageSetting ps = null;
6270        PackageSetting updatedPkg;
6271        // reader
6272        synchronized (mPackages) {
6273            // Look to see if we already know about this package.
6274            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6275            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6276                // This package has been renamed to its original name.  Let's
6277                // use that.
6278                ps = mSettings.peekPackageLPr(oldName);
6279            }
6280            // If there was no original package, see one for the real package name.
6281            if (ps == null) {
6282                ps = mSettings.peekPackageLPr(pkg.packageName);
6283            }
6284            // Check to see if this package could be hiding/updating a system
6285            // package.  Must look for it either under the original or real
6286            // package name depending on our state.
6287            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6288            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6289        }
6290        boolean updatedPkgBetter = false;
6291        // First check if this is a system package that may involve an update
6292        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6293            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6294            // it needs to drop FLAG_PRIVILEGED.
6295            if (locationIsPrivileged(scanFile)) {
6296                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6297            } else {
6298                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6299            }
6300
6301            if (ps != null && !ps.codePath.equals(scanFile)) {
6302                // The path has changed from what was last scanned...  check the
6303                // version of the new path against what we have stored to determine
6304                // what to do.
6305                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6306                if (pkg.mVersionCode <= ps.versionCode) {
6307                    // The system package has been updated and the code path does not match
6308                    // Ignore entry. Skip it.
6309                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6310                            + " ignored: updated version " + ps.versionCode
6311                            + " better than this " + pkg.mVersionCode);
6312                    if (!updatedPkg.codePath.equals(scanFile)) {
6313                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6314                                + ps.name + " changing from " + updatedPkg.codePathString
6315                                + " to " + scanFile);
6316                        updatedPkg.codePath = scanFile;
6317                        updatedPkg.codePathString = scanFile.toString();
6318                        updatedPkg.resourcePath = scanFile;
6319                        updatedPkg.resourcePathString = scanFile.toString();
6320                    }
6321                    updatedPkg.pkg = pkg;
6322                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6323                            "Package " + ps.name + " at " + scanFile
6324                                    + " ignored: updated version " + ps.versionCode
6325                                    + " better than this " + pkg.mVersionCode);
6326                } else {
6327                    // The current app on the system partition is better than
6328                    // what we have updated to on the data partition; switch
6329                    // back to the system partition version.
6330                    // At this point, its safely assumed that package installation for
6331                    // apps in system partition will go through. If not there won't be a working
6332                    // version of the app
6333                    // writer
6334                    synchronized (mPackages) {
6335                        // Just remove the loaded entries from package lists.
6336                        mPackages.remove(ps.name);
6337                    }
6338
6339                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6340                            + " reverting from " + ps.codePathString
6341                            + ": new version " + pkg.mVersionCode
6342                            + " better than installed " + ps.versionCode);
6343
6344                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6345                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6346                    synchronized (mInstallLock) {
6347                        args.cleanUpResourcesLI();
6348                    }
6349                    synchronized (mPackages) {
6350                        mSettings.enableSystemPackageLPw(ps.name);
6351                    }
6352                    updatedPkgBetter = true;
6353                }
6354            }
6355        }
6356
6357        if (updatedPkg != null) {
6358            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6359            // initially
6360            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6361
6362            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6363            // flag set initially
6364            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6365                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6366            }
6367        }
6368
6369        // Verify certificates against what was last scanned
6370        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6371
6372        /*
6373         * A new system app appeared, but we already had a non-system one of the
6374         * same name installed earlier.
6375         */
6376        boolean shouldHideSystemApp = false;
6377        if (updatedPkg == null && ps != null
6378                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6379            /*
6380             * Check to make sure the signatures match first. If they don't,
6381             * wipe the installed application and its data.
6382             */
6383            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6384                    != PackageManager.SIGNATURE_MATCH) {
6385                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6386                        + " signatures don't match existing userdata copy; removing");
6387                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6388                ps = null;
6389            } else {
6390                /*
6391                 * If the newly-added system app is an older version than the
6392                 * already installed version, hide it. It will be scanned later
6393                 * and re-added like an update.
6394                 */
6395                if (pkg.mVersionCode <= ps.versionCode) {
6396                    shouldHideSystemApp = true;
6397                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6398                            + " but new version " + pkg.mVersionCode + " better than installed "
6399                            + ps.versionCode + "; hiding system");
6400                } else {
6401                    /*
6402                     * The newly found system app is a newer version that the
6403                     * one previously installed. Simply remove the
6404                     * already-installed application and replace it with our own
6405                     * while keeping the application data.
6406                     */
6407                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6408                            + " reverting from " + ps.codePathString + ": new version "
6409                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6410                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6411                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6412                    synchronized (mInstallLock) {
6413                        args.cleanUpResourcesLI();
6414                    }
6415                }
6416            }
6417        }
6418
6419        // The apk is forward locked (not public) if its code and resources
6420        // are kept in different files. (except for app in either system or
6421        // vendor path).
6422        // TODO grab this value from PackageSettings
6423        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6424            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6425                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6426            }
6427        }
6428
6429        // TODO: extend to support forward-locked splits
6430        String resourcePath = null;
6431        String baseResourcePath = null;
6432        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6433            if (ps != null && ps.resourcePathString != null) {
6434                resourcePath = ps.resourcePathString;
6435                baseResourcePath = ps.resourcePathString;
6436            } else {
6437                // Should not happen at all. Just log an error.
6438                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6439            }
6440        } else {
6441            resourcePath = pkg.codePath;
6442            baseResourcePath = pkg.baseCodePath;
6443        }
6444
6445        // Set application objects path explicitly.
6446        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6447        pkg.applicationInfo.setCodePath(pkg.codePath);
6448        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6449        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6450        pkg.applicationInfo.setResourcePath(resourcePath);
6451        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6452        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6453
6454        // Note that we invoke the following method only if we are about to unpack an application
6455        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6456                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6457
6458        /*
6459         * If the system app should be overridden by a previously installed
6460         * data, hide the system app now and let the /data/app scan pick it up
6461         * again.
6462         */
6463        if (shouldHideSystemApp) {
6464            synchronized (mPackages) {
6465                mSettings.disableSystemPackageLPw(pkg.packageName);
6466            }
6467        }
6468
6469        return scannedPkg;
6470    }
6471
6472    private static String fixProcessName(String defProcessName,
6473            String processName, int uid) {
6474        if (processName == null) {
6475            return defProcessName;
6476        }
6477        return processName;
6478    }
6479
6480    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6481            throws PackageManagerException {
6482        if (pkgSetting.signatures.mSignatures != null) {
6483            // Already existing package. Make sure signatures match
6484            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6485                    == PackageManager.SIGNATURE_MATCH;
6486            if (!match) {
6487                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6488                        == PackageManager.SIGNATURE_MATCH;
6489            }
6490            if (!match) {
6491                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6492                        == PackageManager.SIGNATURE_MATCH;
6493            }
6494            if (!match) {
6495                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6496                        + pkg.packageName + " signatures do not match the "
6497                        + "previously installed version; ignoring!");
6498            }
6499        }
6500
6501        // Check for shared user signatures
6502        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6503            // Already existing package. Make sure signatures match
6504            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6505                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6506            if (!match) {
6507                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6508                        == PackageManager.SIGNATURE_MATCH;
6509            }
6510            if (!match) {
6511                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6512                        == PackageManager.SIGNATURE_MATCH;
6513            }
6514            if (!match) {
6515                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6516                        "Package " + pkg.packageName
6517                        + " has no signatures that match those in shared user "
6518                        + pkgSetting.sharedUser.name + "; ignoring!");
6519            }
6520        }
6521    }
6522
6523    /**
6524     * Enforces that only the system UID or root's UID can call a method exposed
6525     * via Binder.
6526     *
6527     * @param message used as message if SecurityException is thrown
6528     * @throws SecurityException if the caller is not system or root
6529     */
6530    private static final void enforceSystemOrRoot(String message) {
6531        final int uid = Binder.getCallingUid();
6532        if (uid != Process.SYSTEM_UID && uid != 0) {
6533            throw new SecurityException(message);
6534        }
6535    }
6536
6537    @Override
6538    public void performFstrimIfNeeded() {
6539        enforceSystemOrRoot("Only the system can request fstrim");
6540
6541        // Before everything else, see whether we need to fstrim.
6542        try {
6543            IMountService ms = PackageHelper.getMountService();
6544            if (ms != null) {
6545                final boolean isUpgrade = isUpgrade();
6546                boolean doTrim = isUpgrade;
6547                if (doTrim) {
6548                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6549                } else {
6550                    final long interval = android.provider.Settings.Global.getLong(
6551                            mContext.getContentResolver(),
6552                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6553                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6554                    if (interval > 0) {
6555                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6556                        if (timeSinceLast > interval) {
6557                            doTrim = true;
6558                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6559                                    + "; running immediately");
6560                        }
6561                    }
6562                }
6563                if (doTrim) {
6564                    if (!isFirstBoot()) {
6565                        try {
6566                            ActivityManagerNative.getDefault().showBootMessage(
6567                                    mContext.getResources().getString(
6568                                            R.string.android_upgrading_fstrim), true);
6569                        } catch (RemoteException e) {
6570                        }
6571                    }
6572                    ms.runMaintenance();
6573                }
6574            } else {
6575                Slog.e(TAG, "Mount service unavailable!");
6576            }
6577        } catch (RemoteException e) {
6578            // Can't happen; MountService is local
6579        }
6580    }
6581
6582    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6583        List<ResolveInfo> ris = null;
6584        try {
6585            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6586                    intent, null, 0, userId);
6587        } catch (RemoteException e) {
6588        }
6589        ArraySet<String> pkgNames = new ArraySet<String>();
6590        if (ris != null) {
6591            for (ResolveInfo ri : ris) {
6592                pkgNames.add(ri.activityInfo.packageName);
6593            }
6594        }
6595        return pkgNames;
6596    }
6597
6598    @Override
6599    public void notifyPackageUse(String packageName) {
6600        synchronized (mPackages) {
6601            PackageParser.Package p = mPackages.get(packageName);
6602            if (p == null) {
6603                return;
6604            }
6605            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6606        }
6607    }
6608
6609    @Override
6610    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6611        return performDexOptTraced(packageName, instructionSet);
6612    }
6613
6614    public boolean performDexOpt(String packageName, String instructionSet) {
6615        return performDexOptTraced(packageName, instructionSet);
6616    }
6617
6618    private boolean performDexOptTraced(String packageName, String instructionSet) {
6619        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6620        try {
6621            return performDexOptInternal(packageName, instructionSet);
6622        } finally {
6623            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6624        }
6625    }
6626
6627    private boolean performDexOptInternal(String packageName, String instructionSet) {
6628        PackageParser.Package p;
6629        final String targetInstructionSet;
6630        synchronized (mPackages) {
6631            p = mPackages.get(packageName);
6632            if (p == null) {
6633                return false;
6634            }
6635            mPackageUsage.write(false);
6636
6637            targetInstructionSet = instructionSet != null ? instructionSet :
6638                    getPrimaryInstructionSet(p.applicationInfo);
6639            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6640                return false;
6641            }
6642        }
6643        long callingId = Binder.clearCallingIdentity();
6644        try {
6645            synchronized (mInstallLock) {
6646                final String[] instructionSets = new String[] { targetInstructionSet };
6647                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6648                        true /* inclDependencies */);
6649                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6650            }
6651        } finally {
6652            Binder.restoreCallingIdentity(callingId);
6653        }
6654    }
6655
6656    public ArraySet<String> getPackagesThatNeedDexOpt() {
6657        ArraySet<String> pkgs = null;
6658        synchronized (mPackages) {
6659            for (PackageParser.Package p : mPackages.values()) {
6660                if (DEBUG_DEXOPT) {
6661                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6662                }
6663                if (!p.mDexOptPerformed.isEmpty()) {
6664                    continue;
6665                }
6666                if (pkgs == null) {
6667                    pkgs = new ArraySet<String>();
6668                }
6669                pkgs.add(p.packageName);
6670            }
6671        }
6672        return pkgs;
6673    }
6674
6675    public void shutdown() {
6676        mPackageUsage.write(true);
6677    }
6678
6679    @Override
6680    public void forceDexOpt(String packageName) {
6681        enforceSystemOrRoot("forceDexOpt");
6682
6683        PackageParser.Package pkg;
6684        synchronized (mPackages) {
6685            pkg = mPackages.get(packageName);
6686            if (pkg == null) {
6687                throw new IllegalArgumentException("Unknown package: " + packageName);
6688            }
6689        }
6690
6691        synchronized (mInstallLock) {
6692            final String[] instructionSets = new String[] {
6693                    getPrimaryInstructionSet(pkg.applicationInfo) };
6694
6695            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6696
6697            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6698                    true /* inclDependencies */);
6699
6700            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6701            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6702                throw new IllegalStateException("Failed to dexopt: " + res);
6703            }
6704        }
6705    }
6706
6707    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6708        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6709            Slog.w(TAG, "Unable to update from " + oldPkg.name
6710                    + " to " + newPkg.packageName
6711                    + ": old package not in system partition");
6712            return false;
6713        } else if (mPackages.get(oldPkg.name) != null) {
6714            Slog.w(TAG, "Unable to update from " + oldPkg.name
6715                    + " to " + newPkg.packageName
6716                    + ": old package still exists");
6717            return false;
6718        }
6719        return true;
6720    }
6721
6722    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6723            throws PackageManagerException {
6724        // TODO: triage flags as part of 26466827
6725        final int appId = UserHandle.getAppId(uid);
6726        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6727
6728        try {
6729            final int[] users = sUserManager.getUserIds();
6730            for (int user : users) {
6731                mInstaller.createAppData(volumeUuid, packageName, user, flags, appId, seinfo);
6732            }
6733        } catch (InstallerException e) {
6734            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6735                    "Failed to prepare data directory", e);
6736        }
6737    }
6738
6739    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6740        // TODO: triage flags as part of 26466827
6741        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6742
6743        boolean res = true;
6744        final int[] users = sUserManager.getUserIds();
6745        for (int user : users) {
6746            try {
6747                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
6748            } catch (InstallerException e) {
6749                Slog.w(TAG, "Failed to delete data directory", e);
6750                res = false;
6751            }
6752        }
6753        return res;
6754    }
6755
6756    void removeCodePathLI(File codePath) {
6757        if (codePath.isDirectory()) {
6758            try {
6759                mInstaller.rmPackageDir(codePath.getAbsolutePath());
6760            } catch (InstallerException e) {
6761                Slog.w(TAG, "Failed to remove code path", e);
6762            }
6763        } else {
6764            codePath.delete();
6765        }
6766    }
6767
6768    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6769        // TODO: triage flags as part of 26466827
6770        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6771
6772        final int[] users = sUserManager.getUserIds();
6773        for (int user : users) {
6774            try {
6775                mInstaller.clearAppData(volumeUuid, packageName, user,
6776                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
6777            } catch (InstallerException e) {
6778                Slog.w(TAG, "Failed to delete code cache directory", e);
6779            }
6780        }
6781    }
6782
6783    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6784            PackageParser.Package changingLib) {
6785        if (file.path != null) {
6786            usesLibraryFiles.add(file.path);
6787            return;
6788        }
6789        PackageParser.Package p = mPackages.get(file.apk);
6790        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6791            // If we are doing this while in the middle of updating a library apk,
6792            // then we need to make sure to use that new apk for determining the
6793            // dependencies here.  (We haven't yet finished committing the new apk
6794            // to the package manager state.)
6795            if (p == null || p.packageName.equals(changingLib.packageName)) {
6796                p = changingLib;
6797            }
6798        }
6799        if (p != null) {
6800            usesLibraryFiles.addAll(p.getAllCodePaths());
6801        }
6802    }
6803
6804    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6805            PackageParser.Package changingLib) throws PackageManagerException {
6806        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6807            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6808            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6809            for (int i=0; i<N; i++) {
6810                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6811                if (file == null) {
6812                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6813                            "Package " + pkg.packageName + " requires unavailable shared library "
6814                            + pkg.usesLibraries.get(i) + "; failing!");
6815                }
6816                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6817            }
6818            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6819            for (int i=0; i<N; i++) {
6820                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6821                if (file == null) {
6822                    Slog.w(TAG, "Package " + pkg.packageName
6823                            + " desires unavailable shared library "
6824                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6825                } else {
6826                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6827                }
6828            }
6829            N = usesLibraryFiles.size();
6830            if (N > 0) {
6831                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6832            } else {
6833                pkg.usesLibraryFiles = null;
6834            }
6835        }
6836    }
6837
6838    private static boolean hasString(List<String> list, List<String> which) {
6839        if (list == null) {
6840            return false;
6841        }
6842        for (int i=list.size()-1; i>=0; i--) {
6843            for (int j=which.size()-1; j>=0; j--) {
6844                if (which.get(j).equals(list.get(i))) {
6845                    return true;
6846                }
6847            }
6848        }
6849        return false;
6850    }
6851
6852    private void updateAllSharedLibrariesLPw() {
6853        for (PackageParser.Package pkg : mPackages.values()) {
6854            try {
6855                updateSharedLibrariesLPw(pkg, null);
6856            } catch (PackageManagerException e) {
6857                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6858            }
6859        }
6860    }
6861
6862    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6863            PackageParser.Package changingPkg) {
6864        ArrayList<PackageParser.Package> res = null;
6865        for (PackageParser.Package pkg : mPackages.values()) {
6866            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6867                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6868                if (res == null) {
6869                    res = new ArrayList<PackageParser.Package>();
6870                }
6871                res.add(pkg);
6872                try {
6873                    updateSharedLibrariesLPw(pkg, changingPkg);
6874                } catch (PackageManagerException e) {
6875                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6876                }
6877            }
6878        }
6879        return res;
6880    }
6881
6882    /**
6883     * Derive the value of the {@code cpuAbiOverride} based on the provided
6884     * value and an optional stored value from the package settings.
6885     */
6886    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6887        String cpuAbiOverride = null;
6888
6889        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6890            cpuAbiOverride = null;
6891        } else if (abiOverride != null) {
6892            cpuAbiOverride = abiOverride;
6893        } else if (settings != null) {
6894            cpuAbiOverride = settings.cpuAbiOverrideString;
6895        }
6896
6897        return cpuAbiOverride;
6898    }
6899
6900    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6901            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6902        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6903        try {
6904            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6905        } finally {
6906            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6907        }
6908    }
6909
6910    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6911            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6912        boolean success = false;
6913        try {
6914            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6915                    currentTime, user);
6916            success = true;
6917            return res;
6918        } finally {
6919            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6920                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6921            }
6922        }
6923    }
6924
6925    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6926            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6927        final File scanFile = new File(pkg.codePath);
6928        if (pkg.applicationInfo.getCodePath() == null ||
6929                pkg.applicationInfo.getResourcePath() == null) {
6930            // Bail out. The resource and code paths haven't been set.
6931            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6932                    "Code and resource paths haven't been set correctly");
6933        }
6934
6935        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6936            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6937        } else {
6938            // Only allow system apps to be flagged as core apps.
6939            pkg.coreApp = false;
6940        }
6941
6942        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6943            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6944        }
6945
6946        if (mCustomResolverComponentName != null &&
6947                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6948            setUpCustomResolverActivity(pkg);
6949        }
6950
6951        if (pkg.packageName.equals("android")) {
6952            synchronized (mPackages) {
6953                if (mAndroidApplication != null) {
6954                    Slog.w(TAG, "*************************************************");
6955                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6956                    Slog.w(TAG, " file=" + scanFile);
6957                    Slog.w(TAG, "*************************************************");
6958                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6959                            "Core android package being redefined.  Skipping.");
6960                }
6961
6962                // Set up information for our fall-back user intent resolution activity.
6963                mPlatformPackage = pkg;
6964                pkg.mVersionCode = mSdkVersion;
6965                mAndroidApplication = pkg.applicationInfo;
6966
6967                if (!mResolverReplaced) {
6968                    mResolveActivity.applicationInfo = mAndroidApplication;
6969                    mResolveActivity.name = ResolverActivity.class.getName();
6970                    mResolveActivity.packageName = mAndroidApplication.packageName;
6971                    mResolveActivity.processName = "system:ui";
6972                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6973                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6974                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6975                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6976                    mResolveActivity.exported = true;
6977                    mResolveActivity.enabled = true;
6978                    mResolveInfo.activityInfo = mResolveActivity;
6979                    mResolveInfo.priority = 0;
6980                    mResolveInfo.preferredOrder = 0;
6981                    mResolveInfo.match = 0;
6982                    mResolveComponentName = new ComponentName(
6983                            mAndroidApplication.packageName, mResolveActivity.name);
6984                }
6985            }
6986        }
6987
6988        if (DEBUG_PACKAGE_SCANNING) {
6989            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6990                Log.d(TAG, "Scanning package " + pkg.packageName);
6991        }
6992
6993        if (mPackages.containsKey(pkg.packageName)
6994                || mSharedLibraries.containsKey(pkg.packageName)) {
6995            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6996                    "Application package " + pkg.packageName
6997                    + " already installed.  Skipping duplicate.");
6998        }
6999
7000        // If we're only installing presumed-existing packages, require that the
7001        // scanned APK is both already known and at the path previously established
7002        // for it.  Previously unknown packages we pick up normally, but if we have an
7003        // a priori expectation about this package's install presence, enforce it.
7004        // With a singular exception for new system packages. When an OTA contains
7005        // a new system package, we allow the codepath to change from a system location
7006        // to the user-installed location. If we don't allow this change, any newer,
7007        // user-installed version of the application will be ignored.
7008        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7009            if (mExpectingBetter.containsKey(pkg.packageName)) {
7010                logCriticalInfo(Log.WARN,
7011                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7012            } else {
7013                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7014                if (known != null) {
7015                    if (DEBUG_PACKAGE_SCANNING) {
7016                        Log.d(TAG, "Examining " + pkg.codePath
7017                                + " and requiring known paths " + known.codePathString
7018                                + " & " + known.resourcePathString);
7019                    }
7020                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7021                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7022                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7023                                "Application package " + pkg.packageName
7024                                + " found at " + pkg.applicationInfo.getCodePath()
7025                                + " but expected at " + known.codePathString + "; ignoring.");
7026                    }
7027                }
7028            }
7029        }
7030
7031        // Initialize package source and resource directories
7032        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7033        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7034
7035        SharedUserSetting suid = null;
7036        PackageSetting pkgSetting = null;
7037
7038        if (!isSystemApp(pkg)) {
7039            // Only system apps can use these features.
7040            pkg.mOriginalPackages = null;
7041            pkg.mRealPackage = null;
7042            pkg.mAdoptPermissions = null;
7043        }
7044
7045        // writer
7046        synchronized (mPackages) {
7047            if (pkg.mSharedUserId != null) {
7048                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7049                if (suid == null) {
7050                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7051                            "Creating application package " + pkg.packageName
7052                            + " for shared user failed");
7053                }
7054                if (DEBUG_PACKAGE_SCANNING) {
7055                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7056                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7057                                + "): packages=" + suid.packages);
7058                }
7059            }
7060
7061            // Check if we are renaming from an original package name.
7062            PackageSetting origPackage = null;
7063            String realName = null;
7064            if (pkg.mOriginalPackages != null) {
7065                // This package may need to be renamed to a previously
7066                // installed name.  Let's check on that...
7067                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7068                if (pkg.mOriginalPackages.contains(renamed)) {
7069                    // This package had originally been installed as the
7070                    // original name, and we have already taken care of
7071                    // transitioning to the new one.  Just update the new
7072                    // one to continue using the old name.
7073                    realName = pkg.mRealPackage;
7074                    if (!pkg.packageName.equals(renamed)) {
7075                        // Callers into this function may have already taken
7076                        // care of renaming the package; only do it here if
7077                        // it is not already done.
7078                        pkg.setPackageName(renamed);
7079                    }
7080
7081                } else {
7082                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7083                        if ((origPackage = mSettings.peekPackageLPr(
7084                                pkg.mOriginalPackages.get(i))) != null) {
7085                            // We do have the package already installed under its
7086                            // original name...  should we use it?
7087                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7088                                // New package is not compatible with original.
7089                                origPackage = null;
7090                                continue;
7091                            } else if (origPackage.sharedUser != null) {
7092                                // Make sure uid is compatible between packages.
7093                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7094                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7095                                            + " to " + pkg.packageName + ": old uid "
7096                                            + origPackage.sharedUser.name
7097                                            + " differs from " + pkg.mSharedUserId);
7098                                    origPackage = null;
7099                                    continue;
7100                                }
7101                            } else {
7102                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7103                                        + pkg.packageName + " to old name " + origPackage.name);
7104                            }
7105                            break;
7106                        }
7107                    }
7108                }
7109            }
7110
7111            if (mTransferedPackages.contains(pkg.packageName)) {
7112                Slog.w(TAG, "Package " + pkg.packageName
7113                        + " was transferred to another, but its .apk remains");
7114            }
7115
7116            // Just create the setting, don't add it yet. For already existing packages
7117            // the PkgSetting exists already and doesn't have to be created.
7118            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7119                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7120                    pkg.applicationInfo.primaryCpuAbi,
7121                    pkg.applicationInfo.secondaryCpuAbi,
7122                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7123                    user, false);
7124            if (pkgSetting == null) {
7125                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7126                        "Creating application package " + pkg.packageName + " failed");
7127            }
7128
7129            if (pkgSetting.origPackage != null) {
7130                // If we are first transitioning from an original package,
7131                // fix up the new package's name now.  We need to do this after
7132                // looking up the package under its new name, so getPackageLP
7133                // can take care of fiddling things correctly.
7134                pkg.setPackageName(origPackage.name);
7135
7136                // File a report about this.
7137                String msg = "New package " + pkgSetting.realName
7138                        + " renamed to replace old package " + pkgSetting.name;
7139                reportSettingsProblem(Log.WARN, msg);
7140
7141                // Make a note of it.
7142                mTransferedPackages.add(origPackage.name);
7143
7144                // No longer need to retain this.
7145                pkgSetting.origPackage = null;
7146            }
7147
7148            if (realName != null) {
7149                // Make a note of it.
7150                mTransferedPackages.add(pkg.packageName);
7151            }
7152
7153            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7154                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7155            }
7156
7157            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7158                // Check all shared libraries and map to their actual file path.
7159                // We only do this here for apps not on a system dir, because those
7160                // are the only ones that can fail an install due to this.  We
7161                // will take care of the system apps by updating all of their
7162                // library paths after the scan is done.
7163                updateSharedLibrariesLPw(pkg, null);
7164            }
7165
7166            if (mFoundPolicyFile) {
7167                SELinuxMMAC.assignSeinfoValue(pkg);
7168            }
7169
7170            pkg.applicationInfo.uid = pkgSetting.appId;
7171            pkg.mExtras = pkgSetting;
7172            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7173                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7174                    // We just determined the app is signed correctly, so bring
7175                    // over the latest parsed certs.
7176                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7177                } else {
7178                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7179                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7180                                "Package " + pkg.packageName + " upgrade keys do not match the "
7181                                + "previously installed version");
7182                    } else {
7183                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7184                        String msg = "System package " + pkg.packageName
7185                            + " signature changed; retaining data.";
7186                        reportSettingsProblem(Log.WARN, msg);
7187                    }
7188                }
7189            } else {
7190                try {
7191                    verifySignaturesLP(pkgSetting, pkg);
7192                    // We just determined the app is signed correctly, so bring
7193                    // over the latest parsed certs.
7194                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7195                } catch (PackageManagerException e) {
7196                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7197                        throw e;
7198                    }
7199                    // The signature has changed, but this package is in the system
7200                    // image...  let's recover!
7201                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7202                    // However...  if this package is part of a shared user, but it
7203                    // doesn't match the signature of the shared user, let's fail.
7204                    // What this means is that you can't change the signatures
7205                    // associated with an overall shared user, which doesn't seem all
7206                    // that unreasonable.
7207                    if (pkgSetting.sharedUser != null) {
7208                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7209                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7210                            throw new PackageManagerException(
7211                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7212                                            "Signature mismatch for shared user: "
7213                                            + pkgSetting.sharedUser);
7214                        }
7215                    }
7216                    // File a report about this.
7217                    String msg = "System package " + pkg.packageName
7218                        + " signature changed; retaining data.";
7219                    reportSettingsProblem(Log.WARN, msg);
7220                }
7221            }
7222            // Verify that this new package doesn't have any content providers
7223            // that conflict with existing packages.  Only do this if the
7224            // package isn't already installed, since we don't want to break
7225            // things that are installed.
7226            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7227                final int N = pkg.providers.size();
7228                int i;
7229                for (i=0; i<N; i++) {
7230                    PackageParser.Provider p = pkg.providers.get(i);
7231                    if (p.info.authority != null) {
7232                        String names[] = p.info.authority.split(";");
7233                        for (int j = 0; j < names.length; j++) {
7234                            if (mProvidersByAuthority.containsKey(names[j])) {
7235                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7236                                final String otherPackageName =
7237                                        ((other != null && other.getComponentName() != null) ?
7238                                                other.getComponentName().getPackageName() : "?");
7239                                throw new PackageManagerException(
7240                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7241                                                "Can't install because provider name " + names[j]
7242                                                + " (in package " + pkg.applicationInfo.packageName
7243                                                + ") is already used by " + otherPackageName);
7244                            }
7245                        }
7246                    }
7247                }
7248            }
7249
7250            if (pkg.mAdoptPermissions != null) {
7251                // This package wants to adopt ownership of permissions from
7252                // another package.
7253                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7254                    final String origName = pkg.mAdoptPermissions.get(i);
7255                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7256                    if (orig != null) {
7257                        if (verifyPackageUpdateLPr(orig, pkg)) {
7258                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7259                                    + pkg.packageName);
7260                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7261                        }
7262                    }
7263                }
7264            }
7265        }
7266
7267        final String pkgName = pkg.packageName;
7268
7269        final long scanFileTime = scanFile.lastModified();
7270        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7271        pkg.applicationInfo.processName = fixProcessName(
7272                pkg.applicationInfo.packageName,
7273                pkg.applicationInfo.processName,
7274                pkg.applicationInfo.uid);
7275
7276        if (pkg != mPlatformPackage) {
7277            // This is a normal package, need to make its data directory.
7278            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7279                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7280
7281            // TOOD: switch to ensure various directories
7282
7283            boolean uidError = false;
7284            if (dataPath.exists()) {
7285                int currentUid = 0;
7286                try {
7287                    StructStat stat = Os.stat(dataPath.getPath());
7288                    currentUid = stat.st_uid;
7289                } catch (ErrnoException e) {
7290                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7291                }
7292
7293                // If we have mismatched owners for the data path, we have a problem.
7294                if (currentUid != pkg.applicationInfo.uid) {
7295                    boolean recovered = false;
7296                    if (((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0
7297                            || (scanFlags & SCAN_BOOTING) != 0)) {
7298                        // If this is a system app, we can at least delete its
7299                        // current data so the application will still work.
7300                        boolean res = removeDataDirsLI(pkg.volumeUuid, pkgName);
7301                        if (res) {
7302                            // TODO: Kill the processes first
7303                            // Old data gone!
7304                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7305                                    ? "System package " : "Third party package ";
7306                            String msg = prefix + pkg.packageName
7307                                    + " has changed from uid: "
7308                                    + currentUid + " to "
7309                                    + pkg.applicationInfo.uid + "; old data erased";
7310                            reportSettingsProblem(Log.WARN, msg);
7311                            recovered = true;
7312                        }
7313                        if (!recovered) {
7314                            mHasSystemUidErrors = true;
7315                        }
7316                    } else {
7317                        // If we allow this install to proceed, we will be broken.
7318                        // Abort, abort!
7319                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7320                                "Expected data to be owned by UID " + pkg.applicationInfo.uid
7321                                        + " but found " + currentUid);
7322                    }
7323                    if (!recovered) {
7324                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7325                            + pkg.applicationInfo.uid + "/fs_"
7326                            + currentUid;
7327                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7328                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7329                        String msg = "Package " + pkg.packageName
7330                                + " has mismatched uid: "
7331                                + currentUid + " on disk, "
7332                                + pkg.applicationInfo.uid + " in settings";
7333                        // writer
7334                        synchronized (mPackages) {
7335                            mSettings.mReadMessages.append(msg);
7336                            mSettings.mReadMessages.append('\n');
7337                            uidError = true;
7338                            if (!pkgSetting.uidError) {
7339                                reportSettingsProblem(Log.ERROR, msg);
7340                            }
7341                        }
7342                    }
7343                }
7344
7345                // Ensure that directories are prepared
7346                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7347                        pkg.applicationInfo.seinfo);
7348
7349                if (mShouldRestoreconData) {
7350                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7351                    // TODO: extend this to restorecon over all users
7352                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
7353                    // TODO: triage flags as part of 26466827
7354                    final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
7355                    try {
7356                        mInstaller.restoreconAppData(pkg.volumeUuid, pkg.packageName,
7357                                UserHandle.USER_SYSTEM, flags, appId, pkg.applicationInfo.seinfo);
7358                    } catch (InstallerException e) {
7359                        Slog.w(TAG, "Failed to restorecon " + pkg.packageName, e);
7360                    }
7361                }
7362            } else {
7363                if (DEBUG_PACKAGE_SCANNING) {
7364                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7365                        Log.v(TAG, "Want this data dir: " + dataPath);
7366                }
7367                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7368                        pkg.applicationInfo.seinfo);
7369            }
7370
7371            // Get all of our default paths setup
7372            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7373
7374            pkgSetting.uidError = uidError;
7375        }
7376
7377        final String path = scanFile.getPath();
7378        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7379
7380        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7381            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7382
7383            // Some system apps still use directory structure for native libraries
7384            // in which case we might end up not detecting abi solely based on apk
7385            // structure. Try to detect abi based on directory structure.
7386            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7387                    pkg.applicationInfo.primaryCpuAbi == null) {
7388                setBundledAppAbisAndRoots(pkg, pkgSetting);
7389                setNativeLibraryPaths(pkg);
7390            }
7391
7392        } else {
7393            if ((scanFlags & SCAN_MOVE) != 0) {
7394                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7395                // but we already have this packages package info in the PackageSetting. We just
7396                // use that and derive the native library path based on the new codepath.
7397                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7398                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7399            }
7400
7401            // Set native library paths again. For moves, the path will be updated based on the
7402            // ABIs we've determined above. For non-moves, the path will be updated based on the
7403            // ABIs we determined during compilation, but the path will depend on the final
7404            // package path (after the rename away from the stage path).
7405            setNativeLibraryPaths(pkg);
7406        }
7407
7408        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7409        final int[] userIds = sUserManager.getUserIds();
7410        synchronized (mInstallLock) {
7411            // Make sure all user data directories are ready to roll; we're okay
7412            // if they already exist
7413            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7414                for (int userId : userIds) {
7415                    if (userId != UserHandle.USER_SYSTEM) {
7416                        // TODO: triage flags as part of 26466827
7417                        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
7418                        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
7419                        try {
7420                            mInstaller.createAppData(pkg.volumeUuid, pkg.packageName, userId,
7421                                    flags, appId, pkg.applicationInfo.seinfo);
7422                        } catch (InstallerException e) {
7423                            throw PackageManagerException.from(e);
7424                        }
7425                    }
7426                }
7427            }
7428
7429            // Create a native library symlink only if we have native libraries
7430            // and if the native libraries are 32 bit libraries. We do not provide
7431            // this symlink for 64 bit libraries.
7432            if (pkg.applicationInfo.primaryCpuAbi != null &&
7433                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7434                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7435                try {
7436                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7437                    for (int userId : userIds) {
7438                        try {
7439                            mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7440                                    nativeLibPath, userId);
7441                        } catch (InstallerException e) {
7442                            throw PackageManagerException.from(e);
7443                        }
7444                    }
7445                } finally {
7446                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7447                }
7448            }
7449        }
7450
7451        // This is a special case for the "system" package, where the ABI is
7452        // dictated by the zygote configuration (and init.rc). We should keep track
7453        // of this ABI so that we can deal with "normal" applications that run under
7454        // the same UID correctly.
7455        if (mPlatformPackage == pkg) {
7456            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7457                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7458        }
7459
7460        // If there's a mismatch between the abi-override in the package setting
7461        // and the abiOverride specified for the install. Warn about this because we
7462        // would've already compiled the app without taking the package setting into
7463        // account.
7464        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7465            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7466                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7467                        " for package " + pkg.packageName);
7468            }
7469        }
7470
7471        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7472        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7473        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7474
7475        // Copy the derived override back to the parsed package, so that we can
7476        // update the package settings accordingly.
7477        pkg.cpuAbiOverride = cpuAbiOverride;
7478
7479        if (DEBUG_ABI_SELECTION) {
7480            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7481                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7482                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7483        }
7484
7485        // Push the derived path down into PackageSettings so we know what to
7486        // clean up at uninstall time.
7487        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7488
7489        if (DEBUG_ABI_SELECTION) {
7490            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7491                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7492                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7493        }
7494
7495        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7496            // We don't do this here during boot because we can do it all
7497            // at once after scanning all existing packages.
7498            //
7499            // We also do this *before* we perform dexopt on this package, so that
7500            // we can avoid redundant dexopts, and also to make sure we've got the
7501            // code and package path correct.
7502            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7503                    pkg, true /* boot complete */);
7504        }
7505
7506        if (mFactoryTest && pkg.requestedPermissions.contains(
7507                android.Manifest.permission.FACTORY_TEST)) {
7508            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7509        }
7510
7511        ArrayList<PackageParser.Package> clientLibPkgs = null;
7512
7513        // writer
7514        synchronized (mPackages) {
7515            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7516                // Only system apps can add new shared libraries.
7517                if (pkg.libraryNames != null) {
7518                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7519                        String name = pkg.libraryNames.get(i);
7520                        boolean allowed = false;
7521                        if (pkg.isUpdatedSystemApp()) {
7522                            // New library entries can only be added through the
7523                            // system image.  This is important to get rid of a lot
7524                            // of nasty edge cases: for example if we allowed a non-
7525                            // system update of the app to add a library, then uninstalling
7526                            // the update would make the library go away, and assumptions
7527                            // we made such as through app install filtering would now
7528                            // have allowed apps on the device which aren't compatible
7529                            // with it.  Better to just have the restriction here, be
7530                            // conservative, and create many fewer cases that can negatively
7531                            // impact the user experience.
7532                            final PackageSetting sysPs = mSettings
7533                                    .getDisabledSystemPkgLPr(pkg.packageName);
7534                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7535                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7536                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7537                                        allowed = true;
7538                                        break;
7539                                    }
7540                                }
7541                            }
7542                        } else {
7543                            allowed = true;
7544                        }
7545                        if (allowed) {
7546                            if (!mSharedLibraries.containsKey(name)) {
7547                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7548                            } else if (!name.equals(pkg.packageName)) {
7549                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7550                                        + name + " already exists; skipping");
7551                            }
7552                        } else {
7553                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7554                                    + name + " that is not declared on system image; skipping");
7555                        }
7556                    }
7557                    if ((scanFlags & SCAN_BOOTING) == 0) {
7558                        // If we are not booting, we need to update any applications
7559                        // that are clients of our shared library.  If we are booting,
7560                        // this will all be done once the scan is complete.
7561                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7562                    }
7563                }
7564            }
7565        }
7566
7567        // Request the ActivityManager to kill the process(only for existing packages)
7568        // so that we do not end up in a confused state while the user is still using the older
7569        // version of the application while the new one gets installed.
7570        if ((scanFlags & SCAN_REPLACING) != 0) {
7571            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7572
7573            killApplication(pkg.applicationInfo.packageName,
7574                        pkg.applicationInfo.uid, "replace pkg");
7575
7576            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7577        }
7578
7579        // Also need to kill any apps that are dependent on the library.
7580        if (clientLibPkgs != null) {
7581            for (int i=0; i<clientLibPkgs.size(); i++) {
7582                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7583                killApplication(clientPkg.applicationInfo.packageName,
7584                        clientPkg.applicationInfo.uid, "update lib");
7585            }
7586        }
7587
7588        // Make sure we're not adding any bogus keyset info
7589        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7590        ksms.assertScannedPackageValid(pkg);
7591
7592        // writer
7593        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7594
7595        boolean createIdmapFailed = false;
7596        synchronized (mPackages) {
7597            // We don't expect installation to fail beyond this point
7598
7599            // Add the new setting to mSettings
7600            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7601            // Add the new setting to mPackages
7602            mPackages.put(pkg.applicationInfo.packageName, pkg);
7603            // Make sure we don't accidentally delete its data.
7604            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7605            while (iter.hasNext()) {
7606                PackageCleanItem item = iter.next();
7607                if (pkgName.equals(item.packageName)) {
7608                    iter.remove();
7609                }
7610            }
7611
7612            // Take care of first install / last update times.
7613            if (currentTime != 0) {
7614                if (pkgSetting.firstInstallTime == 0) {
7615                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7616                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7617                    pkgSetting.lastUpdateTime = currentTime;
7618                }
7619            } else if (pkgSetting.firstInstallTime == 0) {
7620                // We need *something*.  Take time time stamp of the file.
7621                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7622            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7623                if (scanFileTime != pkgSetting.timeStamp) {
7624                    // A package on the system image has changed; consider this
7625                    // to be an update.
7626                    pkgSetting.lastUpdateTime = scanFileTime;
7627                }
7628            }
7629
7630            // Add the package's KeySets to the global KeySetManagerService
7631            ksms.addScannedPackageLPw(pkg);
7632
7633            int N = pkg.providers.size();
7634            StringBuilder r = null;
7635            int i;
7636            for (i=0; i<N; i++) {
7637                PackageParser.Provider p = pkg.providers.get(i);
7638                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7639                        p.info.processName, pkg.applicationInfo.uid);
7640                mProviders.addProvider(p);
7641                p.syncable = p.info.isSyncable;
7642                if (p.info.authority != null) {
7643                    String names[] = p.info.authority.split(";");
7644                    p.info.authority = null;
7645                    for (int j = 0; j < names.length; j++) {
7646                        if (j == 1 && p.syncable) {
7647                            // We only want the first authority for a provider to possibly be
7648                            // syncable, so if we already added this provider using a different
7649                            // authority clear the syncable flag. We copy the provider before
7650                            // changing it because the mProviders object contains a reference
7651                            // to a provider that we don't want to change.
7652                            // Only do this for the second authority since the resulting provider
7653                            // object can be the same for all future authorities for this provider.
7654                            p = new PackageParser.Provider(p);
7655                            p.syncable = false;
7656                        }
7657                        if (!mProvidersByAuthority.containsKey(names[j])) {
7658                            mProvidersByAuthority.put(names[j], p);
7659                            if (p.info.authority == null) {
7660                                p.info.authority = names[j];
7661                            } else {
7662                                p.info.authority = p.info.authority + ";" + names[j];
7663                            }
7664                            if (DEBUG_PACKAGE_SCANNING) {
7665                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7666                                    Log.d(TAG, "Registered content provider: " + names[j]
7667                                            + ", className = " + p.info.name + ", isSyncable = "
7668                                            + p.info.isSyncable);
7669                            }
7670                        } else {
7671                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7672                            Slog.w(TAG, "Skipping provider name " + names[j] +
7673                                    " (in package " + pkg.applicationInfo.packageName +
7674                                    "): name already used by "
7675                                    + ((other != null && other.getComponentName() != null)
7676                                            ? other.getComponentName().getPackageName() : "?"));
7677                        }
7678                    }
7679                }
7680                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7681                    if (r == null) {
7682                        r = new StringBuilder(256);
7683                    } else {
7684                        r.append(' ');
7685                    }
7686                    r.append(p.info.name);
7687                }
7688            }
7689            if (r != null) {
7690                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7691            }
7692
7693            N = pkg.services.size();
7694            r = null;
7695            for (i=0; i<N; i++) {
7696                PackageParser.Service s = pkg.services.get(i);
7697                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7698                        s.info.processName, pkg.applicationInfo.uid);
7699                mServices.addService(s);
7700                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7701                    if (r == null) {
7702                        r = new StringBuilder(256);
7703                    } else {
7704                        r.append(' ');
7705                    }
7706                    r.append(s.info.name);
7707                }
7708            }
7709            if (r != null) {
7710                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7711            }
7712
7713            N = pkg.receivers.size();
7714            r = null;
7715            for (i=0; i<N; i++) {
7716                PackageParser.Activity a = pkg.receivers.get(i);
7717                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7718                        a.info.processName, pkg.applicationInfo.uid);
7719                mReceivers.addActivity(a, "receiver");
7720                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7721                    if (r == null) {
7722                        r = new StringBuilder(256);
7723                    } else {
7724                        r.append(' ');
7725                    }
7726                    r.append(a.info.name);
7727                }
7728            }
7729            if (r != null) {
7730                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7731            }
7732
7733            N = pkg.activities.size();
7734            r = null;
7735            for (i=0; i<N; i++) {
7736                PackageParser.Activity a = pkg.activities.get(i);
7737                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7738                        a.info.processName, pkg.applicationInfo.uid);
7739                mActivities.addActivity(a, "activity");
7740                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7741                    if (r == null) {
7742                        r = new StringBuilder(256);
7743                    } else {
7744                        r.append(' ');
7745                    }
7746                    r.append(a.info.name);
7747                }
7748            }
7749            if (r != null) {
7750                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7751            }
7752
7753            N = pkg.permissionGroups.size();
7754            r = null;
7755            for (i=0; i<N; i++) {
7756                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7757                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7758                if (cur == null) {
7759                    mPermissionGroups.put(pg.info.name, pg);
7760                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7761                        if (r == null) {
7762                            r = new StringBuilder(256);
7763                        } else {
7764                            r.append(' ');
7765                        }
7766                        r.append(pg.info.name);
7767                    }
7768                } else {
7769                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7770                            + pg.info.packageName + " ignored: original from "
7771                            + cur.info.packageName);
7772                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7773                        if (r == null) {
7774                            r = new StringBuilder(256);
7775                        } else {
7776                            r.append(' ');
7777                        }
7778                        r.append("DUP:");
7779                        r.append(pg.info.name);
7780                    }
7781                }
7782            }
7783            if (r != null) {
7784                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7785            }
7786
7787            N = pkg.permissions.size();
7788            r = null;
7789            for (i=0; i<N; i++) {
7790                PackageParser.Permission p = pkg.permissions.get(i);
7791
7792                // Assume by default that we did not install this permission into the system.
7793                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7794
7795                // Now that permission groups have a special meaning, we ignore permission
7796                // groups for legacy apps to prevent unexpected behavior. In particular,
7797                // permissions for one app being granted to someone just becuase they happen
7798                // to be in a group defined by another app (before this had no implications).
7799                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7800                    p.group = mPermissionGroups.get(p.info.group);
7801                    // Warn for a permission in an unknown group.
7802                    if (p.info.group != null && p.group == null) {
7803                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7804                                + p.info.packageName + " in an unknown group " + p.info.group);
7805                    }
7806                }
7807
7808                ArrayMap<String, BasePermission> permissionMap =
7809                        p.tree ? mSettings.mPermissionTrees
7810                                : mSettings.mPermissions;
7811                BasePermission bp = permissionMap.get(p.info.name);
7812
7813                // Allow system apps to redefine non-system permissions
7814                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7815                    final boolean currentOwnerIsSystem = (bp.perm != null
7816                            && isSystemApp(bp.perm.owner));
7817                    if (isSystemApp(p.owner)) {
7818                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7819                            // It's a built-in permission and no owner, take ownership now
7820                            bp.packageSetting = pkgSetting;
7821                            bp.perm = p;
7822                            bp.uid = pkg.applicationInfo.uid;
7823                            bp.sourcePackage = p.info.packageName;
7824                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7825                        } else if (!currentOwnerIsSystem) {
7826                            String msg = "New decl " + p.owner + " of permission  "
7827                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7828                            reportSettingsProblem(Log.WARN, msg);
7829                            bp = null;
7830                        }
7831                    }
7832                }
7833
7834                if (bp == null) {
7835                    bp = new BasePermission(p.info.name, p.info.packageName,
7836                            BasePermission.TYPE_NORMAL);
7837                    permissionMap.put(p.info.name, bp);
7838                }
7839
7840                if (bp.perm == null) {
7841                    if (bp.sourcePackage == null
7842                            || bp.sourcePackage.equals(p.info.packageName)) {
7843                        BasePermission tree = findPermissionTreeLP(p.info.name);
7844                        if (tree == null
7845                                || tree.sourcePackage.equals(p.info.packageName)) {
7846                            bp.packageSetting = pkgSetting;
7847                            bp.perm = p;
7848                            bp.uid = pkg.applicationInfo.uid;
7849                            bp.sourcePackage = p.info.packageName;
7850                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7851                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7852                                if (r == null) {
7853                                    r = new StringBuilder(256);
7854                                } else {
7855                                    r.append(' ');
7856                                }
7857                                r.append(p.info.name);
7858                            }
7859                        } else {
7860                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7861                                    + p.info.packageName + " ignored: base tree "
7862                                    + tree.name + " is from package "
7863                                    + tree.sourcePackage);
7864                        }
7865                    } else {
7866                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7867                                + p.info.packageName + " ignored: original from "
7868                                + bp.sourcePackage);
7869                    }
7870                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7871                    if (r == null) {
7872                        r = new StringBuilder(256);
7873                    } else {
7874                        r.append(' ');
7875                    }
7876                    r.append("DUP:");
7877                    r.append(p.info.name);
7878                }
7879                if (bp.perm == p) {
7880                    bp.protectionLevel = p.info.protectionLevel;
7881                }
7882            }
7883
7884            if (r != null) {
7885                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7886            }
7887
7888            N = pkg.instrumentation.size();
7889            r = null;
7890            for (i=0; i<N; i++) {
7891                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7892                a.info.packageName = pkg.applicationInfo.packageName;
7893                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7894                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7895                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7896                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7897                a.info.dataDir = pkg.applicationInfo.dataDir;
7898                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7899                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7900
7901                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7902                // need other information about the application, like the ABI and what not ?
7903                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7904                mInstrumentation.put(a.getComponentName(), a);
7905                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7906                    if (r == null) {
7907                        r = new StringBuilder(256);
7908                    } else {
7909                        r.append(' ');
7910                    }
7911                    r.append(a.info.name);
7912                }
7913            }
7914            if (r != null) {
7915                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7916            }
7917
7918            if (pkg.protectedBroadcasts != null) {
7919                N = pkg.protectedBroadcasts.size();
7920                for (i=0; i<N; i++) {
7921                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7922                }
7923            }
7924
7925            pkgSetting.setTimeStamp(scanFileTime);
7926
7927            // Create idmap files for pairs of (packages, overlay packages).
7928            // Note: "android", ie framework-res.apk, is handled by native layers.
7929            if (pkg.mOverlayTarget != null) {
7930                // This is an overlay package.
7931                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7932                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7933                        mOverlays.put(pkg.mOverlayTarget,
7934                                new ArrayMap<String, PackageParser.Package>());
7935                    }
7936                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7937                    map.put(pkg.packageName, pkg);
7938                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7939                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7940                        createIdmapFailed = true;
7941                    }
7942                }
7943            } else if (mOverlays.containsKey(pkg.packageName) &&
7944                    !pkg.packageName.equals("android")) {
7945                // This is a regular package, with one or more known overlay packages.
7946                createIdmapsForPackageLI(pkg);
7947            }
7948        }
7949
7950        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7951
7952        if (createIdmapFailed) {
7953            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7954                    "scanPackageLI failed to createIdmap");
7955        }
7956        return pkg;
7957    }
7958
7959    /**
7960     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7961     * is derived purely on the basis of the contents of {@code scanFile} and
7962     * {@code cpuAbiOverride}.
7963     *
7964     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7965     */
7966    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7967                                 String cpuAbiOverride, boolean extractLibs)
7968            throws PackageManagerException {
7969        // TODO: We can probably be smarter about this stuff. For installed apps,
7970        // we can calculate this information at install time once and for all. For
7971        // system apps, we can probably assume that this information doesn't change
7972        // after the first boot scan. As things stand, we do lots of unnecessary work.
7973
7974        // Give ourselves some initial paths; we'll come back for another
7975        // pass once we've determined ABI below.
7976        setNativeLibraryPaths(pkg);
7977
7978        // We would never need to extract libs for forward-locked and external packages,
7979        // since the container service will do it for us. We shouldn't attempt to
7980        // extract libs from system app when it was not updated.
7981        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7982                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7983            extractLibs = false;
7984        }
7985
7986        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7987        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7988
7989        NativeLibraryHelper.Handle handle = null;
7990        try {
7991            handle = NativeLibraryHelper.Handle.create(pkg);
7992            // TODO(multiArch): This can be null for apps that didn't go through the
7993            // usual installation process. We can calculate it again, like we
7994            // do during install time.
7995            //
7996            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7997            // unnecessary.
7998            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7999
8000            // Null out the abis so that they can be recalculated.
8001            pkg.applicationInfo.primaryCpuAbi = null;
8002            pkg.applicationInfo.secondaryCpuAbi = null;
8003            if (isMultiArch(pkg.applicationInfo)) {
8004                // Warn if we've set an abiOverride for multi-lib packages..
8005                // By definition, we need to copy both 32 and 64 bit libraries for
8006                // such packages.
8007                if (pkg.cpuAbiOverride != null
8008                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8009                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8010                }
8011
8012                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8013                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8014                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8015                    if (extractLibs) {
8016                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8017                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8018                                useIsaSpecificSubdirs);
8019                    } else {
8020                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8021                    }
8022                }
8023
8024                maybeThrowExceptionForMultiArchCopy(
8025                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8026
8027                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8028                    if (extractLibs) {
8029                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8030                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8031                                useIsaSpecificSubdirs);
8032                    } else {
8033                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8034                    }
8035                }
8036
8037                maybeThrowExceptionForMultiArchCopy(
8038                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8039
8040                if (abi64 >= 0) {
8041                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8042                }
8043
8044                if (abi32 >= 0) {
8045                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8046                    if (abi64 >= 0) {
8047                        pkg.applicationInfo.secondaryCpuAbi = abi;
8048                    } else {
8049                        pkg.applicationInfo.primaryCpuAbi = abi;
8050                    }
8051                }
8052            } else {
8053                String[] abiList = (cpuAbiOverride != null) ?
8054                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8055
8056                // Enable gross and lame hacks for apps that are built with old
8057                // SDK tools. We must scan their APKs for renderscript bitcode and
8058                // not launch them if it's present. Don't bother checking on devices
8059                // that don't have 64 bit support.
8060                boolean needsRenderScriptOverride = false;
8061                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8062                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8063                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8064                    needsRenderScriptOverride = true;
8065                }
8066
8067                final int copyRet;
8068                if (extractLibs) {
8069                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8070                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8071                } else {
8072                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8073                }
8074
8075                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8076                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8077                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8078                }
8079
8080                if (copyRet >= 0) {
8081                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8082                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8083                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8084                } else if (needsRenderScriptOverride) {
8085                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8086                }
8087            }
8088        } catch (IOException ioe) {
8089            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8090        } finally {
8091            IoUtils.closeQuietly(handle);
8092        }
8093
8094        // Now that we've calculated the ABIs and determined if it's an internal app,
8095        // we will go ahead and populate the nativeLibraryPath.
8096        setNativeLibraryPaths(pkg);
8097    }
8098
8099    /**
8100     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8101     * i.e, so that all packages can be run inside a single process if required.
8102     *
8103     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8104     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8105     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8106     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8107     * updating a package that belongs to a shared user.
8108     *
8109     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8110     * adds unnecessary complexity.
8111     */
8112    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8113            PackageParser.Package scannedPackage, boolean bootComplete) {
8114        String requiredInstructionSet = null;
8115        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8116            requiredInstructionSet = VMRuntime.getInstructionSet(
8117                     scannedPackage.applicationInfo.primaryCpuAbi);
8118        }
8119
8120        PackageSetting requirer = null;
8121        for (PackageSetting ps : packagesForUser) {
8122            // If packagesForUser contains scannedPackage, we skip it. This will happen
8123            // when scannedPackage is an update of an existing package. Without this check,
8124            // we will never be able to change the ABI of any package belonging to a shared
8125            // user, even if it's compatible with other packages.
8126            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8127                if (ps.primaryCpuAbiString == null) {
8128                    continue;
8129                }
8130
8131                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8132                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8133                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8134                    // this but there's not much we can do.
8135                    String errorMessage = "Instruction set mismatch, "
8136                            + ((requirer == null) ? "[caller]" : requirer)
8137                            + " requires " + requiredInstructionSet + " whereas " + ps
8138                            + " requires " + instructionSet;
8139                    Slog.w(TAG, errorMessage);
8140                }
8141
8142                if (requiredInstructionSet == null) {
8143                    requiredInstructionSet = instructionSet;
8144                    requirer = ps;
8145                }
8146            }
8147        }
8148
8149        if (requiredInstructionSet != null) {
8150            String adjustedAbi;
8151            if (requirer != null) {
8152                // requirer != null implies that either scannedPackage was null or that scannedPackage
8153                // did not require an ABI, in which case we have to adjust scannedPackage to match
8154                // the ABI of the set (which is the same as requirer's ABI)
8155                adjustedAbi = requirer.primaryCpuAbiString;
8156                if (scannedPackage != null) {
8157                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8158                }
8159            } else {
8160                // requirer == null implies that we're updating all ABIs in the set to
8161                // match scannedPackage.
8162                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8163            }
8164
8165            for (PackageSetting ps : packagesForUser) {
8166                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8167                    if (ps.primaryCpuAbiString != null) {
8168                        continue;
8169                    }
8170
8171                    ps.primaryCpuAbiString = adjustedAbi;
8172                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8173                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8174                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi);
8175                        try {
8176                            mInstaller.rmdex(ps.codePathString,
8177                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8178                        } catch (InstallerException ignored) {
8179                        }
8180                    }
8181                }
8182            }
8183        }
8184    }
8185
8186    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8187        synchronized (mPackages) {
8188            mResolverReplaced = true;
8189            // Set up information for custom user intent resolution activity.
8190            mResolveActivity.applicationInfo = pkg.applicationInfo;
8191            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8192            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8193            mResolveActivity.processName = pkg.applicationInfo.packageName;
8194            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8195            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8196                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8197            mResolveActivity.theme = 0;
8198            mResolveActivity.exported = true;
8199            mResolveActivity.enabled = true;
8200            mResolveInfo.activityInfo = mResolveActivity;
8201            mResolveInfo.priority = 0;
8202            mResolveInfo.preferredOrder = 0;
8203            mResolveInfo.match = 0;
8204            mResolveComponentName = mCustomResolverComponentName;
8205            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8206                    mResolveComponentName);
8207        }
8208    }
8209
8210    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8211        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8212
8213        // Set up information for ephemeral installer activity
8214        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8215        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8216        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8217        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8218        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8219        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8220                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8221        mEphemeralInstallerActivity.theme = 0;
8222        mEphemeralInstallerActivity.exported = true;
8223        mEphemeralInstallerActivity.enabled = true;
8224        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8225        mEphemeralInstallerInfo.priority = 0;
8226        mEphemeralInstallerInfo.preferredOrder = 0;
8227        mEphemeralInstallerInfo.match = 0;
8228
8229        if (DEBUG_EPHEMERAL) {
8230            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8231        }
8232    }
8233
8234    private static String calculateBundledApkRoot(final String codePathString) {
8235        final File codePath = new File(codePathString);
8236        final File codeRoot;
8237        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8238            codeRoot = Environment.getRootDirectory();
8239        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8240            codeRoot = Environment.getOemDirectory();
8241        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8242            codeRoot = Environment.getVendorDirectory();
8243        } else {
8244            // Unrecognized code path; take its top real segment as the apk root:
8245            // e.g. /something/app/blah.apk => /something
8246            try {
8247                File f = codePath.getCanonicalFile();
8248                File parent = f.getParentFile();    // non-null because codePath is a file
8249                File tmp;
8250                while ((tmp = parent.getParentFile()) != null) {
8251                    f = parent;
8252                    parent = tmp;
8253                }
8254                codeRoot = f;
8255                Slog.w(TAG, "Unrecognized code path "
8256                        + codePath + " - using " + codeRoot);
8257            } catch (IOException e) {
8258                // Can't canonicalize the code path -- shenanigans?
8259                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8260                return Environment.getRootDirectory().getPath();
8261            }
8262        }
8263        return codeRoot.getPath();
8264    }
8265
8266    /**
8267     * Derive and set the location of native libraries for the given package,
8268     * which varies depending on where and how the package was installed.
8269     */
8270    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8271        final ApplicationInfo info = pkg.applicationInfo;
8272        final String codePath = pkg.codePath;
8273        final File codeFile = new File(codePath);
8274        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8275        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8276
8277        info.nativeLibraryRootDir = null;
8278        info.nativeLibraryRootRequiresIsa = false;
8279        info.nativeLibraryDir = null;
8280        info.secondaryNativeLibraryDir = null;
8281
8282        if (isApkFile(codeFile)) {
8283            // Monolithic install
8284            if (bundledApp) {
8285                // If "/system/lib64/apkname" exists, assume that is the per-package
8286                // native library directory to use; otherwise use "/system/lib/apkname".
8287                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8288                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8289                        getPrimaryInstructionSet(info));
8290
8291                // This is a bundled system app so choose the path based on the ABI.
8292                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8293                // is just the default path.
8294                final String apkName = deriveCodePathName(codePath);
8295                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8296                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8297                        apkName).getAbsolutePath();
8298
8299                if (info.secondaryCpuAbi != null) {
8300                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8301                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8302                            secondaryLibDir, apkName).getAbsolutePath();
8303                }
8304            } else if (asecApp) {
8305                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8306                        .getAbsolutePath();
8307            } else {
8308                final String apkName = deriveCodePathName(codePath);
8309                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8310                        .getAbsolutePath();
8311            }
8312
8313            info.nativeLibraryRootRequiresIsa = false;
8314            info.nativeLibraryDir = info.nativeLibraryRootDir;
8315        } else {
8316            // Cluster install
8317            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8318            info.nativeLibraryRootRequiresIsa = true;
8319
8320            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8321                    getPrimaryInstructionSet(info)).getAbsolutePath();
8322
8323            if (info.secondaryCpuAbi != null) {
8324                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8325                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8326            }
8327        }
8328    }
8329
8330    /**
8331     * Calculate the abis and roots for a bundled app. These can uniquely
8332     * be determined from the contents of the system partition, i.e whether
8333     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8334     * of this information, and instead assume that the system was built
8335     * sensibly.
8336     */
8337    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8338                                           PackageSetting pkgSetting) {
8339        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8340
8341        // If "/system/lib64/apkname" exists, assume that is the per-package
8342        // native library directory to use; otherwise use "/system/lib/apkname".
8343        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8344        setBundledAppAbi(pkg, apkRoot, apkName);
8345        // pkgSetting might be null during rescan following uninstall of updates
8346        // to a bundled app, so accommodate that possibility.  The settings in
8347        // that case will be established later from the parsed package.
8348        //
8349        // If the settings aren't null, sync them up with what we've just derived.
8350        // note that apkRoot isn't stored in the package settings.
8351        if (pkgSetting != null) {
8352            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8353            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8354        }
8355    }
8356
8357    /**
8358     * Deduces the ABI of a bundled app and sets the relevant fields on the
8359     * parsed pkg object.
8360     *
8361     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8362     *        under which system libraries are installed.
8363     * @param apkName the name of the installed package.
8364     */
8365    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8366        final File codeFile = new File(pkg.codePath);
8367
8368        final boolean has64BitLibs;
8369        final boolean has32BitLibs;
8370        if (isApkFile(codeFile)) {
8371            // Monolithic install
8372            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8373            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8374        } else {
8375            // Cluster install
8376            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8377            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8378                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8379                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8380                has64BitLibs = (new File(rootDir, isa)).exists();
8381            } else {
8382                has64BitLibs = false;
8383            }
8384            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8385                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8386                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8387                has32BitLibs = (new File(rootDir, isa)).exists();
8388            } else {
8389                has32BitLibs = false;
8390            }
8391        }
8392
8393        if (has64BitLibs && !has32BitLibs) {
8394            // The package has 64 bit libs, but not 32 bit libs. Its primary
8395            // ABI should be 64 bit. We can safely assume here that the bundled
8396            // native libraries correspond to the most preferred ABI in the list.
8397
8398            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8399            pkg.applicationInfo.secondaryCpuAbi = null;
8400        } else if (has32BitLibs && !has64BitLibs) {
8401            // The package has 32 bit libs but not 64 bit libs. Its primary
8402            // ABI should be 32 bit.
8403
8404            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8405            pkg.applicationInfo.secondaryCpuAbi = null;
8406        } else if (has32BitLibs && has64BitLibs) {
8407            // The application has both 64 and 32 bit bundled libraries. We check
8408            // here that the app declares multiArch support, and warn if it doesn't.
8409            //
8410            // We will be lenient here and record both ABIs. The primary will be the
8411            // ABI that's higher on the list, i.e, a device that's configured to prefer
8412            // 64 bit apps will see a 64 bit primary ABI,
8413
8414            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8415                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8416            }
8417
8418            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8419                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8420                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8421            } else {
8422                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8423                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8424            }
8425        } else {
8426            pkg.applicationInfo.primaryCpuAbi = null;
8427            pkg.applicationInfo.secondaryCpuAbi = null;
8428        }
8429    }
8430
8431    private void killApplication(String pkgName, int appId, String reason) {
8432        // Request the ActivityManager to kill the process(only for existing packages)
8433        // so that we do not end up in a confused state while the user is still using the older
8434        // version of the application while the new one gets installed.
8435        IActivityManager am = ActivityManagerNative.getDefault();
8436        if (am != null) {
8437            try {
8438                am.killApplicationWithAppId(pkgName, appId, reason);
8439            } catch (RemoteException e) {
8440            }
8441        }
8442    }
8443
8444    void removePackageLI(PackageSetting ps, boolean chatty) {
8445        if (DEBUG_INSTALL) {
8446            if (chatty)
8447                Log.d(TAG, "Removing package " + ps.name);
8448        }
8449
8450        // writer
8451        synchronized (mPackages) {
8452            mPackages.remove(ps.name);
8453            final PackageParser.Package pkg = ps.pkg;
8454            if (pkg != null) {
8455                cleanPackageDataStructuresLILPw(pkg, chatty);
8456            }
8457        }
8458    }
8459
8460    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8461        if (DEBUG_INSTALL) {
8462            if (chatty)
8463                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8464        }
8465
8466        // writer
8467        synchronized (mPackages) {
8468            mPackages.remove(pkg.applicationInfo.packageName);
8469            cleanPackageDataStructuresLILPw(pkg, chatty);
8470        }
8471    }
8472
8473    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8474        int N = pkg.providers.size();
8475        StringBuilder r = null;
8476        int i;
8477        for (i=0; i<N; i++) {
8478            PackageParser.Provider p = pkg.providers.get(i);
8479            mProviders.removeProvider(p);
8480            if (p.info.authority == null) {
8481
8482                /* There was another ContentProvider with this authority when
8483                 * this app was installed so this authority is null,
8484                 * Ignore it as we don't have to unregister the provider.
8485                 */
8486                continue;
8487            }
8488            String names[] = p.info.authority.split(";");
8489            for (int j = 0; j < names.length; j++) {
8490                if (mProvidersByAuthority.get(names[j]) == p) {
8491                    mProvidersByAuthority.remove(names[j]);
8492                    if (DEBUG_REMOVE) {
8493                        if (chatty)
8494                            Log.d(TAG, "Unregistered content provider: " + names[j]
8495                                    + ", className = " + p.info.name + ", isSyncable = "
8496                                    + p.info.isSyncable);
8497                    }
8498                }
8499            }
8500            if (DEBUG_REMOVE && chatty) {
8501                if (r == null) {
8502                    r = new StringBuilder(256);
8503                } else {
8504                    r.append(' ');
8505                }
8506                r.append(p.info.name);
8507            }
8508        }
8509        if (r != null) {
8510            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8511        }
8512
8513        N = pkg.services.size();
8514        r = null;
8515        for (i=0; i<N; i++) {
8516            PackageParser.Service s = pkg.services.get(i);
8517            mServices.removeService(s);
8518            if (chatty) {
8519                if (r == null) {
8520                    r = new StringBuilder(256);
8521                } else {
8522                    r.append(' ');
8523                }
8524                r.append(s.info.name);
8525            }
8526        }
8527        if (r != null) {
8528            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8529        }
8530
8531        N = pkg.receivers.size();
8532        r = null;
8533        for (i=0; i<N; i++) {
8534            PackageParser.Activity a = pkg.receivers.get(i);
8535            mReceivers.removeActivity(a, "receiver");
8536            if (DEBUG_REMOVE && chatty) {
8537                if (r == null) {
8538                    r = new StringBuilder(256);
8539                } else {
8540                    r.append(' ');
8541                }
8542                r.append(a.info.name);
8543            }
8544        }
8545        if (r != null) {
8546            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8547        }
8548
8549        N = pkg.activities.size();
8550        r = null;
8551        for (i=0; i<N; i++) {
8552            PackageParser.Activity a = pkg.activities.get(i);
8553            mActivities.removeActivity(a, "activity");
8554            if (DEBUG_REMOVE && chatty) {
8555                if (r == null) {
8556                    r = new StringBuilder(256);
8557                } else {
8558                    r.append(' ');
8559                }
8560                r.append(a.info.name);
8561            }
8562        }
8563        if (r != null) {
8564            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8565        }
8566
8567        N = pkg.permissions.size();
8568        r = null;
8569        for (i=0; i<N; i++) {
8570            PackageParser.Permission p = pkg.permissions.get(i);
8571            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8572            if (bp == null) {
8573                bp = mSettings.mPermissionTrees.get(p.info.name);
8574            }
8575            if (bp != null && bp.perm == p) {
8576                bp.perm = null;
8577                if (DEBUG_REMOVE && chatty) {
8578                    if (r == null) {
8579                        r = new StringBuilder(256);
8580                    } else {
8581                        r.append(' ');
8582                    }
8583                    r.append(p.info.name);
8584                }
8585            }
8586            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8587                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8588                if (appOpPkgs != null) {
8589                    appOpPkgs.remove(pkg.packageName);
8590                }
8591            }
8592        }
8593        if (r != null) {
8594            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8595        }
8596
8597        N = pkg.requestedPermissions.size();
8598        r = null;
8599        for (i=0; i<N; i++) {
8600            String perm = pkg.requestedPermissions.get(i);
8601            BasePermission bp = mSettings.mPermissions.get(perm);
8602            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8603                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8604                if (appOpPkgs != null) {
8605                    appOpPkgs.remove(pkg.packageName);
8606                    if (appOpPkgs.isEmpty()) {
8607                        mAppOpPermissionPackages.remove(perm);
8608                    }
8609                }
8610            }
8611        }
8612        if (r != null) {
8613            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8614        }
8615
8616        N = pkg.instrumentation.size();
8617        r = null;
8618        for (i=0; i<N; i++) {
8619            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8620            mInstrumentation.remove(a.getComponentName());
8621            if (DEBUG_REMOVE && chatty) {
8622                if (r == null) {
8623                    r = new StringBuilder(256);
8624                } else {
8625                    r.append(' ');
8626                }
8627                r.append(a.info.name);
8628            }
8629        }
8630        if (r != null) {
8631            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8632        }
8633
8634        r = null;
8635        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8636            // Only system apps can hold shared libraries.
8637            if (pkg.libraryNames != null) {
8638                for (i=0; i<pkg.libraryNames.size(); i++) {
8639                    String name = pkg.libraryNames.get(i);
8640                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8641                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8642                        mSharedLibraries.remove(name);
8643                        if (DEBUG_REMOVE && chatty) {
8644                            if (r == null) {
8645                                r = new StringBuilder(256);
8646                            } else {
8647                                r.append(' ');
8648                            }
8649                            r.append(name);
8650                        }
8651                    }
8652                }
8653            }
8654        }
8655        if (r != null) {
8656            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8657        }
8658    }
8659
8660    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8661        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8662            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8663                return true;
8664            }
8665        }
8666        return false;
8667    }
8668
8669    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8670    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8671    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8672
8673    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8674            int flags) {
8675        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8676        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8677    }
8678
8679    private void updatePermissionsLPw(String changingPkg,
8680            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8681        // Make sure there are no dangling permission trees.
8682        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8683        while (it.hasNext()) {
8684            final BasePermission bp = it.next();
8685            if (bp.packageSetting == null) {
8686                // We may not yet have parsed the package, so just see if
8687                // we still know about its settings.
8688                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8689            }
8690            if (bp.packageSetting == null) {
8691                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8692                        + " from package " + bp.sourcePackage);
8693                it.remove();
8694            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8695                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8696                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8697                            + " from package " + bp.sourcePackage);
8698                    flags |= UPDATE_PERMISSIONS_ALL;
8699                    it.remove();
8700                }
8701            }
8702        }
8703
8704        // Make sure all dynamic permissions have been assigned to a package,
8705        // and make sure there are no dangling permissions.
8706        it = mSettings.mPermissions.values().iterator();
8707        while (it.hasNext()) {
8708            final BasePermission bp = it.next();
8709            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8710                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8711                        + bp.name + " pkg=" + bp.sourcePackage
8712                        + " info=" + bp.pendingInfo);
8713                if (bp.packageSetting == null && bp.pendingInfo != null) {
8714                    final BasePermission tree = findPermissionTreeLP(bp.name);
8715                    if (tree != null && tree.perm != null) {
8716                        bp.packageSetting = tree.packageSetting;
8717                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8718                                new PermissionInfo(bp.pendingInfo));
8719                        bp.perm.info.packageName = tree.perm.info.packageName;
8720                        bp.perm.info.name = bp.name;
8721                        bp.uid = tree.uid;
8722                    }
8723                }
8724            }
8725            if (bp.packageSetting == null) {
8726                // We may not yet have parsed the package, so just see if
8727                // we still know about its settings.
8728                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8729            }
8730            if (bp.packageSetting == null) {
8731                Slog.w(TAG, "Removing dangling permission: " + bp.name
8732                        + " from package " + bp.sourcePackage);
8733                it.remove();
8734            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8735                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8736                    Slog.i(TAG, "Removing old permission: " + bp.name
8737                            + " from package " + bp.sourcePackage);
8738                    flags |= UPDATE_PERMISSIONS_ALL;
8739                    it.remove();
8740                }
8741            }
8742        }
8743
8744        // Now update the permissions for all packages, in particular
8745        // replace the granted permissions of the system packages.
8746        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8747            for (PackageParser.Package pkg : mPackages.values()) {
8748                if (pkg != pkgInfo) {
8749                    // Only replace for packages on requested volume
8750                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8751                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8752                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8753                    grantPermissionsLPw(pkg, replace, changingPkg);
8754                }
8755            }
8756        }
8757
8758        if (pkgInfo != null) {
8759            // Only replace for packages on requested volume
8760            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8761            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8762                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8763            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8764        }
8765    }
8766
8767    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8768            String packageOfInterest) {
8769        // IMPORTANT: There are two types of permissions: install and runtime.
8770        // Install time permissions are granted when the app is installed to
8771        // all device users and users added in the future. Runtime permissions
8772        // are granted at runtime explicitly to specific users. Normal and signature
8773        // protected permissions are install time permissions. Dangerous permissions
8774        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8775        // otherwise they are runtime permissions. This function does not manage
8776        // runtime permissions except for the case an app targeting Lollipop MR1
8777        // being upgraded to target a newer SDK, in which case dangerous permissions
8778        // are transformed from install time to runtime ones.
8779
8780        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8781        if (ps == null) {
8782            return;
8783        }
8784
8785        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8786
8787        PermissionsState permissionsState = ps.getPermissionsState();
8788        PermissionsState origPermissions = permissionsState;
8789
8790        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8791
8792        boolean runtimePermissionsRevoked = false;
8793        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8794
8795        boolean changedInstallPermission = false;
8796
8797        if (replace) {
8798            ps.installPermissionsFixed = false;
8799            if (!ps.isSharedUser()) {
8800                origPermissions = new PermissionsState(permissionsState);
8801                permissionsState.reset();
8802            } else {
8803                // We need to know only about runtime permission changes since the
8804                // calling code always writes the install permissions state but
8805                // the runtime ones are written only if changed. The only cases of
8806                // changed runtime permissions here are promotion of an install to
8807                // runtime and revocation of a runtime from a shared user.
8808                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8809                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8810                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8811                    runtimePermissionsRevoked = true;
8812                }
8813            }
8814        }
8815
8816        permissionsState.setGlobalGids(mGlobalGids);
8817
8818        final int N = pkg.requestedPermissions.size();
8819        for (int i=0; i<N; i++) {
8820            final String name = pkg.requestedPermissions.get(i);
8821            final BasePermission bp = mSettings.mPermissions.get(name);
8822
8823            if (DEBUG_INSTALL) {
8824                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8825            }
8826
8827            if (bp == null || bp.packageSetting == null) {
8828                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8829                    Slog.w(TAG, "Unknown permission " + name
8830                            + " in package " + pkg.packageName);
8831                }
8832                continue;
8833            }
8834
8835            final String perm = bp.name;
8836            boolean allowedSig = false;
8837            int grant = GRANT_DENIED;
8838
8839            // Keep track of app op permissions.
8840            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8841                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8842                if (pkgs == null) {
8843                    pkgs = new ArraySet<>();
8844                    mAppOpPermissionPackages.put(bp.name, pkgs);
8845                }
8846                pkgs.add(pkg.packageName);
8847            }
8848
8849            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8850            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8851                    >= Build.VERSION_CODES.M;
8852            switch (level) {
8853                case PermissionInfo.PROTECTION_NORMAL: {
8854                    // For all apps normal permissions are install time ones.
8855                    grant = GRANT_INSTALL;
8856                } break;
8857
8858                case PermissionInfo.PROTECTION_DANGEROUS: {
8859                    // If a permission review is required for legacy apps we represent
8860                    // their permissions as always granted runtime ones since we need
8861                    // to keep the review required permission flag per user while an
8862                    // install permission's state is shared across all users.
8863                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8864                        // For legacy apps dangerous permissions are install time ones.
8865                        grant = GRANT_INSTALL;
8866                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8867                        // For legacy apps that became modern, install becomes runtime.
8868                        grant = GRANT_UPGRADE;
8869                    } else if (mPromoteSystemApps
8870                            && isSystemApp(ps)
8871                            && mExistingSystemPackages.contains(ps.name)) {
8872                        // For legacy system apps, install becomes runtime.
8873                        // We cannot check hasInstallPermission() for system apps since those
8874                        // permissions were granted implicitly and not persisted pre-M.
8875                        grant = GRANT_UPGRADE;
8876                    } else {
8877                        // For modern apps keep runtime permissions unchanged.
8878                        grant = GRANT_RUNTIME;
8879                    }
8880                } break;
8881
8882                case PermissionInfo.PROTECTION_SIGNATURE: {
8883                    // For all apps signature permissions are install time ones.
8884                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8885                    if (allowedSig) {
8886                        grant = GRANT_INSTALL;
8887                    }
8888                } break;
8889            }
8890
8891            if (DEBUG_INSTALL) {
8892                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8893            }
8894
8895            if (grant != GRANT_DENIED) {
8896                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8897                    // If this is an existing, non-system package, then
8898                    // we can't add any new permissions to it.
8899                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8900                        // Except...  if this is a permission that was added
8901                        // to the platform (note: need to only do this when
8902                        // updating the platform).
8903                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8904                            grant = GRANT_DENIED;
8905                        }
8906                    }
8907                }
8908
8909                switch (grant) {
8910                    case GRANT_INSTALL: {
8911                        // Revoke this as runtime permission to handle the case of
8912                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8913                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8914                            if (origPermissions.getRuntimePermissionState(
8915                                    bp.name, userId) != null) {
8916                                // Revoke the runtime permission and clear the flags.
8917                                origPermissions.revokeRuntimePermission(bp, userId);
8918                                origPermissions.updatePermissionFlags(bp, userId,
8919                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8920                                // If we revoked a permission permission, we have to write.
8921                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8922                                        changedRuntimePermissionUserIds, userId);
8923                            }
8924                        }
8925                        // Grant an install permission.
8926                        if (permissionsState.grantInstallPermission(bp) !=
8927                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8928                            changedInstallPermission = true;
8929                        }
8930                    } break;
8931
8932                    case GRANT_RUNTIME: {
8933                        // Grant previously granted runtime permissions.
8934                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8935                            PermissionState permissionState = origPermissions
8936                                    .getRuntimePermissionState(bp.name, userId);
8937                            int flags = permissionState != null
8938                                    ? permissionState.getFlags() : 0;
8939                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8940                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8941                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8942                                    // If we cannot put the permission as it was, we have to write.
8943                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8944                                            changedRuntimePermissionUserIds, userId);
8945                                }
8946                                // If the app supports runtime permissions no need for a review.
8947                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8948                                        && appSupportsRuntimePermissions
8949                                        && (flags & PackageManager
8950                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8951                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8952                                    // Since we changed the flags, we have to write.
8953                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8954                                            changedRuntimePermissionUserIds, userId);
8955                                }
8956                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8957                                    && !appSupportsRuntimePermissions) {
8958                                // For legacy apps that need a permission review, every new
8959                                // runtime permission is granted but it is pending a review.
8960                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8961                                    permissionsState.grantRuntimePermission(bp, userId);
8962                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8963                                    // We changed the permission and flags, hence have to write.
8964                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8965                                            changedRuntimePermissionUserIds, userId);
8966                                }
8967                            }
8968                            // Propagate the permission flags.
8969                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8970                        }
8971                    } break;
8972
8973                    case GRANT_UPGRADE: {
8974                        // Grant runtime permissions for a previously held install permission.
8975                        PermissionState permissionState = origPermissions
8976                                .getInstallPermissionState(bp.name);
8977                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8978
8979                        if (origPermissions.revokeInstallPermission(bp)
8980                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8981                            // We will be transferring the permission flags, so clear them.
8982                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8983                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8984                            changedInstallPermission = true;
8985                        }
8986
8987                        // If the permission is not to be promoted to runtime we ignore it and
8988                        // also its other flags as they are not applicable to install permissions.
8989                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8990                            for (int userId : currentUserIds) {
8991                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8992                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8993                                    // Transfer the permission flags.
8994                                    permissionsState.updatePermissionFlags(bp, userId,
8995                                            flags, flags);
8996                                    // If we granted the permission, we have to write.
8997                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8998                                            changedRuntimePermissionUserIds, userId);
8999                                }
9000                            }
9001                        }
9002                    } break;
9003
9004                    default: {
9005                        if (packageOfInterest == null
9006                                || packageOfInterest.equals(pkg.packageName)) {
9007                            Slog.w(TAG, "Not granting permission " + perm
9008                                    + " to package " + pkg.packageName
9009                                    + " because it was previously installed without");
9010                        }
9011                    } break;
9012                }
9013            } else {
9014                if (permissionsState.revokeInstallPermission(bp) !=
9015                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9016                    // Also drop the permission flags.
9017                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9018                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9019                    changedInstallPermission = true;
9020                    Slog.i(TAG, "Un-granting permission " + perm
9021                            + " from package " + pkg.packageName
9022                            + " (protectionLevel=" + bp.protectionLevel
9023                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9024                            + ")");
9025                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9026                    // Don't print warning for app op permissions, since it is fine for them
9027                    // not to be granted, there is a UI for the user to decide.
9028                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9029                        Slog.w(TAG, "Not granting permission " + perm
9030                                + " to package " + pkg.packageName
9031                                + " (protectionLevel=" + bp.protectionLevel
9032                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9033                                + ")");
9034                    }
9035                }
9036            }
9037        }
9038
9039        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9040                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9041            // This is the first that we have heard about this package, so the
9042            // permissions we have now selected are fixed until explicitly
9043            // changed.
9044            ps.installPermissionsFixed = true;
9045        }
9046
9047        // Persist the runtime permissions state for users with changes. If permissions
9048        // were revoked because no app in the shared user declares them we have to
9049        // write synchronously to avoid losing runtime permissions state.
9050        for (int userId : changedRuntimePermissionUserIds) {
9051            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9052        }
9053
9054        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9055    }
9056
9057    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9058        boolean allowed = false;
9059        final int NP = PackageParser.NEW_PERMISSIONS.length;
9060        for (int ip=0; ip<NP; ip++) {
9061            final PackageParser.NewPermissionInfo npi
9062                    = PackageParser.NEW_PERMISSIONS[ip];
9063            if (npi.name.equals(perm)
9064                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9065                allowed = true;
9066                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9067                        + pkg.packageName);
9068                break;
9069            }
9070        }
9071        return allowed;
9072    }
9073
9074    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9075            BasePermission bp, PermissionsState origPermissions) {
9076        boolean allowed;
9077        allowed = (compareSignatures(
9078                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9079                        == PackageManager.SIGNATURE_MATCH)
9080                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9081                        == PackageManager.SIGNATURE_MATCH);
9082        if (!allowed && (bp.protectionLevel
9083                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9084            if (isSystemApp(pkg)) {
9085                // For updated system applications, a system permission
9086                // is granted only if it had been defined by the original application.
9087                if (pkg.isUpdatedSystemApp()) {
9088                    final PackageSetting sysPs = mSettings
9089                            .getDisabledSystemPkgLPr(pkg.packageName);
9090                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9091                        // If the original was granted this permission, we take
9092                        // that grant decision as read and propagate it to the
9093                        // update.
9094                        if (sysPs.isPrivileged()) {
9095                            allowed = true;
9096                        }
9097                    } else {
9098                        // The system apk may have been updated with an older
9099                        // version of the one on the data partition, but which
9100                        // granted a new system permission that it didn't have
9101                        // before.  In this case we do want to allow the app to
9102                        // now get the new permission if the ancestral apk is
9103                        // privileged to get it.
9104                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9105                            for (int j=0;
9106                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9107                                if (perm.equals(
9108                                        sysPs.pkg.requestedPermissions.get(j))) {
9109                                    allowed = true;
9110                                    break;
9111                                }
9112                            }
9113                        }
9114                    }
9115                } else {
9116                    allowed = isPrivilegedApp(pkg);
9117                }
9118            }
9119        }
9120        if (!allowed) {
9121            if (!allowed && (bp.protectionLevel
9122                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9123                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9124                // If this was a previously normal/dangerous permission that got moved
9125                // to a system permission as part of the runtime permission redesign, then
9126                // we still want to blindly grant it to old apps.
9127                allowed = true;
9128            }
9129            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9130                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9131                // If this permission is to be granted to the system installer and
9132                // this app is an installer, then it gets the permission.
9133                allowed = true;
9134            }
9135            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9136                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9137                // If this permission is to be granted to the system verifier and
9138                // this app is a verifier, then it gets the permission.
9139                allowed = true;
9140            }
9141            if (!allowed && (bp.protectionLevel
9142                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9143                    && isSystemApp(pkg)) {
9144                // Any pre-installed system app is allowed to get this permission.
9145                allowed = true;
9146            }
9147            if (!allowed && (bp.protectionLevel
9148                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9149                // For development permissions, a development permission
9150                // is granted only if it was already granted.
9151                allowed = origPermissions.hasInstallPermission(perm);
9152            }
9153        }
9154        return allowed;
9155    }
9156
9157    final class ActivityIntentResolver
9158            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9159        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9160                boolean defaultOnly, int userId) {
9161            if (!sUserManager.exists(userId)) return null;
9162            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9163            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9164        }
9165
9166        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9167                int userId) {
9168            if (!sUserManager.exists(userId)) return null;
9169            mFlags = flags;
9170            return super.queryIntent(intent, resolvedType,
9171                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9172        }
9173
9174        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9175                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9176            if (!sUserManager.exists(userId)) return null;
9177            if (packageActivities == null) {
9178                return null;
9179            }
9180            mFlags = flags;
9181            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9182            final int N = packageActivities.size();
9183            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9184                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9185
9186            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9187            for (int i = 0; i < N; ++i) {
9188                intentFilters = packageActivities.get(i).intents;
9189                if (intentFilters != null && intentFilters.size() > 0) {
9190                    PackageParser.ActivityIntentInfo[] array =
9191                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9192                    intentFilters.toArray(array);
9193                    listCut.add(array);
9194                }
9195            }
9196            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9197        }
9198
9199        public final void addActivity(PackageParser.Activity a, String type) {
9200            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9201            mActivities.put(a.getComponentName(), a);
9202            if (DEBUG_SHOW_INFO)
9203                Log.v(
9204                TAG, "  " + type + " " +
9205                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9206            if (DEBUG_SHOW_INFO)
9207                Log.v(TAG, "    Class=" + a.info.name);
9208            final int NI = a.intents.size();
9209            for (int j=0; j<NI; j++) {
9210                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9211                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9212                    intent.setPriority(0);
9213                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9214                            + a.className + " with priority > 0, forcing to 0");
9215                }
9216                if (DEBUG_SHOW_INFO) {
9217                    Log.v(TAG, "    IntentFilter:");
9218                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9219                }
9220                if (!intent.debugCheck()) {
9221                    Log.w(TAG, "==> For Activity " + a.info.name);
9222                }
9223                addFilter(intent);
9224            }
9225        }
9226
9227        public final void removeActivity(PackageParser.Activity a, String type) {
9228            mActivities.remove(a.getComponentName());
9229            if (DEBUG_SHOW_INFO) {
9230                Log.v(TAG, "  " + type + " "
9231                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9232                                : a.info.name) + ":");
9233                Log.v(TAG, "    Class=" + a.info.name);
9234            }
9235            final int NI = a.intents.size();
9236            for (int j=0; j<NI; j++) {
9237                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9238                if (DEBUG_SHOW_INFO) {
9239                    Log.v(TAG, "    IntentFilter:");
9240                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9241                }
9242                removeFilter(intent);
9243            }
9244        }
9245
9246        @Override
9247        protected boolean allowFilterResult(
9248                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9249            ActivityInfo filterAi = filter.activity.info;
9250            for (int i=dest.size()-1; i>=0; i--) {
9251                ActivityInfo destAi = dest.get(i).activityInfo;
9252                if (destAi.name == filterAi.name
9253                        && destAi.packageName == filterAi.packageName) {
9254                    return false;
9255                }
9256            }
9257            return true;
9258        }
9259
9260        @Override
9261        protected ActivityIntentInfo[] newArray(int size) {
9262            return new ActivityIntentInfo[size];
9263        }
9264
9265        @Override
9266        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9267            if (!sUserManager.exists(userId)) return true;
9268            PackageParser.Package p = filter.activity.owner;
9269            if (p != null) {
9270                PackageSetting ps = (PackageSetting)p.mExtras;
9271                if (ps != null) {
9272                    // System apps are never considered stopped for purposes of
9273                    // filtering, because there may be no way for the user to
9274                    // actually re-launch them.
9275                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9276                            && ps.getStopped(userId);
9277                }
9278            }
9279            return false;
9280        }
9281
9282        @Override
9283        protected boolean isPackageForFilter(String packageName,
9284                PackageParser.ActivityIntentInfo info) {
9285            return packageName.equals(info.activity.owner.packageName);
9286        }
9287
9288        @Override
9289        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9290                int match, int userId) {
9291            if (!sUserManager.exists(userId)) return null;
9292            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9293                return null;
9294            }
9295            final PackageParser.Activity activity = info.activity;
9296            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9297            if (ps == null) {
9298                return null;
9299            }
9300            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9301                    ps.readUserState(userId), userId);
9302            if (ai == null) {
9303                return null;
9304            }
9305            final ResolveInfo res = new ResolveInfo();
9306            res.activityInfo = ai;
9307            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9308                res.filter = info;
9309            }
9310            if (info != null) {
9311                res.handleAllWebDataURI = info.handleAllWebDataURI();
9312            }
9313            res.priority = info.getPriority();
9314            res.preferredOrder = activity.owner.mPreferredOrder;
9315            //System.out.println("Result: " + res.activityInfo.className +
9316            //                   " = " + res.priority);
9317            res.match = match;
9318            res.isDefault = info.hasDefault;
9319            res.labelRes = info.labelRes;
9320            res.nonLocalizedLabel = info.nonLocalizedLabel;
9321            if (userNeedsBadging(userId)) {
9322                res.noResourceId = true;
9323            } else {
9324                res.icon = info.icon;
9325            }
9326            res.iconResourceId = info.icon;
9327            res.system = res.activityInfo.applicationInfo.isSystemApp();
9328            return res;
9329        }
9330
9331        @Override
9332        protected void sortResults(List<ResolveInfo> results) {
9333            Collections.sort(results, mResolvePrioritySorter);
9334        }
9335
9336        @Override
9337        protected void dumpFilter(PrintWriter out, String prefix,
9338                PackageParser.ActivityIntentInfo filter) {
9339            out.print(prefix); out.print(
9340                    Integer.toHexString(System.identityHashCode(filter.activity)));
9341                    out.print(' ');
9342                    filter.activity.printComponentShortName(out);
9343                    out.print(" filter ");
9344                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9345        }
9346
9347        @Override
9348        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9349            return filter.activity;
9350        }
9351
9352        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9353            PackageParser.Activity activity = (PackageParser.Activity)label;
9354            out.print(prefix); out.print(
9355                    Integer.toHexString(System.identityHashCode(activity)));
9356                    out.print(' ');
9357                    activity.printComponentShortName(out);
9358            if (count > 1) {
9359                out.print(" ("); out.print(count); out.print(" filters)");
9360            }
9361            out.println();
9362        }
9363
9364//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9365//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9366//            final List<ResolveInfo> retList = Lists.newArrayList();
9367//            while (i.hasNext()) {
9368//                final ResolveInfo resolveInfo = i.next();
9369//                if (isEnabledLP(resolveInfo.activityInfo)) {
9370//                    retList.add(resolveInfo);
9371//                }
9372//            }
9373//            return retList;
9374//        }
9375
9376        // Keys are String (activity class name), values are Activity.
9377        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9378                = new ArrayMap<ComponentName, PackageParser.Activity>();
9379        private int mFlags;
9380    }
9381
9382    private final class ServiceIntentResolver
9383            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9384        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9385                boolean defaultOnly, int userId) {
9386            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9387            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9388        }
9389
9390        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9391                int userId) {
9392            if (!sUserManager.exists(userId)) return null;
9393            mFlags = flags;
9394            return super.queryIntent(intent, resolvedType,
9395                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9396        }
9397
9398        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9399                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9400            if (!sUserManager.exists(userId)) return null;
9401            if (packageServices == null) {
9402                return null;
9403            }
9404            mFlags = flags;
9405            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9406            final int N = packageServices.size();
9407            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9408                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9409
9410            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9411            for (int i = 0; i < N; ++i) {
9412                intentFilters = packageServices.get(i).intents;
9413                if (intentFilters != null && intentFilters.size() > 0) {
9414                    PackageParser.ServiceIntentInfo[] array =
9415                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9416                    intentFilters.toArray(array);
9417                    listCut.add(array);
9418                }
9419            }
9420            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9421        }
9422
9423        public final void addService(PackageParser.Service s) {
9424            mServices.put(s.getComponentName(), s);
9425            if (DEBUG_SHOW_INFO) {
9426                Log.v(TAG, "  "
9427                        + (s.info.nonLocalizedLabel != null
9428                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9429                Log.v(TAG, "    Class=" + s.info.name);
9430            }
9431            final int NI = s.intents.size();
9432            int j;
9433            for (j=0; j<NI; j++) {
9434                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9435                if (DEBUG_SHOW_INFO) {
9436                    Log.v(TAG, "    IntentFilter:");
9437                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9438                }
9439                if (!intent.debugCheck()) {
9440                    Log.w(TAG, "==> For Service " + s.info.name);
9441                }
9442                addFilter(intent);
9443            }
9444        }
9445
9446        public final void removeService(PackageParser.Service s) {
9447            mServices.remove(s.getComponentName());
9448            if (DEBUG_SHOW_INFO) {
9449                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9450                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9451                Log.v(TAG, "    Class=" + s.info.name);
9452            }
9453            final int NI = s.intents.size();
9454            int j;
9455            for (j=0; j<NI; j++) {
9456                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9457                if (DEBUG_SHOW_INFO) {
9458                    Log.v(TAG, "    IntentFilter:");
9459                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9460                }
9461                removeFilter(intent);
9462            }
9463        }
9464
9465        @Override
9466        protected boolean allowFilterResult(
9467                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9468            ServiceInfo filterSi = filter.service.info;
9469            for (int i=dest.size()-1; i>=0; i--) {
9470                ServiceInfo destAi = dest.get(i).serviceInfo;
9471                if (destAi.name == filterSi.name
9472                        && destAi.packageName == filterSi.packageName) {
9473                    return false;
9474                }
9475            }
9476            return true;
9477        }
9478
9479        @Override
9480        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9481            return new PackageParser.ServiceIntentInfo[size];
9482        }
9483
9484        @Override
9485        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9486            if (!sUserManager.exists(userId)) return true;
9487            PackageParser.Package p = filter.service.owner;
9488            if (p != null) {
9489                PackageSetting ps = (PackageSetting)p.mExtras;
9490                if (ps != null) {
9491                    // System apps are never considered stopped for purposes of
9492                    // filtering, because there may be no way for the user to
9493                    // actually re-launch them.
9494                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9495                            && ps.getStopped(userId);
9496                }
9497            }
9498            return false;
9499        }
9500
9501        @Override
9502        protected boolean isPackageForFilter(String packageName,
9503                PackageParser.ServiceIntentInfo info) {
9504            return packageName.equals(info.service.owner.packageName);
9505        }
9506
9507        @Override
9508        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9509                int match, int userId) {
9510            if (!sUserManager.exists(userId)) return null;
9511            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9512            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9513                return null;
9514            }
9515            final PackageParser.Service service = info.service;
9516            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9517            if (ps == null) {
9518                return null;
9519            }
9520            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9521                    ps.readUserState(userId), userId);
9522            if (si == null) {
9523                return null;
9524            }
9525            final ResolveInfo res = new ResolveInfo();
9526            res.serviceInfo = si;
9527            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9528                res.filter = filter;
9529            }
9530            res.priority = info.getPriority();
9531            res.preferredOrder = service.owner.mPreferredOrder;
9532            res.match = match;
9533            res.isDefault = info.hasDefault;
9534            res.labelRes = info.labelRes;
9535            res.nonLocalizedLabel = info.nonLocalizedLabel;
9536            res.icon = info.icon;
9537            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9538            return res;
9539        }
9540
9541        @Override
9542        protected void sortResults(List<ResolveInfo> results) {
9543            Collections.sort(results, mResolvePrioritySorter);
9544        }
9545
9546        @Override
9547        protected void dumpFilter(PrintWriter out, String prefix,
9548                PackageParser.ServiceIntentInfo filter) {
9549            out.print(prefix); out.print(
9550                    Integer.toHexString(System.identityHashCode(filter.service)));
9551                    out.print(' ');
9552                    filter.service.printComponentShortName(out);
9553                    out.print(" filter ");
9554                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9555        }
9556
9557        @Override
9558        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9559            return filter.service;
9560        }
9561
9562        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9563            PackageParser.Service service = (PackageParser.Service)label;
9564            out.print(prefix); out.print(
9565                    Integer.toHexString(System.identityHashCode(service)));
9566                    out.print(' ');
9567                    service.printComponentShortName(out);
9568            if (count > 1) {
9569                out.print(" ("); out.print(count); out.print(" filters)");
9570            }
9571            out.println();
9572        }
9573
9574//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9575//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9576//            final List<ResolveInfo> retList = Lists.newArrayList();
9577//            while (i.hasNext()) {
9578//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9579//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9580//                    retList.add(resolveInfo);
9581//                }
9582//            }
9583//            return retList;
9584//        }
9585
9586        // Keys are String (activity class name), values are Activity.
9587        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9588                = new ArrayMap<ComponentName, PackageParser.Service>();
9589        private int mFlags;
9590    };
9591
9592    private final class ProviderIntentResolver
9593            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9594        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9595                boolean defaultOnly, int userId) {
9596            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9597            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9598        }
9599
9600        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9601                int userId) {
9602            if (!sUserManager.exists(userId))
9603                return null;
9604            mFlags = flags;
9605            return super.queryIntent(intent, resolvedType,
9606                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9607        }
9608
9609        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9610                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9611            if (!sUserManager.exists(userId))
9612                return null;
9613            if (packageProviders == null) {
9614                return null;
9615            }
9616            mFlags = flags;
9617            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9618            final int N = packageProviders.size();
9619            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9620                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9621
9622            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9623            for (int i = 0; i < N; ++i) {
9624                intentFilters = packageProviders.get(i).intents;
9625                if (intentFilters != null && intentFilters.size() > 0) {
9626                    PackageParser.ProviderIntentInfo[] array =
9627                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9628                    intentFilters.toArray(array);
9629                    listCut.add(array);
9630                }
9631            }
9632            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9633        }
9634
9635        public final void addProvider(PackageParser.Provider p) {
9636            if (mProviders.containsKey(p.getComponentName())) {
9637                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9638                return;
9639            }
9640
9641            mProviders.put(p.getComponentName(), p);
9642            if (DEBUG_SHOW_INFO) {
9643                Log.v(TAG, "  "
9644                        + (p.info.nonLocalizedLabel != null
9645                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9646                Log.v(TAG, "    Class=" + p.info.name);
9647            }
9648            final int NI = p.intents.size();
9649            int j;
9650            for (j = 0; j < NI; j++) {
9651                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9652                if (DEBUG_SHOW_INFO) {
9653                    Log.v(TAG, "    IntentFilter:");
9654                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9655                }
9656                if (!intent.debugCheck()) {
9657                    Log.w(TAG, "==> For Provider " + p.info.name);
9658                }
9659                addFilter(intent);
9660            }
9661        }
9662
9663        public final void removeProvider(PackageParser.Provider p) {
9664            mProviders.remove(p.getComponentName());
9665            if (DEBUG_SHOW_INFO) {
9666                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9667                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9668                Log.v(TAG, "    Class=" + p.info.name);
9669            }
9670            final int NI = p.intents.size();
9671            int j;
9672            for (j = 0; j < NI; j++) {
9673                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9674                if (DEBUG_SHOW_INFO) {
9675                    Log.v(TAG, "    IntentFilter:");
9676                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9677                }
9678                removeFilter(intent);
9679            }
9680        }
9681
9682        @Override
9683        protected boolean allowFilterResult(
9684                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9685            ProviderInfo filterPi = filter.provider.info;
9686            for (int i = dest.size() - 1; i >= 0; i--) {
9687                ProviderInfo destPi = dest.get(i).providerInfo;
9688                if (destPi.name == filterPi.name
9689                        && destPi.packageName == filterPi.packageName) {
9690                    return false;
9691                }
9692            }
9693            return true;
9694        }
9695
9696        @Override
9697        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9698            return new PackageParser.ProviderIntentInfo[size];
9699        }
9700
9701        @Override
9702        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9703            if (!sUserManager.exists(userId))
9704                return true;
9705            PackageParser.Package p = filter.provider.owner;
9706            if (p != null) {
9707                PackageSetting ps = (PackageSetting) p.mExtras;
9708                if (ps != null) {
9709                    // System apps are never considered stopped for purposes of
9710                    // filtering, because there may be no way for the user to
9711                    // actually re-launch them.
9712                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9713                            && ps.getStopped(userId);
9714                }
9715            }
9716            return false;
9717        }
9718
9719        @Override
9720        protected boolean isPackageForFilter(String packageName,
9721                PackageParser.ProviderIntentInfo info) {
9722            return packageName.equals(info.provider.owner.packageName);
9723        }
9724
9725        @Override
9726        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9727                int match, int userId) {
9728            if (!sUserManager.exists(userId))
9729                return null;
9730            final PackageParser.ProviderIntentInfo info = filter;
9731            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9732                return null;
9733            }
9734            final PackageParser.Provider provider = info.provider;
9735            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9736            if (ps == null) {
9737                return null;
9738            }
9739            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9740                    ps.readUserState(userId), userId);
9741            if (pi == null) {
9742                return null;
9743            }
9744            final ResolveInfo res = new ResolveInfo();
9745            res.providerInfo = pi;
9746            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9747                res.filter = filter;
9748            }
9749            res.priority = info.getPriority();
9750            res.preferredOrder = provider.owner.mPreferredOrder;
9751            res.match = match;
9752            res.isDefault = info.hasDefault;
9753            res.labelRes = info.labelRes;
9754            res.nonLocalizedLabel = info.nonLocalizedLabel;
9755            res.icon = info.icon;
9756            res.system = res.providerInfo.applicationInfo.isSystemApp();
9757            return res;
9758        }
9759
9760        @Override
9761        protected void sortResults(List<ResolveInfo> results) {
9762            Collections.sort(results, mResolvePrioritySorter);
9763        }
9764
9765        @Override
9766        protected void dumpFilter(PrintWriter out, String prefix,
9767                PackageParser.ProviderIntentInfo filter) {
9768            out.print(prefix);
9769            out.print(
9770                    Integer.toHexString(System.identityHashCode(filter.provider)));
9771            out.print(' ');
9772            filter.provider.printComponentShortName(out);
9773            out.print(" filter ");
9774            out.println(Integer.toHexString(System.identityHashCode(filter)));
9775        }
9776
9777        @Override
9778        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9779            return filter.provider;
9780        }
9781
9782        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9783            PackageParser.Provider provider = (PackageParser.Provider)label;
9784            out.print(prefix); out.print(
9785                    Integer.toHexString(System.identityHashCode(provider)));
9786                    out.print(' ');
9787                    provider.printComponentShortName(out);
9788            if (count > 1) {
9789                out.print(" ("); out.print(count); out.print(" filters)");
9790            }
9791            out.println();
9792        }
9793
9794        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9795                = new ArrayMap<ComponentName, PackageParser.Provider>();
9796        private int mFlags;
9797    }
9798
9799    private static final class EphemeralIntentResolver
9800            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9801        @Override
9802        protected EphemeralResolveIntentInfo[] newArray(int size) {
9803            return new EphemeralResolveIntentInfo[size];
9804        }
9805
9806        @Override
9807        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9808            return true;
9809        }
9810
9811        @Override
9812        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9813                int userId) {
9814            if (!sUserManager.exists(userId)) {
9815                return null;
9816            }
9817            return info.getEphemeralResolveInfo();
9818        }
9819    }
9820
9821    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9822            new Comparator<ResolveInfo>() {
9823        public int compare(ResolveInfo r1, ResolveInfo r2) {
9824            int v1 = r1.priority;
9825            int v2 = r2.priority;
9826            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9827            if (v1 != v2) {
9828                return (v1 > v2) ? -1 : 1;
9829            }
9830            v1 = r1.preferredOrder;
9831            v2 = r2.preferredOrder;
9832            if (v1 != v2) {
9833                return (v1 > v2) ? -1 : 1;
9834            }
9835            if (r1.isDefault != r2.isDefault) {
9836                return r1.isDefault ? -1 : 1;
9837            }
9838            v1 = r1.match;
9839            v2 = r2.match;
9840            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9841            if (v1 != v2) {
9842                return (v1 > v2) ? -1 : 1;
9843            }
9844            if (r1.system != r2.system) {
9845                return r1.system ? -1 : 1;
9846            }
9847            if (r1.activityInfo != null) {
9848                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9849            }
9850            if (r1.serviceInfo != null) {
9851                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9852            }
9853            if (r1.providerInfo != null) {
9854                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9855            }
9856            return 0;
9857        }
9858    };
9859
9860    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9861            new Comparator<ProviderInfo>() {
9862        public int compare(ProviderInfo p1, ProviderInfo p2) {
9863            final int v1 = p1.initOrder;
9864            final int v2 = p2.initOrder;
9865            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9866        }
9867    };
9868
9869    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9870            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9871            final int[] userIds) {
9872        mHandler.post(new Runnable() {
9873            @Override
9874            public void run() {
9875                try {
9876                    final IActivityManager am = ActivityManagerNative.getDefault();
9877                    if (am == null) return;
9878                    final int[] resolvedUserIds;
9879                    if (userIds == null) {
9880                        resolvedUserIds = am.getRunningUserIds();
9881                    } else {
9882                        resolvedUserIds = userIds;
9883                    }
9884                    for (int id : resolvedUserIds) {
9885                        final Intent intent = new Intent(action,
9886                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9887                        if (extras != null) {
9888                            intent.putExtras(extras);
9889                        }
9890                        if (targetPkg != null) {
9891                            intent.setPackage(targetPkg);
9892                        }
9893                        // Modify the UID when posting to other users
9894                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9895                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9896                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9897                            intent.putExtra(Intent.EXTRA_UID, uid);
9898                        }
9899                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9900                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9901                        if (DEBUG_BROADCASTS) {
9902                            RuntimeException here = new RuntimeException("here");
9903                            here.fillInStackTrace();
9904                            Slog.d(TAG, "Sending to user " + id + ": "
9905                                    + intent.toShortString(false, true, false, false)
9906                                    + " " + intent.getExtras(), here);
9907                        }
9908                        am.broadcastIntent(null, intent, null, finishedReceiver,
9909                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9910                                null, finishedReceiver != null, false, id);
9911                    }
9912                } catch (RemoteException ex) {
9913                }
9914            }
9915        });
9916    }
9917
9918    /**
9919     * Check if the external storage media is available. This is true if there
9920     * is a mounted external storage medium or if the external storage is
9921     * emulated.
9922     */
9923    private boolean isExternalMediaAvailable() {
9924        return mMediaMounted || Environment.isExternalStorageEmulated();
9925    }
9926
9927    @Override
9928    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9929        // writer
9930        synchronized (mPackages) {
9931            if (!isExternalMediaAvailable()) {
9932                // If the external storage is no longer mounted at this point,
9933                // the caller may not have been able to delete all of this
9934                // packages files and can not delete any more.  Bail.
9935                return null;
9936            }
9937            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9938            if (lastPackage != null) {
9939                pkgs.remove(lastPackage);
9940            }
9941            if (pkgs.size() > 0) {
9942                return pkgs.get(0);
9943            }
9944        }
9945        return null;
9946    }
9947
9948    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9949        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9950                userId, andCode ? 1 : 0, packageName);
9951        if (mSystemReady) {
9952            msg.sendToTarget();
9953        } else {
9954            if (mPostSystemReadyMessages == null) {
9955                mPostSystemReadyMessages = new ArrayList<>();
9956            }
9957            mPostSystemReadyMessages.add(msg);
9958        }
9959    }
9960
9961    void startCleaningPackages() {
9962        // reader
9963        synchronized (mPackages) {
9964            if (!isExternalMediaAvailable()) {
9965                return;
9966            }
9967            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9968                return;
9969            }
9970        }
9971        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9972        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9973        IActivityManager am = ActivityManagerNative.getDefault();
9974        if (am != null) {
9975            try {
9976                am.startService(null, intent, null, mContext.getOpPackageName(),
9977                        UserHandle.USER_SYSTEM);
9978            } catch (RemoteException e) {
9979            }
9980        }
9981    }
9982
9983    @Override
9984    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9985            int installFlags, String installerPackageName, VerificationParams verificationParams,
9986            String packageAbiOverride) {
9987        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9988                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9989    }
9990
9991    @Override
9992    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9993            int installFlags, String installerPackageName, VerificationParams verificationParams,
9994            String packageAbiOverride, int userId) {
9995        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9996
9997        final int callingUid = Binder.getCallingUid();
9998        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9999
10000        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10001            try {
10002                if (observer != null) {
10003                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10004                }
10005            } catch (RemoteException re) {
10006            }
10007            return;
10008        }
10009
10010        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10011            installFlags |= PackageManager.INSTALL_FROM_ADB;
10012
10013        } else {
10014            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10015            // about installerPackageName.
10016
10017            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10018            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10019        }
10020
10021        UserHandle user;
10022        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10023            user = UserHandle.ALL;
10024        } else {
10025            user = new UserHandle(userId);
10026        }
10027
10028        // Only system components can circumvent runtime permissions when installing.
10029        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10030                && mContext.checkCallingOrSelfPermission(Manifest.permission
10031                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10032            throw new SecurityException("You need the "
10033                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10034                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10035        }
10036
10037        verificationParams.setInstallerUid(callingUid);
10038
10039        final File originFile = new File(originPath);
10040        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10041
10042        final Message msg = mHandler.obtainMessage(INIT_COPY);
10043        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10044                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10045        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10046        msg.obj = params;
10047
10048        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10049                System.identityHashCode(msg.obj));
10050        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10051                System.identityHashCode(msg.obj));
10052
10053        mHandler.sendMessage(msg);
10054    }
10055
10056    void installStage(String packageName, File stagedDir, String stagedCid,
10057            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10058            String installerPackageName, int installerUid, UserHandle user) {
10059        if (DEBUG_EPHEMERAL) {
10060            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10061                Slog.d(TAG, "Ephemeral install of " + packageName);
10062            }
10063        }
10064        final VerificationParams verifParams = new VerificationParams(
10065                null, sessionParams.originatingUri, sessionParams.referrerUri,
10066                sessionParams.originatingUid);
10067        verifParams.setInstallerUid(installerUid);
10068
10069        final OriginInfo origin;
10070        if (stagedDir != null) {
10071            origin = OriginInfo.fromStagedFile(stagedDir);
10072        } else {
10073            origin = OriginInfo.fromStagedContainer(stagedCid);
10074        }
10075
10076        final Message msg = mHandler.obtainMessage(INIT_COPY);
10077        final InstallParams params = new InstallParams(origin, null, observer,
10078                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10079                verifParams, user, sessionParams.abiOverride,
10080                sessionParams.grantedRuntimePermissions);
10081        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10082        msg.obj = params;
10083
10084        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10085                System.identityHashCode(msg.obj));
10086        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10087                System.identityHashCode(msg.obj));
10088
10089        mHandler.sendMessage(msg);
10090    }
10091
10092    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10093        Bundle extras = new Bundle(1);
10094        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10095
10096        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10097                packageName, extras, 0, null, null, new int[] {userId});
10098        try {
10099            IActivityManager am = ActivityManagerNative.getDefault();
10100            final boolean isSystem =
10101                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10102            if (isSystem && am.isUserRunning(userId, 0)) {
10103                // The just-installed/enabled app is bundled on the system, so presumed
10104                // to be able to run automatically without needing an explicit launch.
10105                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10106                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10107                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10108                        .setPackage(packageName);
10109                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10110                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10111            }
10112        } catch (RemoteException e) {
10113            // shouldn't happen
10114            Slog.w(TAG, "Unable to bootstrap installed package", e);
10115        }
10116    }
10117
10118    @Override
10119    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10120            int userId) {
10121        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10122        PackageSetting pkgSetting;
10123        final int uid = Binder.getCallingUid();
10124        enforceCrossUserPermission(uid, userId, true, true,
10125                "setApplicationHiddenSetting for user " + userId);
10126
10127        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10128            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10129            return false;
10130        }
10131
10132        long callingId = Binder.clearCallingIdentity();
10133        try {
10134            boolean sendAdded = false;
10135            boolean sendRemoved = false;
10136            // writer
10137            synchronized (mPackages) {
10138                pkgSetting = mSettings.mPackages.get(packageName);
10139                if (pkgSetting == null) {
10140                    return false;
10141                }
10142                if (pkgSetting.getHidden(userId) != hidden) {
10143                    pkgSetting.setHidden(hidden, userId);
10144                    mSettings.writePackageRestrictionsLPr(userId);
10145                    if (hidden) {
10146                        sendRemoved = true;
10147                    } else {
10148                        sendAdded = true;
10149                    }
10150                }
10151            }
10152            if (sendAdded) {
10153                sendPackageAddedForUser(packageName, pkgSetting, userId);
10154                return true;
10155            }
10156            if (sendRemoved) {
10157                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10158                        "hiding pkg");
10159                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10160                return true;
10161            }
10162        } finally {
10163            Binder.restoreCallingIdentity(callingId);
10164        }
10165        return false;
10166    }
10167
10168    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10169            int userId) {
10170        final PackageRemovedInfo info = new PackageRemovedInfo();
10171        info.removedPackage = packageName;
10172        info.removedUsers = new int[] {userId};
10173        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10174        info.sendBroadcast(false, false, false);
10175    }
10176
10177    /**
10178     * Returns true if application is not found or there was an error. Otherwise it returns
10179     * the hidden state of the package for the given user.
10180     */
10181    @Override
10182    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10183        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10184        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10185                false, "getApplicationHidden for user " + userId);
10186        PackageSetting pkgSetting;
10187        long callingId = Binder.clearCallingIdentity();
10188        try {
10189            // writer
10190            synchronized (mPackages) {
10191                pkgSetting = mSettings.mPackages.get(packageName);
10192                if (pkgSetting == null) {
10193                    return true;
10194                }
10195                return pkgSetting.getHidden(userId);
10196            }
10197        } finally {
10198            Binder.restoreCallingIdentity(callingId);
10199        }
10200    }
10201
10202    /**
10203     * @hide
10204     */
10205    @Override
10206    public int installExistingPackageAsUser(String packageName, int userId) {
10207        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10208                null);
10209        PackageSetting pkgSetting;
10210        final int uid = Binder.getCallingUid();
10211        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10212                + userId);
10213        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10214            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10215        }
10216
10217        long callingId = Binder.clearCallingIdentity();
10218        try {
10219            boolean installed = false;
10220
10221            // writer
10222            synchronized (mPackages) {
10223                pkgSetting = mSettings.mPackages.get(packageName);
10224                if (pkgSetting == null) {
10225                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10226                }
10227                if (!pkgSetting.getInstalled(userId)) {
10228                    pkgSetting.setInstalled(true, userId);
10229                    pkgSetting.setHidden(false, userId);
10230                    mSettings.writePackageRestrictionsLPr(userId);
10231                    installed = true;
10232                }
10233            }
10234
10235            if (installed) {
10236                synchronized (mInstallLock) {
10237                    final int flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
10238                    try {
10239                        mInstaller.createAppData(pkgSetting.volumeUuid, packageName, userId, flags,
10240                                pkgSetting.appId, pkgSetting.pkg.applicationInfo.seinfo);
10241                    } catch (InstallerException e) {
10242                        throw new IllegalStateException(e);
10243                    }
10244                }
10245
10246                sendPackageAddedForUser(packageName, pkgSetting, userId);
10247            }
10248        } finally {
10249            Binder.restoreCallingIdentity(callingId);
10250        }
10251
10252        return PackageManager.INSTALL_SUCCEEDED;
10253    }
10254
10255    boolean isUserRestricted(int userId, String restrictionKey) {
10256        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10257        if (restrictions.getBoolean(restrictionKey, false)) {
10258            Log.w(TAG, "User is restricted: " + restrictionKey);
10259            return true;
10260        }
10261        return false;
10262    }
10263
10264    @Override
10265    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10266        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10267        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10268                "setPackageSuspended for user " + userId);
10269
10270        long callingId = Binder.clearCallingIdentity();
10271        try {
10272            synchronized (mPackages) {
10273                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10274                if (pkgSetting != null) {
10275                    if (pkgSetting.getSuspended(userId) != suspended) {
10276                        pkgSetting.setSuspended(suspended, userId);
10277                        mSettings.writePackageRestrictionsLPr(userId);
10278                    }
10279
10280                    // TODO:
10281                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10282                    // * remove app from recents (kill app it if it is running)
10283                    // * erase existing notifications for this app
10284                    return true;
10285                }
10286
10287                return false;
10288            }
10289        } finally {
10290            Binder.restoreCallingIdentity(callingId);
10291        }
10292    }
10293
10294    @Override
10295    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10296        mContext.enforceCallingOrSelfPermission(
10297                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10298                "Only package verification agents can verify applications");
10299
10300        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10301        final PackageVerificationResponse response = new PackageVerificationResponse(
10302                verificationCode, Binder.getCallingUid());
10303        msg.arg1 = id;
10304        msg.obj = response;
10305        mHandler.sendMessage(msg);
10306    }
10307
10308    @Override
10309    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10310            long millisecondsToDelay) {
10311        mContext.enforceCallingOrSelfPermission(
10312                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10313                "Only package verification agents can extend verification timeouts");
10314
10315        final PackageVerificationState state = mPendingVerification.get(id);
10316        final PackageVerificationResponse response = new PackageVerificationResponse(
10317                verificationCodeAtTimeout, Binder.getCallingUid());
10318
10319        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10320            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10321        }
10322        if (millisecondsToDelay < 0) {
10323            millisecondsToDelay = 0;
10324        }
10325        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10326                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10327            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10328        }
10329
10330        if ((state != null) && !state.timeoutExtended()) {
10331            state.extendTimeout();
10332
10333            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10334            msg.arg1 = id;
10335            msg.obj = response;
10336            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10337        }
10338    }
10339
10340    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10341            int verificationCode, UserHandle user) {
10342        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10343        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10344        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10345        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10346        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10347
10348        mContext.sendBroadcastAsUser(intent, user,
10349                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10350    }
10351
10352    private ComponentName matchComponentForVerifier(String packageName,
10353            List<ResolveInfo> receivers) {
10354        ActivityInfo targetReceiver = null;
10355
10356        final int NR = receivers.size();
10357        for (int i = 0; i < NR; i++) {
10358            final ResolveInfo info = receivers.get(i);
10359            if (info.activityInfo == null) {
10360                continue;
10361            }
10362
10363            if (packageName.equals(info.activityInfo.packageName)) {
10364                targetReceiver = info.activityInfo;
10365                break;
10366            }
10367        }
10368
10369        if (targetReceiver == null) {
10370            return null;
10371        }
10372
10373        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10374    }
10375
10376    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10377            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10378        if (pkgInfo.verifiers.length == 0) {
10379            return null;
10380        }
10381
10382        final int N = pkgInfo.verifiers.length;
10383        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10384        for (int i = 0; i < N; i++) {
10385            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10386
10387            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10388                    receivers);
10389            if (comp == null) {
10390                continue;
10391            }
10392
10393            final int verifierUid = getUidForVerifier(verifierInfo);
10394            if (verifierUid == -1) {
10395                continue;
10396            }
10397
10398            if (DEBUG_VERIFY) {
10399                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10400                        + " with the correct signature");
10401            }
10402            sufficientVerifiers.add(comp);
10403            verificationState.addSufficientVerifier(verifierUid);
10404        }
10405
10406        return sufficientVerifiers;
10407    }
10408
10409    private int getUidForVerifier(VerifierInfo verifierInfo) {
10410        synchronized (mPackages) {
10411            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10412            if (pkg == null) {
10413                return -1;
10414            } else if (pkg.mSignatures.length != 1) {
10415                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10416                        + " has more than one signature; ignoring");
10417                return -1;
10418            }
10419
10420            /*
10421             * If the public key of the package's signature does not match
10422             * our expected public key, then this is a different package and
10423             * we should skip.
10424             */
10425
10426            final byte[] expectedPublicKey;
10427            try {
10428                final Signature verifierSig = pkg.mSignatures[0];
10429                final PublicKey publicKey = verifierSig.getPublicKey();
10430                expectedPublicKey = publicKey.getEncoded();
10431            } catch (CertificateException e) {
10432                return -1;
10433            }
10434
10435            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10436
10437            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10438                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10439                        + " does not have the expected public key; ignoring");
10440                return -1;
10441            }
10442
10443            return pkg.applicationInfo.uid;
10444        }
10445    }
10446
10447    @Override
10448    public void finishPackageInstall(int token) {
10449        enforceSystemOrRoot("Only the system is allowed to finish installs");
10450
10451        if (DEBUG_INSTALL) {
10452            Slog.v(TAG, "BM finishing package install for " + token);
10453        }
10454        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10455
10456        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10457        mHandler.sendMessage(msg);
10458    }
10459
10460    /**
10461     * Get the verification agent timeout.
10462     *
10463     * @return verification timeout in milliseconds
10464     */
10465    private long getVerificationTimeout() {
10466        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10467                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10468                DEFAULT_VERIFICATION_TIMEOUT);
10469    }
10470
10471    /**
10472     * Get the default verification agent response code.
10473     *
10474     * @return default verification response code
10475     */
10476    private int getDefaultVerificationResponse() {
10477        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10478                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10479                DEFAULT_VERIFICATION_RESPONSE);
10480    }
10481
10482    /**
10483     * Check whether or not package verification has been enabled.
10484     *
10485     * @return true if verification should be performed
10486     */
10487    private boolean isVerificationEnabled(int userId, int installFlags) {
10488        if (!DEFAULT_VERIFY_ENABLE) {
10489            return false;
10490        }
10491        // Ephemeral apps don't get the full verification treatment
10492        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10493            if (DEBUG_EPHEMERAL) {
10494                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10495            }
10496            return false;
10497        }
10498
10499        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10500
10501        // Check if installing from ADB
10502        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10503            // Do not run verification in a test harness environment
10504            if (ActivityManager.isRunningInTestHarness()) {
10505                return false;
10506            }
10507            if (ensureVerifyAppsEnabled) {
10508                return true;
10509            }
10510            // Check if the developer does not want package verification for ADB installs
10511            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10512                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10513                return false;
10514            }
10515        }
10516
10517        if (ensureVerifyAppsEnabled) {
10518            return true;
10519        }
10520
10521        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10522                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10523    }
10524
10525    @Override
10526    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10527            throws RemoteException {
10528        mContext.enforceCallingOrSelfPermission(
10529                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10530                "Only intentfilter verification agents can verify applications");
10531
10532        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10533        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10534                Binder.getCallingUid(), verificationCode, failedDomains);
10535        msg.arg1 = id;
10536        msg.obj = response;
10537        mHandler.sendMessage(msg);
10538    }
10539
10540    @Override
10541    public int getIntentVerificationStatus(String packageName, int userId) {
10542        synchronized (mPackages) {
10543            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10544        }
10545    }
10546
10547    @Override
10548    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10549        mContext.enforceCallingOrSelfPermission(
10550                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10551
10552        boolean result = false;
10553        synchronized (mPackages) {
10554            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10555        }
10556        if (result) {
10557            scheduleWritePackageRestrictionsLocked(userId);
10558        }
10559        return result;
10560    }
10561
10562    @Override
10563    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10564        synchronized (mPackages) {
10565            return mSettings.getIntentFilterVerificationsLPr(packageName);
10566        }
10567    }
10568
10569    @Override
10570    public List<IntentFilter> getAllIntentFilters(String packageName) {
10571        if (TextUtils.isEmpty(packageName)) {
10572            return Collections.<IntentFilter>emptyList();
10573        }
10574        synchronized (mPackages) {
10575            PackageParser.Package pkg = mPackages.get(packageName);
10576            if (pkg == null || pkg.activities == null) {
10577                return Collections.<IntentFilter>emptyList();
10578            }
10579            final int count = pkg.activities.size();
10580            ArrayList<IntentFilter> result = new ArrayList<>();
10581            for (int n=0; n<count; n++) {
10582                PackageParser.Activity activity = pkg.activities.get(n);
10583                if (activity.intents != null && activity.intents.size() > 0) {
10584                    result.addAll(activity.intents);
10585                }
10586            }
10587            return result;
10588        }
10589    }
10590
10591    @Override
10592    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10593        mContext.enforceCallingOrSelfPermission(
10594                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10595
10596        synchronized (mPackages) {
10597            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10598            if (packageName != null) {
10599                result |= updateIntentVerificationStatus(packageName,
10600                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10601                        userId);
10602                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10603                        packageName, userId);
10604            }
10605            return result;
10606        }
10607    }
10608
10609    @Override
10610    public String getDefaultBrowserPackageName(int userId) {
10611        synchronized (mPackages) {
10612            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10613        }
10614    }
10615
10616    /**
10617     * Get the "allow unknown sources" setting.
10618     *
10619     * @return the current "allow unknown sources" setting
10620     */
10621    private int getUnknownSourcesSettings() {
10622        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10623                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10624                -1);
10625    }
10626
10627    @Override
10628    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10629        final int uid = Binder.getCallingUid();
10630        // writer
10631        synchronized (mPackages) {
10632            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10633            if (targetPackageSetting == null) {
10634                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10635            }
10636
10637            PackageSetting installerPackageSetting;
10638            if (installerPackageName != null) {
10639                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10640                if (installerPackageSetting == null) {
10641                    throw new IllegalArgumentException("Unknown installer package: "
10642                            + installerPackageName);
10643                }
10644            } else {
10645                installerPackageSetting = null;
10646            }
10647
10648            Signature[] callerSignature;
10649            Object obj = mSettings.getUserIdLPr(uid);
10650            if (obj != null) {
10651                if (obj instanceof SharedUserSetting) {
10652                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10653                } else if (obj instanceof PackageSetting) {
10654                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10655                } else {
10656                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10657                }
10658            } else {
10659                throw new SecurityException("Unknown calling UID: " + uid);
10660            }
10661
10662            // Verify: can't set installerPackageName to a package that is
10663            // not signed with the same cert as the caller.
10664            if (installerPackageSetting != null) {
10665                if (compareSignatures(callerSignature,
10666                        installerPackageSetting.signatures.mSignatures)
10667                        != PackageManager.SIGNATURE_MATCH) {
10668                    throw new SecurityException(
10669                            "Caller does not have same cert as new installer package "
10670                            + installerPackageName);
10671                }
10672            }
10673
10674            // Verify: if target already has an installer package, it must
10675            // be signed with the same cert as the caller.
10676            if (targetPackageSetting.installerPackageName != null) {
10677                PackageSetting setting = mSettings.mPackages.get(
10678                        targetPackageSetting.installerPackageName);
10679                // If the currently set package isn't valid, then it's always
10680                // okay to change it.
10681                if (setting != null) {
10682                    if (compareSignatures(callerSignature,
10683                            setting.signatures.mSignatures)
10684                            != PackageManager.SIGNATURE_MATCH) {
10685                        throw new SecurityException(
10686                                "Caller does not have same cert as old installer package "
10687                                + targetPackageSetting.installerPackageName);
10688                    }
10689                }
10690            }
10691
10692            // Okay!
10693            targetPackageSetting.installerPackageName = installerPackageName;
10694            scheduleWriteSettingsLocked();
10695        }
10696    }
10697
10698    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10699        // Queue up an async operation since the package installation may take a little while.
10700        mHandler.post(new Runnable() {
10701            public void run() {
10702                mHandler.removeCallbacks(this);
10703                 // Result object to be returned
10704                PackageInstalledInfo res = new PackageInstalledInfo();
10705                res.returnCode = currentStatus;
10706                res.uid = -1;
10707                res.pkg = null;
10708                res.removedInfo = new PackageRemovedInfo();
10709                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10710                    args.doPreInstall(res.returnCode);
10711                    synchronized (mInstallLock) {
10712                        installPackageTracedLI(args, res);
10713                    }
10714                    args.doPostInstall(res.returnCode, res.uid);
10715                }
10716
10717                // A restore should be performed at this point if (a) the install
10718                // succeeded, (b) the operation is not an update, and (c) the new
10719                // package has not opted out of backup participation.
10720                final boolean update = res.removedInfo.removedPackage != null;
10721                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10722                boolean doRestore = !update
10723                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10724
10725                // Set up the post-install work request bookkeeping.  This will be used
10726                // and cleaned up by the post-install event handling regardless of whether
10727                // there's a restore pass performed.  Token values are >= 1.
10728                int token;
10729                if (mNextInstallToken < 0) mNextInstallToken = 1;
10730                token = mNextInstallToken++;
10731
10732                PostInstallData data = new PostInstallData(args, res);
10733                mRunningInstalls.put(token, data);
10734                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10735
10736                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10737                    // Pass responsibility to the Backup Manager.  It will perform a
10738                    // restore if appropriate, then pass responsibility back to the
10739                    // Package Manager to run the post-install observer callbacks
10740                    // and broadcasts.
10741                    IBackupManager bm = IBackupManager.Stub.asInterface(
10742                            ServiceManager.getService(Context.BACKUP_SERVICE));
10743                    if (bm != null) {
10744                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10745                                + " to BM for possible restore");
10746                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10747                        try {
10748                            // TODO: http://b/22388012
10749                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10750                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10751                            } else {
10752                                doRestore = false;
10753                            }
10754                        } catch (RemoteException e) {
10755                            // can't happen; the backup manager is local
10756                        } catch (Exception e) {
10757                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10758                            doRestore = false;
10759                        }
10760                    } else {
10761                        Slog.e(TAG, "Backup Manager not found!");
10762                        doRestore = false;
10763                    }
10764                }
10765
10766                if (!doRestore) {
10767                    // No restore possible, or the Backup Manager was mysteriously not
10768                    // available -- just fire the post-install work request directly.
10769                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10770
10771                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10772
10773                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10774                    mHandler.sendMessage(msg);
10775                }
10776            }
10777        });
10778    }
10779
10780    private abstract class HandlerParams {
10781        private static final int MAX_RETRIES = 4;
10782
10783        /**
10784         * Number of times startCopy() has been attempted and had a non-fatal
10785         * error.
10786         */
10787        private int mRetries = 0;
10788
10789        /** User handle for the user requesting the information or installation. */
10790        private final UserHandle mUser;
10791        String traceMethod;
10792        int traceCookie;
10793
10794        HandlerParams(UserHandle user) {
10795            mUser = user;
10796        }
10797
10798        UserHandle getUser() {
10799            return mUser;
10800        }
10801
10802        HandlerParams setTraceMethod(String traceMethod) {
10803            this.traceMethod = traceMethod;
10804            return this;
10805        }
10806
10807        HandlerParams setTraceCookie(int traceCookie) {
10808            this.traceCookie = traceCookie;
10809            return this;
10810        }
10811
10812        final boolean startCopy() {
10813            boolean res;
10814            try {
10815                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10816
10817                if (++mRetries > MAX_RETRIES) {
10818                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10819                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10820                    handleServiceError();
10821                    return false;
10822                } else {
10823                    handleStartCopy();
10824                    res = true;
10825                }
10826            } catch (RemoteException e) {
10827                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10828                mHandler.sendEmptyMessage(MCS_RECONNECT);
10829                res = false;
10830            }
10831            handleReturnCode();
10832            return res;
10833        }
10834
10835        final void serviceError() {
10836            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10837            handleServiceError();
10838            handleReturnCode();
10839        }
10840
10841        abstract void handleStartCopy() throws RemoteException;
10842        abstract void handleServiceError();
10843        abstract void handleReturnCode();
10844    }
10845
10846    class MeasureParams extends HandlerParams {
10847        private final PackageStats mStats;
10848        private boolean mSuccess;
10849
10850        private final IPackageStatsObserver mObserver;
10851
10852        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10853            super(new UserHandle(stats.userHandle));
10854            mObserver = observer;
10855            mStats = stats;
10856        }
10857
10858        @Override
10859        public String toString() {
10860            return "MeasureParams{"
10861                + Integer.toHexString(System.identityHashCode(this))
10862                + " " + mStats.packageName + "}";
10863        }
10864
10865        @Override
10866        void handleStartCopy() throws RemoteException {
10867            synchronized (mInstallLock) {
10868                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10869            }
10870
10871            if (mSuccess) {
10872                final boolean mounted;
10873                if (Environment.isExternalStorageEmulated()) {
10874                    mounted = true;
10875                } else {
10876                    final String status = Environment.getExternalStorageState();
10877                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10878                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10879                }
10880
10881                if (mounted) {
10882                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10883
10884                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10885                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10886
10887                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10888                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10889
10890                    // Always subtract cache size, since it's a subdirectory
10891                    mStats.externalDataSize -= mStats.externalCacheSize;
10892
10893                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10894                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10895
10896                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10897                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10898                }
10899            }
10900        }
10901
10902        @Override
10903        void handleReturnCode() {
10904            if (mObserver != null) {
10905                try {
10906                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10907                } catch (RemoteException e) {
10908                    Slog.i(TAG, "Observer no longer exists.");
10909                }
10910            }
10911        }
10912
10913        @Override
10914        void handleServiceError() {
10915            Slog.e(TAG, "Could not measure application " + mStats.packageName
10916                            + " external storage");
10917        }
10918    }
10919
10920    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10921            throws RemoteException {
10922        long result = 0;
10923        for (File path : paths) {
10924            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10925        }
10926        return result;
10927    }
10928
10929    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10930        for (File path : paths) {
10931            try {
10932                mcs.clearDirectory(path.getAbsolutePath());
10933            } catch (RemoteException e) {
10934            }
10935        }
10936    }
10937
10938    static class OriginInfo {
10939        /**
10940         * Location where install is coming from, before it has been
10941         * copied/renamed into place. This could be a single monolithic APK
10942         * file, or a cluster directory. This location may be untrusted.
10943         */
10944        final File file;
10945        final String cid;
10946
10947        /**
10948         * Flag indicating that {@link #file} or {@link #cid} has already been
10949         * staged, meaning downstream users don't need to defensively copy the
10950         * contents.
10951         */
10952        final boolean staged;
10953
10954        /**
10955         * Flag indicating that {@link #file} or {@link #cid} is an already
10956         * installed app that is being moved.
10957         */
10958        final boolean existing;
10959
10960        final String resolvedPath;
10961        final File resolvedFile;
10962
10963        static OriginInfo fromNothing() {
10964            return new OriginInfo(null, null, false, false);
10965        }
10966
10967        static OriginInfo fromUntrustedFile(File file) {
10968            return new OriginInfo(file, null, false, false);
10969        }
10970
10971        static OriginInfo fromExistingFile(File file) {
10972            return new OriginInfo(file, null, false, true);
10973        }
10974
10975        static OriginInfo fromStagedFile(File file) {
10976            return new OriginInfo(file, null, true, false);
10977        }
10978
10979        static OriginInfo fromStagedContainer(String cid) {
10980            return new OriginInfo(null, cid, true, false);
10981        }
10982
10983        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10984            this.file = file;
10985            this.cid = cid;
10986            this.staged = staged;
10987            this.existing = existing;
10988
10989            if (cid != null) {
10990                resolvedPath = PackageHelper.getSdDir(cid);
10991                resolvedFile = new File(resolvedPath);
10992            } else if (file != null) {
10993                resolvedPath = file.getAbsolutePath();
10994                resolvedFile = file;
10995            } else {
10996                resolvedPath = null;
10997                resolvedFile = null;
10998            }
10999        }
11000    }
11001
11002    static class MoveInfo {
11003        final int moveId;
11004        final String fromUuid;
11005        final String toUuid;
11006        final String packageName;
11007        final String dataAppName;
11008        final int appId;
11009        final String seinfo;
11010
11011        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11012                String dataAppName, int appId, String seinfo) {
11013            this.moveId = moveId;
11014            this.fromUuid = fromUuid;
11015            this.toUuid = toUuid;
11016            this.packageName = packageName;
11017            this.dataAppName = dataAppName;
11018            this.appId = appId;
11019            this.seinfo = seinfo;
11020        }
11021    }
11022
11023    class InstallParams extends HandlerParams {
11024        final OriginInfo origin;
11025        final MoveInfo move;
11026        final IPackageInstallObserver2 observer;
11027        int installFlags;
11028        final String installerPackageName;
11029        final String volumeUuid;
11030        final VerificationParams verificationParams;
11031        private InstallArgs mArgs;
11032        private int mRet;
11033        final String packageAbiOverride;
11034        final String[] grantedRuntimePermissions;
11035
11036        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11037                int installFlags, String installerPackageName, String volumeUuid,
11038                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11039                String[] grantedPermissions) {
11040            super(user);
11041            this.origin = origin;
11042            this.move = move;
11043            this.observer = observer;
11044            this.installFlags = installFlags;
11045            this.installerPackageName = installerPackageName;
11046            this.volumeUuid = volumeUuid;
11047            this.verificationParams = verificationParams;
11048            this.packageAbiOverride = packageAbiOverride;
11049            this.grantedRuntimePermissions = grantedPermissions;
11050        }
11051
11052        @Override
11053        public String toString() {
11054            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11055                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11056        }
11057
11058        private int installLocationPolicy(PackageInfoLite pkgLite) {
11059            String packageName = pkgLite.packageName;
11060            int installLocation = pkgLite.installLocation;
11061            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11062            // reader
11063            synchronized (mPackages) {
11064                PackageParser.Package pkg = mPackages.get(packageName);
11065                if (pkg != null) {
11066                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11067                        // Check for downgrading.
11068                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11069                            try {
11070                                checkDowngrade(pkg, pkgLite);
11071                            } catch (PackageManagerException e) {
11072                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11073                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11074                            }
11075                        }
11076                        // Check for updated system application.
11077                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11078                            if (onSd) {
11079                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11080                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11081                            }
11082                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11083                        } else {
11084                            if (onSd) {
11085                                // Install flag overrides everything.
11086                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11087                            }
11088                            // If current upgrade specifies particular preference
11089                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11090                                // Application explicitly specified internal.
11091                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11092                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11093                                // App explictly prefers external. Let policy decide
11094                            } else {
11095                                // Prefer previous location
11096                                if (isExternal(pkg)) {
11097                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11098                                }
11099                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11100                            }
11101                        }
11102                    } else {
11103                        // Invalid install. Return error code
11104                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11105                    }
11106                }
11107            }
11108            // All the special cases have been taken care of.
11109            // Return result based on recommended install location.
11110            if (onSd) {
11111                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11112            }
11113            return pkgLite.recommendedInstallLocation;
11114        }
11115
11116        /*
11117         * Invoke remote method to get package information and install
11118         * location values. Override install location based on default
11119         * policy if needed and then create install arguments based
11120         * on the install location.
11121         */
11122        public void handleStartCopy() throws RemoteException {
11123            int ret = PackageManager.INSTALL_SUCCEEDED;
11124
11125            // If we're already staged, we've firmly committed to an install location
11126            if (origin.staged) {
11127                if (origin.file != null) {
11128                    installFlags |= PackageManager.INSTALL_INTERNAL;
11129                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11130                } else if (origin.cid != null) {
11131                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11132                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11133                } else {
11134                    throw new IllegalStateException("Invalid stage location");
11135                }
11136            }
11137
11138            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11139            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11140            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11141            PackageInfoLite pkgLite = null;
11142
11143            if (onInt && onSd) {
11144                // Check if both bits are set.
11145                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11146                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11147            } else if (onSd && ephemeral) {
11148                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11149                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11150            } else {
11151                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11152                        packageAbiOverride);
11153
11154                if (DEBUG_EPHEMERAL && ephemeral) {
11155                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11156                }
11157
11158                /*
11159                 * If we have too little free space, try to free cache
11160                 * before giving up.
11161                 */
11162                if (!origin.staged && pkgLite.recommendedInstallLocation
11163                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11164                    // TODO: focus freeing disk space on the target device
11165                    final StorageManager storage = StorageManager.from(mContext);
11166                    final long lowThreshold = storage.getStorageLowBytes(
11167                            Environment.getDataDirectory());
11168
11169                    final long sizeBytes = mContainerService.calculateInstalledSize(
11170                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11171
11172                    try {
11173                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11174                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11175                                installFlags, packageAbiOverride);
11176                    } catch (InstallerException e) {
11177                        Slog.w(TAG, "Failed to free cache", e);
11178                    }
11179
11180                    /*
11181                     * The cache free must have deleted the file we
11182                     * downloaded to install.
11183                     *
11184                     * TODO: fix the "freeCache" call to not delete
11185                     *       the file we care about.
11186                     */
11187                    if (pkgLite.recommendedInstallLocation
11188                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11189                        pkgLite.recommendedInstallLocation
11190                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11191                    }
11192                }
11193            }
11194
11195            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11196                int loc = pkgLite.recommendedInstallLocation;
11197                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11198                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11199                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11200                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11201                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11202                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11203                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11204                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11205                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11206                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11207                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11208                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11209                } else {
11210                    // Override with defaults if needed.
11211                    loc = installLocationPolicy(pkgLite);
11212                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11213                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11214                    } else if (!onSd && !onInt) {
11215                        // Override install location with flags
11216                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11217                            // Set the flag to install on external media.
11218                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11219                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11220                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11221                            if (DEBUG_EPHEMERAL) {
11222                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11223                            }
11224                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11225                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11226                                    |PackageManager.INSTALL_INTERNAL);
11227                        } else {
11228                            // Make sure the flag for installing on external
11229                            // media is unset
11230                            installFlags |= PackageManager.INSTALL_INTERNAL;
11231                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11232                        }
11233                    }
11234                }
11235            }
11236
11237            final InstallArgs args = createInstallArgs(this);
11238            mArgs = args;
11239
11240            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11241                // TODO: http://b/22976637
11242                // Apps installed for "all" users use the device owner to verify the app
11243                UserHandle verifierUser = getUser();
11244                if (verifierUser == UserHandle.ALL) {
11245                    verifierUser = UserHandle.SYSTEM;
11246                }
11247
11248                /*
11249                 * Determine if we have any installed package verifiers. If we
11250                 * do, then we'll defer to them to verify the packages.
11251                 */
11252                final int requiredUid = mRequiredVerifierPackage == null ? -1
11253                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11254                                verifierUser.getIdentifier());
11255                if (!origin.existing && requiredUid != -1
11256                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11257                    final Intent verification = new Intent(
11258                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11259                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11260                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11261                            PACKAGE_MIME_TYPE);
11262                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11263
11264                    // Query all live verifiers based on current user state
11265                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11266                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11267
11268                    if (DEBUG_VERIFY) {
11269                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11270                                + verification.toString() + " with " + pkgLite.verifiers.length
11271                                + " optional verifiers");
11272                    }
11273
11274                    final int verificationId = mPendingVerificationToken++;
11275
11276                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11277
11278                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11279                            installerPackageName);
11280
11281                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11282                            installFlags);
11283
11284                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11285                            pkgLite.packageName);
11286
11287                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11288                            pkgLite.versionCode);
11289
11290                    if (verificationParams != null) {
11291                        if (verificationParams.getVerificationURI() != null) {
11292                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11293                                 verificationParams.getVerificationURI());
11294                        }
11295                        if (verificationParams.getOriginatingURI() != null) {
11296                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11297                                  verificationParams.getOriginatingURI());
11298                        }
11299                        if (verificationParams.getReferrer() != null) {
11300                            verification.putExtra(Intent.EXTRA_REFERRER,
11301                                  verificationParams.getReferrer());
11302                        }
11303                        if (verificationParams.getOriginatingUid() >= 0) {
11304                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11305                                  verificationParams.getOriginatingUid());
11306                        }
11307                        if (verificationParams.getInstallerUid() >= 0) {
11308                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11309                                  verificationParams.getInstallerUid());
11310                        }
11311                    }
11312
11313                    final PackageVerificationState verificationState = new PackageVerificationState(
11314                            requiredUid, args);
11315
11316                    mPendingVerification.append(verificationId, verificationState);
11317
11318                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11319                            receivers, verificationState);
11320
11321                    /*
11322                     * If any sufficient verifiers were listed in the package
11323                     * manifest, attempt to ask them.
11324                     */
11325                    if (sufficientVerifiers != null) {
11326                        final int N = sufficientVerifiers.size();
11327                        if (N == 0) {
11328                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11329                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11330                        } else {
11331                            for (int i = 0; i < N; i++) {
11332                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11333
11334                                final Intent sufficientIntent = new Intent(verification);
11335                                sufficientIntent.setComponent(verifierComponent);
11336                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11337                            }
11338                        }
11339                    }
11340
11341                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11342                            mRequiredVerifierPackage, receivers);
11343                    if (ret == PackageManager.INSTALL_SUCCEEDED
11344                            && mRequiredVerifierPackage != null) {
11345                        Trace.asyncTraceBegin(
11346                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11347                        /*
11348                         * Send the intent to the required verification agent,
11349                         * but only start the verification timeout after the
11350                         * target BroadcastReceivers have run.
11351                         */
11352                        verification.setComponent(requiredVerifierComponent);
11353                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11354                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11355                                new BroadcastReceiver() {
11356                                    @Override
11357                                    public void onReceive(Context context, Intent intent) {
11358                                        final Message msg = mHandler
11359                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11360                                        msg.arg1 = verificationId;
11361                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11362                                    }
11363                                }, null, 0, null, null);
11364
11365                        /*
11366                         * We don't want the copy to proceed until verification
11367                         * succeeds, so null out this field.
11368                         */
11369                        mArgs = null;
11370                    }
11371                } else {
11372                    /*
11373                     * No package verification is enabled, so immediately start
11374                     * the remote call to initiate copy using temporary file.
11375                     */
11376                    ret = args.copyApk(mContainerService, true);
11377                }
11378            }
11379
11380            mRet = ret;
11381        }
11382
11383        @Override
11384        void handleReturnCode() {
11385            // If mArgs is null, then MCS couldn't be reached. When it
11386            // reconnects, it will try again to install. At that point, this
11387            // will succeed.
11388            if (mArgs != null) {
11389                processPendingInstall(mArgs, mRet);
11390            }
11391        }
11392
11393        @Override
11394        void handleServiceError() {
11395            mArgs = createInstallArgs(this);
11396            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11397        }
11398
11399        public boolean isForwardLocked() {
11400            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11401        }
11402    }
11403
11404    /**
11405     * Used during creation of InstallArgs
11406     *
11407     * @param installFlags package installation flags
11408     * @return true if should be installed on external storage
11409     */
11410    private static boolean installOnExternalAsec(int installFlags) {
11411        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11412            return false;
11413        }
11414        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11415            return true;
11416        }
11417        return false;
11418    }
11419
11420    /**
11421     * Used during creation of InstallArgs
11422     *
11423     * @param installFlags package installation flags
11424     * @return true if should be installed as forward locked
11425     */
11426    private static boolean installForwardLocked(int installFlags) {
11427        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11428    }
11429
11430    private InstallArgs createInstallArgs(InstallParams params) {
11431        if (params.move != null) {
11432            return new MoveInstallArgs(params);
11433        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11434            return new AsecInstallArgs(params);
11435        } else {
11436            return new FileInstallArgs(params);
11437        }
11438    }
11439
11440    /**
11441     * Create args that describe an existing installed package. Typically used
11442     * when cleaning up old installs, or used as a move source.
11443     */
11444    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11445            String resourcePath, String[] instructionSets) {
11446        final boolean isInAsec;
11447        if (installOnExternalAsec(installFlags)) {
11448            /* Apps on SD card are always in ASEC containers. */
11449            isInAsec = true;
11450        } else if (installForwardLocked(installFlags)
11451                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11452            /*
11453             * Forward-locked apps are only in ASEC containers if they're the
11454             * new style
11455             */
11456            isInAsec = true;
11457        } else {
11458            isInAsec = false;
11459        }
11460
11461        if (isInAsec) {
11462            return new AsecInstallArgs(codePath, instructionSets,
11463                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11464        } else {
11465            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11466        }
11467    }
11468
11469    static abstract class InstallArgs {
11470        /** @see InstallParams#origin */
11471        final OriginInfo origin;
11472        /** @see InstallParams#move */
11473        final MoveInfo move;
11474
11475        final IPackageInstallObserver2 observer;
11476        // Always refers to PackageManager flags only
11477        final int installFlags;
11478        final String installerPackageName;
11479        final String volumeUuid;
11480        final UserHandle user;
11481        final String abiOverride;
11482        final String[] installGrantPermissions;
11483        /** If non-null, drop an async trace when the install completes */
11484        final String traceMethod;
11485        final int traceCookie;
11486
11487        // The list of instruction sets supported by this app. This is currently
11488        // only used during the rmdex() phase to clean up resources. We can get rid of this
11489        // if we move dex files under the common app path.
11490        /* nullable */ String[] instructionSets;
11491
11492        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11493                int installFlags, String installerPackageName, String volumeUuid,
11494                UserHandle user, String[] instructionSets,
11495                String abiOverride, String[] installGrantPermissions,
11496                String traceMethod, int traceCookie) {
11497            this.origin = origin;
11498            this.move = move;
11499            this.installFlags = installFlags;
11500            this.observer = observer;
11501            this.installerPackageName = installerPackageName;
11502            this.volumeUuid = volumeUuid;
11503            this.user = user;
11504            this.instructionSets = instructionSets;
11505            this.abiOverride = abiOverride;
11506            this.installGrantPermissions = installGrantPermissions;
11507            this.traceMethod = traceMethod;
11508            this.traceCookie = traceCookie;
11509        }
11510
11511        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11512        abstract int doPreInstall(int status);
11513
11514        /**
11515         * Rename package into final resting place. All paths on the given
11516         * scanned package should be updated to reflect the rename.
11517         */
11518        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11519        abstract int doPostInstall(int status, int uid);
11520
11521        /** @see PackageSettingBase#codePathString */
11522        abstract String getCodePath();
11523        /** @see PackageSettingBase#resourcePathString */
11524        abstract String getResourcePath();
11525
11526        // Need installer lock especially for dex file removal.
11527        abstract void cleanUpResourcesLI();
11528        abstract boolean doPostDeleteLI(boolean delete);
11529
11530        /**
11531         * Called before the source arguments are copied. This is used mostly
11532         * for MoveParams when it needs to read the source file to put it in the
11533         * destination.
11534         */
11535        int doPreCopy() {
11536            return PackageManager.INSTALL_SUCCEEDED;
11537        }
11538
11539        /**
11540         * Called after the source arguments are copied. This is used mostly for
11541         * MoveParams when it needs to read the source file to put it in the
11542         * destination.
11543         *
11544         * @return
11545         */
11546        int doPostCopy(int uid) {
11547            return PackageManager.INSTALL_SUCCEEDED;
11548        }
11549
11550        protected boolean isFwdLocked() {
11551            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11552        }
11553
11554        protected boolean isExternalAsec() {
11555            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11556        }
11557
11558        protected boolean isEphemeral() {
11559            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11560        }
11561
11562        UserHandle getUser() {
11563            return user;
11564        }
11565    }
11566
11567    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11568        if (!allCodePaths.isEmpty()) {
11569            if (instructionSets == null) {
11570                throw new IllegalStateException("instructionSet == null");
11571            }
11572            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11573            for (String codePath : allCodePaths) {
11574                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11575                    try {
11576                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11577                    } catch (InstallerException ignored) {
11578                    }
11579                }
11580            }
11581        }
11582    }
11583
11584    /**
11585     * Logic to handle installation of non-ASEC applications, including copying
11586     * and renaming logic.
11587     */
11588    class FileInstallArgs extends InstallArgs {
11589        private File codeFile;
11590        private File resourceFile;
11591
11592        // Example topology:
11593        // /data/app/com.example/base.apk
11594        // /data/app/com.example/split_foo.apk
11595        // /data/app/com.example/lib/arm/libfoo.so
11596        // /data/app/com.example/lib/arm64/libfoo.so
11597        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11598
11599        /** New install */
11600        FileInstallArgs(InstallParams params) {
11601            super(params.origin, params.move, params.observer, params.installFlags,
11602                    params.installerPackageName, params.volumeUuid,
11603                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11604                    params.grantedRuntimePermissions,
11605                    params.traceMethod, params.traceCookie);
11606            if (isFwdLocked()) {
11607                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11608            }
11609        }
11610
11611        /** Existing install */
11612        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11613            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11614                    null, null, null, 0);
11615            this.codeFile = (codePath != null) ? new File(codePath) : null;
11616            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11617        }
11618
11619        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11620            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11621            try {
11622                return doCopyApk(imcs, temp);
11623            } finally {
11624                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11625            }
11626        }
11627
11628        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11629            if (origin.staged) {
11630                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11631                codeFile = origin.file;
11632                resourceFile = origin.file;
11633                return PackageManager.INSTALL_SUCCEEDED;
11634            }
11635
11636            try {
11637                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11638                final File tempDir =
11639                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11640                codeFile = tempDir;
11641                resourceFile = tempDir;
11642            } catch (IOException e) {
11643                Slog.w(TAG, "Failed to create copy file: " + e);
11644                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11645            }
11646
11647            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11648                @Override
11649                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11650                    if (!FileUtils.isValidExtFilename(name)) {
11651                        throw new IllegalArgumentException("Invalid filename: " + name);
11652                    }
11653                    try {
11654                        final File file = new File(codeFile, name);
11655                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11656                                O_RDWR | O_CREAT, 0644);
11657                        Os.chmod(file.getAbsolutePath(), 0644);
11658                        return new ParcelFileDescriptor(fd);
11659                    } catch (ErrnoException e) {
11660                        throw new RemoteException("Failed to open: " + e.getMessage());
11661                    }
11662                }
11663            };
11664
11665            int ret = PackageManager.INSTALL_SUCCEEDED;
11666            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11667            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11668                Slog.e(TAG, "Failed to copy package");
11669                return ret;
11670            }
11671
11672            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11673            NativeLibraryHelper.Handle handle = null;
11674            try {
11675                handle = NativeLibraryHelper.Handle.create(codeFile);
11676                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11677                        abiOverride);
11678            } catch (IOException e) {
11679                Slog.e(TAG, "Copying native libraries failed", e);
11680                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11681            } finally {
11682                IoUtils.closeQuietly(handle);
11683            }
11684
11685            return ret;
11686        }
11687
11688        int doPreInstall(int status) {
11689            if (status != PackageManager.INSTALL_SUCCEEDED) {
11690                cleanUp();
11691            }
11692            return status;
11693        }
11694
11695        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11696            if (status != PackageManager.INSTALL_SUCCEEDED) {
11697                cleanUp();
11698                return false;
11699            }
11700
11701            final File targetDir = codeFile.getParentFile();
11702            final File beforeCodeFile = codeFile;
11703            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11704
11705            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11706            try {
11707                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11708            } catch (ErrnoException e) {
11709                Slog.w(TAG, "Failed to rename", e);
11710                return false;
11711            }
11712
11713            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11714                Slog.w(TAG, "Failed to restorecon");
11715                return false;
11716            }
11717
11718            // Reflect the rename internally
11719            codeFile = afterCodeFile;
11720            resourceFile = afterCodeFile;
11721
11722            // Reflect the rename in scanned details
11723            pkg.codePath = afterCodeFile.getAbsolutePath();
11724            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11725                    pkg.baseCodePath);
11726            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11727                    pkg.splitCodePaths);
11728
11729            // Reflect the rename in app info
11730            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11731            pkg.applicationInfo.setCodePath(pkg.codePath);
11732            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11733            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11734            pkg.applicationInfo.setResourcePath(pkg.codePath);
11735            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11736            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11737
11738            return true;
11739        }
11740
11741        int doPostInstall(int status, int uid) {
11742            if (status != PackageManager.INSTALL_SUCCEEDED) {
11743                cleanUp();
11744            }
11745            return status;
11746        }
11747
11748        @Override
11749        String getCodePath() {
11750            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11751        }
11752
11753        @Override
11754        String getResourcePath() {
11755            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11756        }
11757
11758        private boolean cleanUp() {
11759            if (codeFile == null || !codeFile.exists()) {
11760                return false;
11761            }
11762
11763            removeCodePathLI(codeFile);
11764
11765            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11766                resourceFile.delete();
11767            }
11768
11769            return true;
11770        }
11771
11772        void cleanUpResourcesLI() {
11773            // Try enumerating all code paths before deleting
11774            List<String> allCodePaths = Collections.EMPTY_LIST;
11775            if (codeFile != null && codeFile.exists()) {
11776                try {
11777                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11778                    allCodePaths = pkg.getAllCodePaths();
11779                } catch (PackageParserException e) {
11780                    // Ignored; we tried our best
11781                }
11782            }
11783
11784            cleanUp();
11785            removeDexFiles(allCodePaths, instructionSets);
11786        }
11787
11788        boolean doPostDeleteLI(boolean delete) {
11789            // XXX err, shouldn't we respect the delete flag?
11790            cleanUpResourcesLI();
11791            return true;
11792        }
11793    }
11794
11795    private boolean isAsecExternal(String cid) {
11796        final String asecPath = PackageHelper.getSdFilesystem(cid);
11797        return !asecPath.startsWith(mAsecInternalPath);
11798    }
11799
11800    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11801            PackageManagerException {
11802        if (copyRet < 0) {
11803            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11804                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11805                throw new PackageManagerException(copyRet, message);
11806            }
11807        }
11808    }
11809
11810    /**
11811     * Extract the MountService "container ID" from the full code path of an
11812     * .apk.
11813     */
11814    static String cidFromCodePath(String fullCodePath) {
11815        int eidx = fullCodePath.lastIndexOf("/");
11816        String subStr1 = fullCodePath.substring(0, eidx);
11817        int sidx = subStr1.lastIndexOf("/");
11818        return subStr1.substring(sidx+1, eidx);
11819    }
11820
11821    /**
11822     * Logic to handle installation of ASEC applications, including copying and
11823     * renaming logic.
11824     */
11825    class AsecInstallArgs extends InstallArgs {
11826        static final String RES_FILE_NAME = "pkg.apk";
11827        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11828
11829        String cid;
11830        String packagePath;
11831        String resourcePath;
11832
11833        /** New install */
11834        AsecInstallArgs(InstallParams params) {
11835            super(params.origin, params.move, params.observer, params.installFlags,
11836                    params.installerPackageName, params.volumeUuid,
11837                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11838                    params.grantedRuntimePermissions,
11839                    params.traceMethod, params.traceCookie);
11840        }
11841
11842        /** Existing install */
11843        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11844                        boolean isExternal, boolean isForwardLocked) {
11845            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11846                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11847                    instructionSets, null, null, null, 0);
11848            // Hackily pretend we're still looking at a full code path
11849            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11850                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11851            }
11852
11853            // Extract cid from fullCodePath
11854            int eidx = fullCodePath.lastIndexOf("/");
11855            String subStr1 = fullCodePath.substring(0, eidx);
11856            int sidx = subStr1.lastIndexOf("/");
11857            cid = subStr1.substring(sidx+1, eidx);
11858            setMountPath(subStr1);
11859        }
11860
11861        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11862            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11863                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11864                    instructionSets, null, null, null, 0);
11865            this.cid = cid;
11866            setMountPath(PackageHelper.getSdDir(cid));
11867        }
11868
11869        void createCopyFile() {
11870            cid = mInstallerService.allocateExternalStageCidLegacy();
11871        }
11872
11873        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11874            if (origin.staged && origin.cid != null) {
11875                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11876                cid = origin.cid;
11877                setMountPath(PackageHelper.getSdDir(cid));
11878                return PackageManager.INSTALL_SUCCEEDED;
11879            }
11880
11881            if (temp) {
11882                createCopyFile();
11883            } else {
11884                /*
11885                 * Pre-emptively destroy the container since it's destroyed if
11886                 * copying fails due to it existing anyway.
11887                 */
11888                PackageHelper.destroySdDir(cid);
11889            }
11890
11891            final String newMountPath = imcs.copyPackageToContainer(
11892                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11893                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11894
11895            if (newMountPath != null) {
11896                setMountPath(newMountPath);
11897                return PackageManager.INSTALL_SUCCEEDED;
11898            } else {
11899                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11900            }
11901        }
11902
11903        @Override
11904        String getCodePath() {
11905            return packagePath;
11906        }
11907
11908        @Override
11909        String getResourcePath() {
11910            return resourcePath;
11911        }
11912
11913        int doPreInstall(int status) {
11914            if (status != PackageManager.INSTALL_SUCCEEDED) {
11915                // Destroy container
11916                PackageHelper.destroySdDir(cid);
11917            } else {
11918                boolean mounted = PackageHelper.isContainerMounted(cid);
11919                if (!mounted) {
11920                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11921                            Process.SYSTEM_UID);
11922                    if (newMountPath != null) {
11923                        setMountPath(newMountPath);
11924                    } else {
11925                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11926                    }
11927                }
11928            }
11929            return status;
11930        }
11931
11932        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11933            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11934            String newMountPath = null;
11935            if (PackageHelper.isContainerMounted(cid)) {
11936                // Unmount the container
11937                if (!PackageHelper.unMountSdDir(cid)) {
11938                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11939                    return false;
11940                }
11941            }
11942            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11943                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11944                        " which might be stale. Will try to clean up.");
11945                // Clean up the stale container and proceed to recreate.
11946                if (!PackageHelper.destroySdDir(newCacheId)) {
11947                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11948                    return false;
11949                }
11950                // Successfully cleaned up stale container. Try to rename again.
11951                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11952                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11953                            + " inspite of cleaning it up.");
11954                    return false;
11955                }
11956            }
11957            if (!PackageHelper.isContainerMounted(newCacheId)) {
11958                Slog.w(TAG, "Mounting container " + newCacheId);
11959                newMountPath = PackageHelper.mountSdDir(newCacheId,
11960                        getEncryptKey(), Process.SYSTEM_UID);
11961            } else {
11962                newMountPath = PackageHelper.getSdDir(newCacheId);
11963            }
11964            if (newMountPath == null) {
11965                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11966                return false;
11967            }
11968            Log.i(TAG, "Succesfully renamed " + cid +
11969                    " to " + newCacheId +
11970                    " at new path: " + newMountPath);
11971            cid = newCacheId;
11972
11973            final File beforeCodeFile = new File(packagePath);
11974            setMountPath(newMountPath);
11975            final File afterCodeFile = new File(packagePath);
11976
11977            // Reflect the rename in scanned details
11978            pkg.codePath = afterCodeFile.getAbsolutePath();
11979            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11980                    pkg.baseCodePath);
11981            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11982                    pkg.splitCodePaths);
11983
11984            // Reflect the rename in app info
11985            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11986            pkg.applicationInfo.setCodePath(pkg.codePath);
11987            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11988            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11989            pkg.applicationInfo.setResourcePath(pkg.codePath);
11990            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11991            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11992
11993            return true;
11994        }
11995
11996        private void setMountPath(String mountPath) {
11997            final File mountFile = new File(mountPath);
11998
11999            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12000            if (monolithicFile.exists()) {
12001                packagePath = monolithicFile.getAbsolutePath();
12002                if (isFwdLocked()) {
12003                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12004                } else {
12005                    resourcePath = packagePath;
12006                }
12007            } else {
12008                packagePath = mountFile.getAbsolutePath();
12009                resourcePath = packagePath;
12010            }
12011        }
12012
12013        int doPostInstall(int status, int uid) {
12014            if (status != PackageManager.INSTALL_SUCCEEDED) {
12015                cleanUp();
12016            } else {
12017                final int groupOwner;
12018                final String protectedFile;
12019                if (isFwdLocked()) {
12020                    groupOwner = UserHandle.getSharedAppGid(uid);
12021                    protectedFile = RES_FILE_NAME;
12022                } else {
12023                    groupOwner = -1;
12024                    protectedFile = null;
12025                }
12026
12027                if (uid < Process.FIRST_APPLICATION_UID
12028                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12029                    Slog.e(TAG, "Failed to finalize " + cid);
12030                    PackageHelper.destroySdDir(cid);
12031                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12032                }
12033
12034                boolean mounted = PackageHelper.isContainerMounted(cid);
12035                if (!mounted) {
12036                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12037                }
12038            }
12039            return status;
12040        }
12041
12042        private void cleanUp() {
12043            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12044
12045            // Destroy secure container
12046            PackageHelper.destroySdDir(cid);
12047        }
12048
12049        private List<String> getAllCodePaths() {
12050            final File codeFile = new File(getCodePath());
12051            if (codeFile != null && codeFile.exists()) {
12052                try {
12053                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12054                    return pkg.getAllCodePaths();
12055                } catch (PackageParserException e) {
12056                    // Ignored; we tried our best
12057                }
12058            }
12059            return Collections.EMPTY_LIST;
12060        }
12061
12062        void cleanUpResourcesLI() {
12063            // Enumerate all code paths before deleting
12064            cleanUpResourcesLI(getAllCodePaths());
12065        }
12066
12067        private void cleanUpResourcesLI(List<String> allCodePaths) {
12068            cleanUp();
12069            removeDexFiles(allCodePaths, instructionSets);
12070        }
12071
12072        String getPackageName() {
12073            return getAsecPackageName(cid);
12074        }
12075
12076        boolean doPostDeleteLI(boolean delete) {
12077            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12078            final List<String> allCodePaths = getAllCodePaths();
12079            boolean mounted = PackageHelper.isContainerMounted(cid);
12080            if (mounted) {
12081                // Unmount first
12082                if (PackageHelper.unMountSdDir(cid)) {
12083                    mounted = false;
12084                }
12085            }
12086            if (!mounted && delete) {
12087                cleanUpResourcesLI(allCodePaths);
12088            }
12089            return !mounted;
12090        }
12091
12092        @Override
12093        int doPreCopy() {
12094            if (isFwdLocked()) {
12095                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12096                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12097                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12098                }
12099            }
12100
12101            return PackageManager.INSTALL_SUCCEEDED;
12102        }
12103
12104        @Override
12105        int doPostCopy(int uid) {
12106            if (isFwdLocked()) {
12107                if (uid < Process.FIRST_APPLICATION_UID
12108                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12109                                RES_FILE_NAME)) {
12110                    Slog.e(TAG, "Failed to finalize " + cid);
12111                    PackageHelper.destroySdDir(cid);
12112                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12113                }
12114            }
12115
12116            return PackageManager.INSTALL_SUCCEEDED;
12117        }
12118    }
12119
12120    /**
12121     * Logic to handle movement of existing installed applications.
12122     */
12123    class MoveInstallArgs extends InstallArgs {
12124        private File codeFile;
12125        private File resourceFile;
12126
12127        /** New install */
12128        MoveInstallArgs(InstallParams params) {
12129            super(params.origin, params.move, params.observer, params.installFlags,
12130                    params.installerPackageName, params.volumeUuid,
12131                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12132                    params.grantedRuntimePermissions,
12133                    params.traceMethod, params.traceCookie);
12134        }
12135
12136        int copyApk(IMediaContainerService imcs, boolean temp) {
12137            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12138                    + move.fromUuid + " to " + move.toUuid);
12139            synchronized (mInstaller) {
12140                try {
12141                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12142                            move.dataAppName, move.appId, move.seinfo);
12143                } catch (InstallerException e) {
12144                    Slog.w(TAG, "Failed to move app", e);
12145                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12146                }
12147            }
12148
12149            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12150            resourceFile = codeFile;
12151            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12152
12153            return PackageManager.INSTALL_SUCCEEDED;
12154        }
12155
12156        int doPreInstall(int status) {
12157            if (status != PackageManager.INSTALL_SUCCEEDED) {
12158                cleanUp(move.toUuid);
12159            }
12160            return status;
12161        }
12162
12163        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12164            if (status != PackageManager.INSTALL_SUCCEEDED) {
12165                cleanUp(move.toUuid);
12166                return false;
12167            }
12168
12169            // Reflect the move in app info
12170            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12171            pkg.applicationInfo.setCodePath(pkg.codePath);
12172            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12173            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12174            pkg.applicationInfo.setResourcePath(pkg.codePath);
12175            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12176            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12177
12178            return true;
12179        }
12180
12181        int doPostInstall(int status, int uid) {
12182            if (status == PackageManager.INSTALL_SUCCEEDED) {
12183                cleanUp(move.fromUuid);
12184            } else {
12185                cleanUp(move.toUuid);
12186            }
12187            return status;
12188        }
12189
12190        @Override
12191        String getCodePath() {
12192            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12193        }
12194
12195        @Override
12196        String getResourcePath() {
12197            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12198        }
12199
12200        private boolean cleanUp(String volumeUuid) {
12201            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12202                    move.dataAppName);
12203            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12204            synchronized (mInstallLock) {
12205                // Clean up both app data and code
12206                removeDataDirsLI(volumeUuid, move.packageName);
12207                removeCodePathLI(codeFile);
12208            }
12209            return true;
12210        }
12211
12212        void cleanUpResourcesLI() {
12213            throw new UnsupportedOperationException();
12214        }
12215
12216        boolean doPostDeleteLI(boolean delete) {
12217            throw new UnsupportedOperationException();
12218        }
12219    }
12220
12221    static String getAsecPackageName(String packageCid) {
12222        int idx = packageCid.lastIndexOf("-");
12223        if (idx == -1) {
12224            return packageCid;
12225        }
12226        return packageCid.substring(0, idx);
12227    }
12228
12229    // Utility method used to create code paths based on package name and available index.
12230    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12231        String idxStr = "";
12232        int idx = 1;
12233        // Fall back to default value of idx=1 if prefix is not
12234        // part of oldCodePath
12235        if (oldCodePath != null) {
12236            String subStr = oldCodePath;
12237            // Drop the suffix right away
12238            if (suffix != null && subStr.endsWith(suffix)) {
12239                subStr = subStr.substring(0, subStr.length() - suffix.length());
12240            }
12241            // If oldCodePath already contains prefix find out the
12242            // ending index to either increment or decrement.
12243            int sidx = subStr.lastIndexOf(prefix);
12244            if (sidx != -1) {
12245                subStr = subStr.substring(sidx + prefix.length());
12246                if (subStr != null) {
12247                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12248                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12249                    }
12250                    try {
12251                        idx = Integer.parseInt(subStr);
12252                        if (idx <= 1) {
12253                            idx++;
12254                        } else {
12255                            idx--;
12256                        }
12257                    } catch(NumberFormatException e) {
12258                    }
12259                }
12260            }
12261        }
12262        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12263        return prefix + idxStr;
12264    }
12265
12266    private File getNextCodePath(File targetDir, String packageName) {
12267        int suffix = 1;
12268        File result;
12269        do {
12270            result = new File(targetDir, packageName + "-" + suffix);
12271            suffix++;
12272        } while (result.exists());
12273        return result;
12274    }
12275
12276    // Utility method that returns the relative package path with respect
12277    // to the installation directory. Like say for /data/data/com.test-1.apk
12278    // string com.test-1 is returned.
12279    static String deriveCodePathName(String codePath) {
12280        if (codePath == null) {
12281            return null;
12282        }
12283        final File codeFile = new File(codePath);
12284        final String name = codeFile.getName();
12285        if (codeFile.isDirectory()) {
12286            return name;
12287        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12288            final int lastDot = name.lastIndexOf('.');
12289            return name.substring(0, lastDot);
12290        } else {
12291            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12292            return null;
12293        }
12294    }
12295
12296    static class PackageInstalledInfo {
12297        String name;
12298        int uid;
12299        // The set of users that originally had this package installed.
12300        int[] origUsers;
12301        // The set of users that now have this package installed.
12302        int[] newUsers;
12303        PackageParser.Package pkg;
12304        int returnCode;
12305        String returnMsg;
12306        PackageRemovedInfo removedInfo;
12307
12308        public void setError(int code, String msg) {
12309            returnCode = code;
12310            returnMsg = msg;
12311            Slog.w(TAG, msg);
12312        }
12313
12314        public void setError(String msg, PackageParserException e) {
12315            returnCode = e.error;
12316            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12317            Slog.w(TAG, msg, e);
12318        }
12319
12320        public void setError(String msg, PackageManagerException e) {
12321            returnCode = e.error;
12322            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12323            Slog.w(TAG, msg, e);
12324        }
12325
12326        // In some error cases we want to convey more info back to the observer
12327        String origPackage;
12328        String origPermission;
12329    }
12330
12331    /*
12332     * Install a non-existing package.
12333     */
12334    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12335            UserHandle user, String installerPackageName, String volumeUuid,
12336            PackageInstalledInfo res) {
12337        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12338
12339        // Remember this for later, in case we need to rollback this install
12340        String pkgName = pkg.packageName;
12341
12342        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12343        // TODO: b/23350563
12344        final boolean dataDirExists = Environment
12345                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12346
12347        synchronized(mPackages) {
12348            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12349                // A package with the same name is already installed, though
12350                // it has been renamed to an older name.  The package we
12351                // are trying to install should be installed as an update to
12352                // the existing one, but that has not been requested, so bail.
12353                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12354                        + " without first uninstalling package running as "
12355                        + mSettings.mRenamedPackages.get(pkgName));
12356                return;
12357            }
12358            if (mPackages.containsKey(pkgName)) {
12359                // Don't allow installation over an existing package with the same name.
12360                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12361                        + " without first uninstalling.");
12362                return;
12363            }
12364        }
12365
12366        try {
12367            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12368                    System.currentTimeMillis(), user);
12369
12370            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12371            // delete the partially installed application. the data directory will have to be
12372            // restored if it was already existing
12373            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12374                // remove package from internal structures.  Note that we want deletePackageX to
12375                // delete the package data and cache directories that it created in
12376                // scanPackageLocked, unless those directories existed before we even tried to
12377                // install.
12378                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12379                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12380                                res.removedInfo, true);
12381            }
12382
12383        } catch (PackageManagerException e) {
12384            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12385        }
12386
12387        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12388    }
12389
12390    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12391        // Can't rotate keys during boot or if sharedUser.
12392        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12393                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12394            return false;
12395        }
12396        // app is using upgradeKeySets; make sure all are valid
12397        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12398        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12399        for (int i = 0; i < upgradeKeySets.length; i++) {
12400            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12401                Slog.wtf(TAG, "Package "
12402                         + (oldPs.name != null ? oldPs.name : "<null>")
12403                         + " contains upgrade-key-set reference to unknown key-set: "
12404                         + upgradeKeySets[i]
12405                         + " reverting to signatures check.");
12406                return false;
12407            }
12408        }
12409        return true;
12410    }
12411
12412    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12413        // Upgrade keysets are being used.  Determine if new package has a superset of the
12414        // required keys.
12415        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12416        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12417        for (int i = 0; i < upgradeKeySets.length; i++) {
12418            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12419            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12420                return true;
12421            }
12422        }
12423        return false;
12424    }
12425
12426    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12427            UserHandle user, String installerPackageName, String volumeUuid,
12428            PackageInstalledInfo res) {
12429        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12430
12431        final PackageParser.Package oldPackage;
12432        final String pkgName = pkg.packageName;
12433        final int[] allUsers;
12434        final boolean[] perUserInstalled;
12435
12436        // First find the old package info and check signatures
12437        synchronized(mPackages) {
12438            oldPackage = mPackages.get(pkgName);
12439            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12440            if (isEphemeral && !oldIsEphemeral) {
12441                // can't downgrade from full to ephemeral
12442                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12443                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12444                return;
12445            }
12446            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12447            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12448            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12449                if(!checkUpgradeKeySetLP(ps, pkg)) {
12450                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12451                            "New package not signed by keys specified by upgrade-keysets: "
12452                            + pkgName);
12453                    return;
12454                }
12455            } else {
12456                // default to original signature matching
12457                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12458                    != PackageManager.SIGNATURE_MATCH) {
12459                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12460                            "New package has a different signature: " + pkgName);
12461                    return;
12462                }
12463            }
12464
12465            // In case of rollback, remember per-user/profile install state
12466            allUsers = sUserManager.getUserIds();
12467            perUserInstalled = new boolean[allUsers.length];
12468            for (int i = 0; i < allUsers.length; i++) {
12469                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12470            }
12471        }
12472
12473        boolean sysPkg = (isSystemApp(oldPackage));
12474        if (sysPkg) {
12475            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12476                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12477        } else {
12478            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12479                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12480        }
12481    }
12482
12483    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12484            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12485            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12486            String volumeUuid, PackageInstalledInfo res) {
12487        String pkgName = deletedPackage.packageName;
12488        boolean deletedPkg = true;
12489        boolean updatedSettings = false;
12490
12491        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12492                + deletedPackage);
12493        long origUpdateTime;
12494        if (pkg.mExtras != null) {
12495            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12496        } else {
12497            origUpdateTime = 0;
12498        }
12499
12500        // First delete the existing package while retaining the data directory
12501        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12502                res.removedInfo, true)) {
12503            // If the existing package wasn't successfully deleted
12504            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12505            deletedPkg = false;
12506        } else {
12507            // Successfully deleted the old package; proceed with replace.
12508
12509            // If deleted package lived in a container, give users a chance to
12510            // relinquish resources before killing.
12511            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12512                if (DEBUG_INSTALL) {
12513                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12514                }
12515                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12516                final ArrayList<String> pkgList = new ArrayList<String>(1);
12517                pkgList.add(deletedPackage.applicationInfo.packageName);
12518                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12519            }
12520
12521            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12522            try {
12523                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12524                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12525                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12526                        perUserInstalled, res, user);
12527                updatedSettings = true;
12528            } catch (PackageManagerException e) {
12529                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12530            }
12531        }
12532
12533        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12534            // remove package from internal structures.  Note that we want deletePackageX to
12535            // delete the package data and cache directories that it created in
12536            // scanPackageLocked, unless those directories existed before we even tried to
12537            // install.
12538            if(updatedSettings) {
12539                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12540                deletePackageLI(
12541                        pkgName, null, true, allUsers, perUserInstalled,
12542                        PackageManager.DELETE_KEEP_DATA,
12543                                res.removedInfo, true);
12544            }
12545            // Since we failed to install the new package we need to restore the old
12546            // package that we deleted.
12547            if (deletedPkg) {
12548                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12549                File restoreFile = new File(deletedPackage.codePath);
12550                // Parse old package
12551                boolean oldExternal = isExternal(deletedPackage);
12552                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12553                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12554                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12555                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12556                try {
12557                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12558                            null);
12559                } catch (PackageManagerException e) {
12560                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12561                            + e.getMessage());
12562                    return;
12563                }
12564                // Restore of old package succeeded. Update permissions.
12565                // writer
12566                synchronized (mPackages) {
12567                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12568                            UPDATE_PERMISSIONS_ALL);
12569                    // can downgrade to reader
12570                    mSettings.writeLPr();
12571                }
12572                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12573            }
12574        }
12575    }
12576
12577    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12578            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12579            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12580            String volumeUuid, PackageInstalledInfo res) {
12581        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12582                + ", old=" + deletedPackage);
12583        boolean disabledSystem = false;
12584        boolean updatedSettings = false;
12585        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12586        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12587                != 0) {
12588            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12589        }
12590        String packageName = deletedPackage.packageName;
12591        if (packageName == null) {
12592            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12593                    "Attempt to delete null packageName.");
12594            return;
12595        }
12596        PackageParser.Package oldPkg;
12597        PackageSetting oldPkgSetting;
12598        // reader
12599        synchronized (mPackages) {
12600            oldPkg = mPackages.get(packageName);
12601            oldPkgSetting = mSettings.mPackages.get(packageName);
12602            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12603                    (oldPkgSetting == null)) {
12604                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12605                        "Couldn't find package " + packageName + " information");
12606                return;
12607            }
12608        }
12609
12610        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12611
12612        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12613        res.removedInfo.removedPackage = packageName;
12614        // Remove existing system package
12615        removePackageLI(oldPkgSetting, true);
12616        // writer
12617        synchronized (mPackages) {
12618            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12619            if (!disabledSystem && deletedPackage != null) {
12620                // We didn't need to disable the .apk as a current system package,
12621                // which means we are replacing another update that is already
12622                // installed.  We need to make sure to delete the older one's .apk.
12623                res.removedInfo.args = createInstallArgsForExisting(0,
12624                        deletedPackage.applicationInfo.getCodePath(),
12625                        deletedPackage.applicationInfo.getResourcePath(),
12626                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12627            } else {
12628                res.removedInfo.args = null;
12629            }
12630        }
12631
12632        // Successfully disabled the old package. Now proceed with re-installation
12633        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12634
12635        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12636        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12637
12638        PackageParser.Package newPackage = null;
12639        try {
12640            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12641            if (newPackage.mExtras != null) {
12642                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12643                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12644                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12645
12646                // is the update attempting to change shared user? that isn't going to work...
12647                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12648                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12649                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12650                            + " to " + newPkgSetting.sharedUser);
12651                    updatedSettings = true;
12652                }
12653            }
12654
12655            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12656                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12657                        perUserInstalled, res, user);
12658                updatedSettings = true;
12659            }
12660
12661        } catch (PackageManagerException e) {
12662            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12663        }
12664
12665        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12666            // Re installation failed. Restore old information
12667            // Remove new pkg information
12668            if (newPackage != null) {
12669                removeInstalledPackageLI(newPackage, true);
12670            }
12671            // Add back the old system package
12672            try {
12673                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12674            } catch (PackageManagerException e) {
12675                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12676            }
12677            // Restore the old system information in Settings
12678            synchronized (mPackages) {
12679                if (disabledSystem) {
12680                    mSettings.enableSystemPackageLPw(packageName);
12681                }
12682                if (updatedSettings) {
12683                    mSettings.setInstallerPackageName(packageName,
12684                            oldPkgSetting.installerPackageName);
12685                }
12686                mSettings.writeLPr();
12687            }
12688        }
12689    }
12690
12691    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12692        // Collect all used permissions in the UID
12693        ArraySet<String> usedPermissions = new ArraySet<>();
12694        final int packageCount = su.packages.size();
12695        for (int i = 0; i < packageCount; i++) {
12696            PackageSetting ps = su.packages.valueAt(i);
12697            if (ps.pkg == null) {
12698                continue;
12699            }
12700            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12701            for (int j = 0; j < requestedPermCount; j++) {
12702                String permission = ps.pkg.requestedPermissions.get(j);
12703                BasePermission bp = mSettings.mPermissions.get(permission);
12704                if (bp != null) {
12705                    usedPermissions.add(permission);
12706                }
12707            }
12708        }
12709
12710        PermissionsState permissionsState = su.getPermissionsState();
12711        // Prune install permissions
12712        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12713        final int installPermCount = installPermStates.size();
12714        for (int i = installPermCount - 1; i >= 0;  i--) {
12715            PermissionState permissionState = installPermStates.get(i);
12716            if (!usedPermissions.contains(permissionState.getName())) {
12717                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12718                if (bp != null) {
12719                    permissionsState.revokeInstallPermission(bp);
12720                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12721                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12722                }
12723            }
12724        }
12725
12726        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12727
12728        // Prune runtime permissions
12729        for (int userId : allUserIds) {
12730            List<PermissionState> runtimePermStates = permissionsState
12731                    .getRuntimePermissionStates(userId);
12732            final int runtimePermCount = runtimePermStates.size();
12733            for (int i = runtimePermCount - 1; i >= 0; i--) {
12734                PermissionState permissionState = runtimePermStates.get(i);
12735                if (!usedPermissions.contains(permissionState.getName())) {
12736                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12737                    if (bp != null) {
12738                        permissionsState.revokeRuntimePermission(bp, userId);
12739                        permissionsState.updatePermissionFlags(bp, userId,
12740                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12741                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12742                                runtimePermissionChangedUserIds, userId);
12743                    }
12744                }
12745            }
12746        }
12747
12748        return runtimePermissionChangedUserIds;
12749    }
12750
12751    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12752            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12753            UserHandle user) {
12754        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12755
12756        String pkgName = newPackage.packageName;
12757        synchronized (mPackages) {
12758            //write settings. the installStatus will be incomplete at this stage.
12759            //note that the new package setting would have already been
12760            //added to mPackages. It hasn't been persisted yet.
12761            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12762            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12763            mSettings.writeLPr();
12764            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12765        }
12766
12767        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12768        synchronized (mPackages) {
12769            updatePermissionsLPw(newPackage.packageName, newPackage,
12770                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12771                            ? UPDATE_PERMISSIONS_ALL : 0));
12772            // For system-bundled packages, we assume that installing an upgraded version
12773            // of the package implies that the user actually wants to run that new code,
12774            // so we enable the package.
12775            PackageSetting ps = mSettings.mPackages.get(pkgName);
12776            if (ps != null) {
12777                if (isSystemApp(newPackage)) {
12778                    // NB: implicit assumption that system package upgrades apply to all users
12779                    if (DEBUG_INSTALL) {
12780                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12781                    }
12782                    if (res.origUsers != null) {
12783                        for (int userHandle : res.origUsers) {
12784                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12785                                    userHandle, installerPackageName);
12786                        }
12787                    }
12788                    // Also convey the prior install/uninstall state
12789                    if (allUsers != null && perUserInstalled != null) {
12790                        for (int i = 0; i < allUsers.length; i++) {
12791                            if (DEBUG_INSTALL) {
12792                                Slog.d(TAG, "    user " + allUsers[i]
12793                                        + " => " + perUserInstalled[i]);
12794                            }
12795                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12796                        }
12797                        // these install state changes will be persisted in the
12798                        // upcoming call to mSettings.writeLPr().
12799                    }
12800                }
12801                // It's implied that when a user requests installation, they want the app to be
12802                // installed and enabled.
12803                int userId = user.getIdentifier();
12804                if (userId != UserHandle.USER_ALL) {
12805                    ps.setInstalled(true, userId);
12806                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12807                }
12808            }
12809            res.name = pkgName;
12810            res.uid = newPackage.applicationInfo.uid;
12811            res.pkg = newPackage;
12812            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12813            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12814            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12815            //to update install status
12816            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12817            mSettings.writeLPr();
12818            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12819        }
12820
12821        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12822    }
12823
12824    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12825        try {
12826            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12827            installPackageLI(args, res);
12828        } finally {
12829            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12830        }
12831    }
12832
12833    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12834        final int installFlags = args.installFlags;
12835        final String installerPackageName = args.installerPackageName;
12836        final String volumeUuid = args.volumeUuid;
12837        final File tmpPackageFile = new File(args.getCodePath());
12838        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12839        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12840                || (args.volumeUuid != null));
12841        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12842        boolean replace = false;
12843        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12844        if (args.move != null) {
12845            // moving a complete application; perfom an initial scan on the new install location
12846            scanFlags |= SCAN_INITIAL;
12847        }
12848        // Result object to be returned
12849        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12850
12851        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12852
12853        // Sanity check
12854        if (ephemeral && (forwardLocked || onExternal)) {
12855            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12856                    + " external=" + onExternal);
12857            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12858            return;
12859        }
12860
12861        // Retrieve PackageSettings and parse package
12862        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12863                | PackageParser.PARSE_ENFORCE_CODE
12864                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12865                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12866                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12867        PackageParser pp = new PackageParser();
12868        pp.setSeparateProcesses(mSeparateProcesses);
12869        pp.setDisplayMetrics(mMetrics);
12870
12871        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12872        final PackageParser.Package pkg;
12873        try {
12874            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12875        } catch (PackageParserException e) {
12876            res.setError("Failed parse during installPackageLI", e);
12877            return;
12878        } finally {
12879            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12880        }
12881
12882        // Mark that we have an install time CPU ABI override.
12883        pkg.cpuAbiOverride = args.abiOverride;
12884
12885        String pkgName = res.name = pkg.packageName;
12886        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12887            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12888                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12889                return;
12890            }
12891        }
12892
12893        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12894        try {
12895            pp.collectCertificates(pkg, parseFlags);
12896        } catch (PackageParserException e) {
12897            res.setError("Failed collect during installPackageLI", e);
12898            return;
12899        } finally {
12900            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12901        }
12902
12903        // Get rid of all references to package scan path via parser.
12904        pp = null;
12905        String oldCodePath = null;
12906        boolean systemApp = false;
12907        synchronized (mPackages) {
12908            // Check if installing already existing package
12909            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12910                String oldName = mSettings.mRenamedPackages.get(pkgName);
12911                if (pkg.mOriginalPackages != null
12912                        && pkg.mOriginalPackages.contains(oldName)
12913                        && mPackages.containsKey(oldName)) {
12914                    // This package is derived from an original package,
12915                    // and this device has been updating from that original
12916                    // name.  We must continue using the original name, so
12917                    // rename the new package here.
12918                    pkg.setPackageName(oldName);
12919                    pkgName = pkg.packageName;
12920                    replace = true;
12921                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12922                            + oldName + " pkgName=" + pkgName);
12923                } else if (mPackages.containsKey(pkgName)) {
12924                    // This package, under its official name, already exists
12925                    // on the device; we should replace it.
12926                    replace = true;
12927                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12928                }
12929
12930                // Prevent apps opting out from runtime permissions
12931                if (replace) {
12932                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12933                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12934                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12935                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12936                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12937                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12938                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12939                                        + " doesn't support runtime permissions but the old"
12940                                        + " target SDK " + oldTargetSdk + " does.");
12941                        return;
12942                    }
12943                }
12944            }
12945
12946            PackageSetting ps = mSettings.mPackages.get(pkgName);
12947            if (ps != null) {
12948                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12949
12950                // Quick sanity check that we're signed correctly if updating;
12951                // we'll check this again later when scanning, but we want to
12952                // bail early here before tripping over redefined permissions.
12953                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12954                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12955                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12956                                + pkg.packageName + " upgrade keys do not match the "
12957                                + "previously installed version");
12958                        return;
12959                    }
12960                } else {
12961                    try {
12962                        verifySignaturesLP(ps, pkg);
12963                    } catch (PackageManagerException e) {
12964                        res.setError(e.error, e.getMessage());
12965                        return;
12966                    }
12967                }
12968
12969                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12970                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12971                    systemApp = (ps.pkg.applicationInfo.flags &
12972                            ApplicationInfo.FLAG_SYSTEM) != 0;
12973                }
12974                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12975            }
12976
12977            // Check whether the newly-scanned package wants to define an already-defined perm
12978            int N = pkg.permissions.size();
12979            for (int i = N-1; i >= 0; i--) {
12980                PackageParser.Permission perm = pkg.permissions.get(i);
12981                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12982                if (bp != null) {
12983                    // If the defining package is signed with our cert, it's okay.  This
12984                    // also includes the "updating the same package" case, of course.
12985                    // "updating same package" could also involve key-rotation.
12986                    final boolean sigsOk;
12987                    if (bp.sourcePackage.equals(pkg.packageName)
12988                            && (bp.packageSetting instanceof PackageSetting)
12989                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12990                                    scanFlags))) {
12991                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12992                    } else {
12993                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12994                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12995                    }
12996                    if (!sigsOk) {
12997                        // If the owning package is the system itself, we log but allow
12998                        // install to proceed; we fail the install on all other permission
12999                        // redefinitions.
13000                        if (!bp.sourcePackage.equals("android")) {
13001                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13002                                    + pkg.packageName + " attempting to redeclare permission "
13003                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13004                            res.origPermission = perm.info.name;
13005                            res.origPackage = bp.sourcePackage;
13006                            return;
13007                        } else {
13008                            Slog.w(TAG, "Package " + pkg.packageName
13009                                    + " attempting to redeclare system permission "
13010                                    + perm.info.name + "; ignoring new declaration");
13011                            pkg.permissions.remove(i);
13012                        }
13013                    }
13014                }
13015            }
13016
13017        }
13018
13019        if (systemApp) {
13020            if (onExternal) {
13021                // Abort update; system app can't be replaced with app on sdcard
13022                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13023                        "Cannot install updates to system apps on sdcard");
13024                return;
13025            } else if (ephemeral) {
13026                // Abort update; system app can't be replaced with an ephemeral app
13027                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13028                        "Cannot update a system app with an ephemeral app");
13029                return;
13030            }
13031        }
13032
13033        if (args.move != null) {
13034            // We did an in-place move, so dex is ready to roll
13035            scanFlags |= SCAN_NO_DEX;
13036            scanFlags |= SCAN_MOVE;
13037
13038            synchronized (mPackages) {
13039                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13040                if (ps == null) {
13041                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13042                            "Missing settings for moved package " + pkgName);
13043                }
13044
13045                // We moved the entire application as-is, so bring over the
13046                // previously derived ABI information.
13047                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13048                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13049            }
13050
13051        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13052            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13053            scanFlags |= SCAN_NO_DEX;
13054
13055            try {
13056                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13057                        true /* extract libs */);
13058            } catch (PackageManagerException pme) {
13059                Slog.e(TAG, "Error deriving application ABI", pme);
13060                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13061                return;
13062            }
13063        }
13064
13065        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13066            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13067            return;
13068        }
13069
13070        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13071
13072        if (replace) {
13073            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13074                    installerPackageName, volumeUuid, res);
13075        } else {
13076            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13077                    args.user, installerPackageName, volumeUuid, res);
13078        }
13079        synchronized (mPackages) {
13080            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13081            if (ps != null) {
13082                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13083            }
13084        }
13085    }
13086
13087    private void startIntentFilterVerifications(int userId, boolean replacing,
13088            PackageParser.Package pkg) {
13089        if (mIntentFilterVerifierComponent == null) {
13090            Slog.w(TAG, "No IntentFilter verification will not be done as "
13091                    + "there is no IntentFilterVerifier available!");
13092            return;
13093        }
13094
13095        final int verifierUid = getPackageUid(
13096                mIntentFilterVerifierComponent.getPackageName(),
13097                MATCH_DEBUG_TRIAGED_MISSING,
13098                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13099
13100        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13101        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13102        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13103        mHandler.sendMessage(msg);
13104    }
13105
13106    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13107            PackageParser.Package pkg) {
13108        int size = pkg.activities.size();
13109        if (size == 0) {
13110            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13111                    "No activity, so no need to verify any IntentFilter!");
13112            return;
13113        }
13114
13115        final boolean hasDomainURLs = hasDomainURLs(pkg);
13116        if (!hasDomainURLs) {
13117            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13118                    "No domain URLs, so no need to verify any IntentFilter!");
13119            return;
13120        }
13121
13122        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13123                + " if any IntentFilter from the " + size
13124                + " Activities needs verification ...");
13125
13126        int count = 0;
13127        final String packageName = pkg.packageName;
13128
13129        synchronized (mPackages) {
13130            // If this is a new install and we see that we've already run verification for this
13131            // package, we have nothing to do: it means the state was restored from backup.
13132            if (!replacing) {
13133                IntentFilterVerificationInfo ivi =
13134                        mSettings.getIntentFilterVerificationLPr(packageName);
13135                if (ivi != null) {
13136                    if (DEBUG_DOMAIN_VERIFICATION) {
13137                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13138                                + ivi.getStatusString());
13139                    }
13140                    return;
13141                }
13142            }
13143
13144            // If any filters need to be verified, then all need to be.
13145            boolean needToVerify = false;
13146            for (PackageParser.Activity a : pkg.activities) {
13147                for (ActivityIntentInfo filter : a.intents) {
13148                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13149                        if (DEBUG_DOMAIN_VERIFICATION) {
13150                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13151                        }
13152                        needToVerify = true;
13153                        break;
13154                    }
13155                }
13156            }
13157
13158            if (needToVerify) {
13159                final int verificationId = mIntentFilterVerificationToken++;
13160                for (PackageParser.Activity a : pkg.activities) {
13161                    for (ActivityIntentInfo filter : a.intents) {
13162                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13163                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13164                                    "Verification needed for IntentFilter:" + filter.toString());
13165                            mIntentFilterVerifier.addOneIntentFilterVerification(
13166                                    verifierUid, userId, verificationId, filter, packageName);
13167                            count++;
13168                        }
13169                    }
13170                }
13171            }
13172        }
13173
13174        if (count > 0) {
13175            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13176                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13177                    +  " for userId:" + userId);
13178            mIntentFilterVerifier.startVerifications(userId);
13179        } else {
13180            if (DEBUG_DOMAIN_VERIFICATION) {
13181                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13182            }
13183        }
13184    }
13185
13186    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13187        final ComponentName cn  = filter.activity.getComponentName();
13188        final String packageName = cn.getPackageName();
13189
13190        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13191                packageName);
13192        if (ivi == null) {
13193            return true;
13194        }
13195        int status = ivi.getStatus();
13196        switch (status) {
13197            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13198            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13199                return true;
13200
13201            default:
13202                // Nothing to do
13203                return false;
13204        }
13205    }
13206
13207    private static boolean isMultiArch(ApplicationInfo info) {
13208        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13209    }
13210
13211    private static boolean isExternal(PackageParser.Package pkg) {
13212        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13213    }
13214
13215    private static boolean isExternal(PackageSetting ps) {
13216        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13217    }
13218
13219    private static boolean isEphemeral(PackageParser.Package pkg) {
13220        return pkg.applicationInfo.isEphemeralApp();
13221    }
13222
13223    private static boolean isEphemeral(PackageSetting ps) {
13224        return ps.pkg != null && isEphemeral(ps.pkg);
13225    }
13226
13227    private static boolean isSystemApp(PackageParser.Package pkg) {
13228        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13229    }
13230
13231    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13232        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13233    }
13234
13235    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13236        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13237    }
13238
13239    private static boolean isSystemApp(PackageSetting ps) {
13240        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13241    }
13242
13243    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13244        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13245    }
13246
13247    private int packageFlagsToInstallFlags(PackageSetting ps) {
13248        int installFlags = 0;
13249        if (isEphemeral(ps)) {
13250            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13251        }
13252        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13253            // This existing package was an external ASEC install when we have
13254            // the external flag without a UUID
13255            installFlags |= PackageManager.INSTALL_EXTERNAL;
13256        }
13257        if (ps.isForwardLocked()) {
13258            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13259        }
13260        return installFlags;
13261    }
13262
13263    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13264        if (isExternal(pkg)) {
13265            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13266                return StorageManager.UUID_PRIMARY_PHYSICAL;
13267            } else {
13268                return pkg.volumeUuid;
13269            }
13270        } else {
13271            return StorageManager.UUID_PRIVATE_INTERNAL;
13272        }
13273    }
13274
13275    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13276        if (isExternal(pkg)) {
13277            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13278                return mSettings.getExternalVersion();
13279            } else {
13280                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13281            }
13282        } else {
13283            return mSettings.getInternalVersion();
13284        }
13285    }
13286
13287    private void deleteTempPackageFiles() {
13288        final FilenameFilter filter = new FilenameFilter() {
13289            public boolean accept(File dir, String name) {
13290                return name.startsWith("vmdl") && name.endsWith(".tmp");
13291            }
13292        };
13293        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13294            file.delete();
13295        }
13296    }
13297
13298    @Override
13299    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13300            int flags) {
13301        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13302                flags);
13303    }
13304
13305    @Override
13306    public void deletePackage(final String packageName,
13307            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13308        mContext.enforceCallingOrSelfPermission(
13309                android.Manifest.permission.DELETE_PACKAGES, null);
13310        Preconditions.checkNotNull(packageName);
13311        Preconditions.checkNotNull(observer);
13312        final int uid = Binder.getCallingUid();
13313        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13314        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13315        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13316            mContext.enforceCallingOrSelfPermission(
13317                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13318                    "deletePackage for user " + userId);
13319        }
13320
13321        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13322            try {
13323                observer.onPackageDeleted(packageName,
13324                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13325            } catch (RemoteException re) {
13326            }
13327            return;
13328        }
13329
13330        for (int currentUserId : users) {
13331            if (getBlockUninstallForUser(packageName, currentUserId)) {
13332                try {
13333                    observer.onPackageDeleted(packageName,
13334                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13335                } catch (RemoteException re) {
13336                }
13337                return;
13338            }
13339        }
13340
13341        if (DEBUG_REMOVE) {
13342            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13343        }
13344        // Queue up an async operation since the package deletion may take a little while.
13345        mHandler.post(new Runnable() {
13346            public void run() {
13347                mHandler.removeCallbacks(this);
13348                final int returnCode = deletePackageX(packageName, userId, flags);
13349                try {
13350                    observer.onPackageDeleted(packageName, returnCode, null);
13351                } catch (RemoteException e) {
13352                    Log.i(TAG, "Observer no longer exists.");
13353                } //end catch
13354            } //end run
13355        });
13356    }
13357
13358    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13359        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13360                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13361        try {
13362            if (dpm != null) {
13363                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13364                        /* callingUserOnly =*/ false);
13365                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13366                        : deviceOwnerComponentName.getPackageName();
13367                // Does the package contains the device owner?
13368                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13369                // this check is probably not needed, since DO should be registered as a device
13370                // admin on some user too. (Original bug for this: b/17657954)
13371                if (packageName.equals(deviceOwnerPackageName)) {
13372                    return true;
13373                }
13374                // Does it contain a device admin for any user?
13375                int[] users;
13376                if (userId == UserHandle.USER_ALL) {
13377                    users = sUserManager.getUserIds();
13378                } else {
13379                    users = new int[]{userId};
13380                }
13381                for (int i = 0; i < users.length; ++i) {
13382                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13383                        return true;
13384                    }
13385                }
13386            }
13387        } catch (RemoteException e) {
13388        }
13389        return false;
13390    }
13391
13392    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13393        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13394    }
13395
13396    /**
13397     *  This method is an internal method that could be get invoked either
13398     *  to delete an installed package or to clean up a failed installation.
13399     *  After deleting an installed package, a broadcast is sent to notify any
13400     *  listeners that the package has been installed. For cleaning up a failed
13401     *  installation, the broadcast is not necessary since the package's
13402     *  installation wouldn't have sent the initial broadcast either
13403     *  The key steps in deleting a package are
13404     *  deleting the package information in internal structures like mPackages,
13405     *  deleting the packages base directories through installd
13406     *  updating mSettings to reflect current status
13407     *  persisting settings for later use
13408     *  sending a broadcast if necessary
13409     */
13410    private int deletePackageX(String packageName, int userId, int flags) {
13411        final PackageRemovedInfo info = new PackageRemovedInfo();
13412        final boolean res;
13413
13414        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13415                ? UserHandle.ALL : new UserHandle(userId);
13416
13417        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13418            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13419            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13420        }
13421
13422        boolean removedForAllUsers = false;
13423        boolean systemUpdate = false;
13424
13425        PackageParser.Package uninstalledPkg;
13426
13427        // for the uninstall-updates case and restricted profiles, remember the per-
13428        // userhandle installed state
13429        int[] allUsers;
13430        boolean[] perUserInstalled;
13431        synchronized (mPackages) {
13432            uninstalledPkg = mPackages.get(packageName);
13433            PackageSetting ps = mSettings.mPackages.get(packageName);
13434            allUsers = sUserManager.getUserIds();
13435            perUserInstalled = new boolean[allUsers.length];
13436            for (int i = 0; i < allUsers.length; i++) {
13437                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13438            }
13439        }
13440
13441        synchronized (mInstallLock) {
13442            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13443            res = deletePackageLI(packageName, removeForUser,
13444                    true, allUsers, perUserInstalled,
13445                    flags | REMOVE_CHATTY, info, true);
13446            systemUpdate = info.isRemovedPackageSystemUpdate;
13447            synchronized (mPackages) {
13448                if (res) {
13449                    if (!systemUpdate && mPackages.get(packageName) == null) {
13450                        removedForAllUsers = true;
13451                    }
13452                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13453                }
13454            }
13455            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13456                    + " removedForAllUsers=" + removedForAllUsers);
13457        }
13458
13459        if (res) {
13460            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13461
13462            // If the removed package was a system update, the old system package
13463            // was re-enabled; we need to broadcast this information
13464            if (systemUpdate) {
13465                Bundle extras = new Bundle(1);
13466                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13467                        ? info.removedAppId : info.uid);
13468                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13469
13470                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13471                        extras, 0, null, null, null);
13472                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13473                        extras, 0, null, null, null);
13474                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13475                        null, 0, packageName, null, null);
13476            }
13477        }
13478        // Force a gc here.
13479        Runtime.getRuntime().gc();
13480        // Delete the resources here after sending the broadcast to let
13481        // other processes clean up before deleting resources.
13482        if (info.args != null) {
13483            synchronized (mInstallLock) {
13484                info.args.doPostDeleteLI(true);
13485            }
13486        }
13487
13488        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13489    }
13490
13491    class PackageRemovedInfo {
13492        String removedPackage;
13493        int uid = -1;
13494        int removedAppId = -1;
13495        int[] removedUsers = null;
13496        boolean isRemovedPackageSystemUpdate = false;
13497        // Clean up resources deleted packages.
13498        InstallArgs args = null;
13499
13500        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13501            Bundle extras = new Bundle(1);
13502            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13503            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13504            if (replacing) {
13505                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13506            }
13507            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13508            if (removedPackage != null) {
13509                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13510                        extras, 0, null, null, removedUsers);
13511                if (fullRemove && !replacing) {
13512                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13513                            extras, 0, null, null, removedUsers);
13514                }
13515            }
13516            if (removedAppId >= 0) {
13517                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13518                        removedUsers);
13519            }
13520        }
13521    }
13522
13523    /*
13524     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13525     * flag is not set, the data directory is removed as well.
13526     * make sure this flag is set for partially installed apps. If not its meaningless to
13527     * delete a partially installed application.
13528     */
13529    private void removePackageDataLI(PackageSetting ps,
13530            int[] allUserHandles, boolean[] perUserInstalled,
13531            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13532        String packageName = ps.name;
13533        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13534        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13535        // Retrieve object to delete permissions for shared user later on
13536        final PackageSetting deletedPs;
13537        // reader
13538        synchronized (mPackages) {
13539            deletedPs = mSettings.mPackages.get(packageName);
13540            if (outInfo != null) {
13541                outInfo.removedPackage = packageName;
13542                outInfo.removedUsers = deletedPs != null
13543                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13544                        : null;
13545            }
13546        }
13547        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13548            removeDataDirsLI(ps.volumeUuid, packageName);
13549            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13550        }
13551        // writer
13552        synchronized (mPackages) {
13553            if (deletedPs != null) {
13554                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13555                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13556                    clearDefaultBrowserIfNeeded(packageName);
13557                    if (outInfo != null) {
13558                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13559                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13560                    }
13561                    updatePermissionsLPw(deletedPs.name, null, 0);
13562                    if (deletedPs.sharedUser != null) {
13563                        // Remove permissions associated with package. Since runtime
13564                        // permissions are per user we have to kill the removed package
13565                        // or packages running under the shared user of the removed
13566                        // package if revoking the permissions requested only by the removed
13567                        // package is successful and this causes a change in gids.
13568                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13569                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13570                                    userId);
13571                            if (userIdToKill == UserHandle.USER_ALL
13572                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13573                                // If gids changed for this user, kill all affected packages.
13574                                mHandler.post(new Runnable() {
13575                                    @Override
13576                                    public void run() {
13577                                        // This has to happen with no lock held.
13578                                        killApplication(deletedPs.name, deletedPs.appId,
13579                                                KILL_APP_REASON_GIDS_CHANGED);
13580                                    }
13581                                });
13582                                break;
13583                            }
13584                        }
13585                    }
13586                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13587                }
13588                // make sure to preserve per-user disabled state if this removal was just
13589                // a downgrade of a system app to the factory package
13590                if (allUserHandles != null && perUserInstalled != null) {
13591                    if (DEBUG_REMOVE) {
13592                        Slog.d(TAG, "Propagating install state across downgrade");
13593                    }
13594                    for (int i = 0; i < allUserHandles.length; i++) {
13595                        if (DEBUG_REMOVE) {
13596                            Slog.d(TAG, "    user " + allUserHandles[i]
13597                                    + " => " + perUserInstalled[i]);
13598                        }
13599                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13600                    }
13601                }
13602            }
13603            // can downgrade to reader
13604            if (writeSettings) {
13605                // Save settings now
13606                mSettings.writeLPr();
13607            }
13608        }
13609        if (outInfo != null) {
13610            // A user ID was deleted here. Go through all users and remove it
13611            // from KeyStore.
13612            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13613        }
13614    }
13615
13616    static boolean locationIsPrivileged(File path) {
13617        try {
13618            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13619                    .getCanonicalPath();
13620            return path.getCanonicalPath().startsWith(privilegedAppDir);
13621        } catch (IOException e) {
13622            Slog.e(TAG, "Unable to access code path " + path);
13623        }
13624        return false;
13625    }
13626
13627    /*
13628     * Tries to delete system package.
13629     */
13630    private boolean deleteSystemPackageLI(PackageSetting newPs,
13631            int[] allUserHandles, boolean[] perUserInstalled,
13632            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13633        final boolean applyUserRestrictions
13634                = (allUserHandles != null) && (perUserInstalled != null);
13635        PackageSetting disabledPs = null;
13636        // Confirm if the system package has been updated
13637        // An updated system app can be deleted. This will also have to restore
13638        // the system pkg from system partition
13639        // reader
13640        synchronized (mPackages) {
13641            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13642        }
13643        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13644                + " disabledPs=" + disabledPs);
13645        if (disabledPs == null) {
13646            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13647            return false;
13648        } else if (DEBUG_REMOVE) {
13649            Slog.d(TAG, "Deleting system pkg from data partition");
13650        }
13651        if (DEBUG_REMOVE) {
13652            if (applyUserRestrictions) {
13653                Slog.d(TAG, "Remembering install states:");
13654                for (int i = 0; i < allUserHandles.length; i++) {
13655                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13656                }
13657            }
13658        }
13659        // Delete the updated package
13660        outInfo.isRemovedPackageSystemUpdate = true;
13661        if (disabledPs.versionCode < newPs.versionCode) {
13662            // Delete data for downgrades
13663            flags &= ~PackageManager.DELETE_KEEP_DATA;
13664        } else {
13665            // Preserve data by setting flag
13666            flags |= PackageManager.DELETE_KEEP_DATA;
13667        }
13668        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13669                allUserHandles, perUserInstalled, outInfo, writeSettings);
13670        if (!ret) {
13671            return false;
13672        }
13673        // writer
13674        synchronized (mPackages) {
13675            // Reinstate the old system package
13676            mSettings.enableSystemPackageLPw(newPs.name);
13677            // Remove any native libraries from the upgraded package.
13678            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13679        }
13680        // Install the system package
13681        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13682        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13683        if (locationIsPrivileged(disabledPs.codePath)) {
13684            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13685        }
13686
13687        final PackageParser.Package newPkg;
13688        try {
13689            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13690        } catch (PackageManagerException e) {
13691            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13692            return false;
13693        }
13694
13695        // writer
13696        synchronized (mPackages) {
13697            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13698
13699            // Propagate the permissions state as we do not want to drop on the floor
13700            // runtime permissions. The update permissions method below will take
13701            // care of removing obsolete permissions and grant install permissions.
13702            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13703            updatePermissionsLPw(newPkg.packageName, newPkg,
13704                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13705
13706            if (applyUserRestrictions) {
13707                if (DEBUG_REMOVE) {
13708                    Slog.d(TAG, "Propagating install state across reinstall");
13709                }
13710                for (int i = 0; i < allUserHandles.length; i++) {
13711                    if (DEBUG_REMOVE) {
13712                        Slog.d(TAG, "    user " + allUserHandles[i]
13713                                + " => " + perUserInstalled[i]);
13714                    }
13715                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13716
13717                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13718                }
13719                // Regardless of writeSettings we need to ensure that this restriction
13720                // state propagation is persisted
13721                mSettings.writeAllUsersPackageRestrictionsLPr();
13722            }
13723            // can downgrade to reader here
13724            if (writeSettings) {
13725                mSettings.writeLPr();
13726            }
13727        }
13728        return true;
13729    }
13730
13731    private boolean deleteInstalledPackageLI(PackageSetting ps,
13732            boolean deleteCodeAndResources, int flags,
13733            int[] allUserHandles, boolean[] perUserInstalled,
13734            PackageRemovedInfo outInfo, boolean writeSettings) {
13735        if (outInfo != null) {
13736            outInfo.uid = ps.appId;
13737        }
13738
13739        // Delete package data from internal structures and also remove data if flag is set
13740        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13741
13742        // Delete application code and resources
13743        if (deleteCodeAndResources && (outInfo != null)) {
13744            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13745                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13746            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13747        }
13748        return true;
13749    }
13750
13751    @Override
13752    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13753            int userId) {
13754        mContext.enforceCallingOrSelfPermission(
13755                android.Manifest.permission.DELETE_PACKAGES, null);
13756        synchronized (mPackages) {
13757            PackageSetting ps = mSettings.mPackages.get(packageName);
13758            if (ps == null) {
13759                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13760                return false;
13761            }
13762            if (!ps.getInstalled(userId)) {
13763                // Can't block uninstall for an app that is not installed or enabled.
13764                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13765                return false;
13766            }
13767            ps.setBlockUninstall(blockUninstall, userId);
13768            mSettings.writePackageRestrictionsLPr(userId);
13769        }
13770        return true;
13771    }
13772
13773    @Override
13774    public boolean getBlockUninstallForUser(String packageName, int userId) {
13775        synchronized (mPackages) {
13776            PackageSetting ps = mSettings.mPackages.get(packageName);
13777            if (ps == null) {
13778                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13779                return false;
13780            }
13781            return ps.getBlockUninstall(userId);
13782        }
13783    }
13784
13785    @Override
13786    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13787        int callingUid = Binder.getCallingUid();
13788        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13789            throw new SecurityException(
13790                    "setRequiredForSystemUser can only be run by the system or root");
13791        }
13792        synchronized (mPackages) {
13793            PackageSetting ps = mSettings.mPackages.get(packageName);
13794            if (ps == null) {
13795                Log.w(TAG, "Package doesn't exist: " + packageName);
13796                return false;
13797            }
13798            if (systemUserApp) {
13799                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13800            } else {
13801                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13802            }
13803            mSettings.writeLPr();
13804        }
13805        return true;
13806    }
13807
13808    /*
13809     * This method handles package deletion in general
13810     */
13811    private boolean deletePackageLI(String packageName, UserHandle user,
13812            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13813            int flags, PackageRemovedInfo outInfo,
13814            boolean writeSettings) {
13815        if (packageName == null) {
13816            Slog.w(TAG, "Attempt to delete null packageName.");
13817            return false;
13818        }
13819        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13820        PackageSetting ps;
13821        boolean dataOnly = false;
13822        int removeUser = -1;
13823        int appId = -1;
13824        synchronized (mPackages) {
13825            ps = mSettings.mPackages.get(packageName);
13826            if (ps == null) {
13827                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13828                return false;
13829            }
13830            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13831                    && user.getIdentifier() != UserHandle.USER_ALL) {
13832                // The caller is asking that the package only be deleted for a single
13833                // user.  To do this, we just mark its uninstalled state and delete
13834                // its data.  If this is a system app, we only allow this to happen if
13835                // they have set the special DELETE_SYSTEM_APP which requests different
13836                // semantics than normal for uninstalling system apps.
13837                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13838                final int userId = user.getIdentifier();
13839                ps.setUserState(userId,
13840                        COMPONENT_ENABLED_STATE_DEFAULT,
13841                        false, //installed
13842                        true,  //stopped
13843                        true,  //notLaunched
13844                        false, //hidden
13845                        false, //suspended
13846                        null, null, null,
13847                        false, // blockUninstall
13848                        ps.readUserState(userId).domainVerificationStatus, 0);
13849                if (!isSystemApp(ps)) {
13850                    // Do not uninstall the APK if an app should be cached
13851                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13852                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13853                        // Other user still have this package installed, so all
13854                        // we need to do is clear this user's data and save that
13855                        // it is uninstalled.
13856                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13857                        removeUser = user.getIdentifier();
13858                        appId = ps.appId;
13859                        scheduleWritePackageRestrictionsLocked(removeUser);
13860                    } else {
13861                        // We need to set it back to 'installed' so the uninstall
13862                        // broadcasts will be sent correctly.
13863                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13864                        ps.setInstalled(true, user.getIdentifier());
13865                    }
13866                } else {
13867                    // This is a system app, so we assume that the
13868                    // other users still have this package installed, so all
13869                    // we need to do is clear this user's data and save that
13870                    // it is uninstalled.
13871                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13872                    removeUser = user.getIdentifier();
13873                    appId = ps.appId;
13874                    scheduleWritePackageRestrictionsLocked(removeUser);
13875                }
13876            }
13877        }
13878
13879        if (removeUser >= 0) {
13880            // From above, we determined that we are deleting this only
13881            // for a single user.  Continue the work here.
13882            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13883            if (outInfo != null) {
13884                outInfo.removedPackage = packageName;
13885                outInfo.removedAppId = appId;
13886                outInfo.removedUsers = new int[] {removeUser};
13887            }
13888            // TODO: triage flags as part of 26466827
13889            final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13890            try {
13891                mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags);
13892            } catch (InstallerException e) {
13893                Slog.w(TAG, "Failed to delete app data", e);
13894            }
13895            removeKeystoreDataIfNeeded(removeUser, appId);
13896            schedulePackageCleaning(packageName, removeUser, false);
13897            synchronized (mPackages) {
13898                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13899                    scheduleWritePackageRestrictionsLocked(removeUser);
13900                }
13901                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13902            }
13903            return true;
13904        }
13905
13906        if (dataOnly) {
13907            // Delete application data first
13908            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13909            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13910            return true;
13911        }
13912
13913        boolean ret = false;
13914        if (isSystemApp(ps)) {
13915            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13916            // When an updated system application is deleted we delete the existing resources as well and
13917            // fall back to existing code in system partition
13918            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13919                    flags, outInfo, writeSettings);
13920        } else {
13921            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13922            // Kill application pre-emptively especially for apps on sd.
13923            killApplication(packageName, ps.appId, "uninstall pkg");
13924            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13925                    allUserHandles, perUserInstalled,
13926                    outInfo, writeSettings);
13927        }
13928
13929        return ret;
13930    }
13931
13932    private final static class ClearStorageConnection implements ServiceConnection {
13933        IMediaContainerService mContainerService;
13934
13935        @Override
13936        public void onServiceConnected(ComponentName name, IBinder service) {
13937            synchronized (this) {
13938                mContainerService = IMediaContainerService.Stub.asInterface(service);
13939                notifyAll();
13940            }
13941        }
13942
13943        @Override
13944        public void onServiceDisconnected(ComponentName name) {
13945        }
13946    }
13947
13948    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13949        final boolean mounted;
13950        if (Environment.isExternalStorageEmulated()) {
13951            mounted = true;
13952        } else {
13953            final String status = Environment.getExternalStorageState();
13954
13955            mounted = status.equals(Environment.MEDIA_MOUNTED)
13956                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13957        }
13958
13959        if (!mounted) {
13960            return;
13961        }
13962
13963        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13964        int[] users;
13965        if (userId == UserHandle.USER_ALL) {
13966            users = sUserManager.getUserIds();
13967        } else {
13968            users = new int[] { userId };
13969        }
13970        final ClearStorageConnection conn = new ClearStorageConnection();
13971        if (mContext.bindServiceAsUser(
13972                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13973            try {
13974                for (int curUser : users) {
13975                    long timeout = SystemClock.uptimeMillis() + 5000;
13976                    synchronized (conn) {
13977                        long now = SystemClock.uptimeMillis();
13978                        while (conn.mContainerService == null && now < timeout) {
13979                            try {
13980                                conn.wait(timeout - now);
13981                            } catch (InterruptedException e) {
13982                            }
13983                        }
13984                    }
13985                    if (conn.mContainerService == null) {
13986                        return;
13987                    }
13988
13989                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13990                    clearDirectory(conn.mContainerService,
13991                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13992                    if (allData) {
13993                        clearDirectory(conn.mContainerService,
13994                                userEnv.buildExternalStorageAppDataDirs(packageName));
13995                        clearDirectory(conn.mContainerService,
13996                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13997                    }
13998                }
13999            } finally {
14000                mContext.unbindService(conn);
14001            }
14002        }
14003    }
14004
14005    @Override
14006    public void clearApplicationUserData(final String packageName,
14007            final IPackageDataObserver observer, final int userId) {
14008        mContext.enforceCallingOrSelfPermission(
14009                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14010        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14011        // Queue up an async operation since the package deletion may take a little while.
14012        mHandler.post(new Runnable() {
14013            public void run() {
14014                mHandler.removeCallbacks(this);
14015                final boolean succeeded;
14016                synchronized (mInstallLock) {
14017                    succeeded = clearApplicationUserDataLI(packageName, userId);
14018                }
14019                clearExternalStorageDataSync(packageName, userId, true);
14020                if (succeeded) {
14021                    // invoke DeviceStorageMonitor's update method to clear any notifications
14022                    DeviceStorageMonitorInternal
14023                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14024                    if (dsm != null) {
14025                        dsm.checkMemory();
14026                    }
14027                }
14028                if(observer != null) {
14029                    try {
14030                        observer.onRemoveCompleted(packageName, succeeded);
14031                    } catch (RemoteException e) {
14032                        Log.i(TAG, "Observer no longer exists.");
14033                    }
14034                } //end if observer
14035            } //end run
14036        });
14037    }
14038
14039    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14040        if (packageName == null) {
14041            Slog.w(TAG, "Attempt to delete null packageName.");
14042            return false;
14043        }
14044
14045        // Try finding details about the requested package
14046        PackageParser.Package pkg;
14047        synchronized (mPackages) {
14048            pkg = mPackages.get(packageName);
14049            if (pkg == null) {
14050                final PackageSetting ps = mSettings.mPackages.get(packageName);
14051                if (ps != null) {
14052                    pkg = ps.pkg;
14053                }
14054            }
14055
14056            if (pkg == null) {
14057                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14058                return false;
14059            }
14060
14061            PackageSetting ps = (PackageSetting) pkg.mExtras;
14062            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14063        }
14064
14065        // Always delete data directories for package, even if we found no other
14066        // record of app. This helps users recover from UID mismatches without
14067        // resorting to a full data wipe.
14068        // TODO: triage flags as part of 26466827
14069        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14070        try {
14071            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
14072        } catch (InstallerException e) {
14073            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
14074            return false;
14075        }
14076
14077        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14078        removeKeystoreDataIfNeeded(userId, appId);
14079
14080        // Create a native library symlink only if we have native libraries
14081        // and if the native libraries are 32 bit libraries. We do not provide
14082        // this symlink for 64 bit libraries.
14083        if (pkg.applicationInfo.primaryCpuAbi != null &&
14084                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14085            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14086            try {
14087                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14088                        nativeLibPath, userId);
14089            } catch (InstallerException e) {
14090                Slog.w(TAG, "Failed linking native library dir", e);
14091                return false;
14092            }
14093        }
14094
14095        return true;
14096    }
14097
14098    /**
14099     * Reverts user permission state changes (permissions and flags) in
14100     * all packages for a given user.
14101     *
14102     * @param userId The device user for which to do a reset.
14103     */
14104    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14105        final int packageCount = mPackages.size();
14106        for (int i = 0; i < packageCount; i++) {
14107            PackageParser.Package pkg = mPackages.valueAt(i);
14108            PackageSetting ps = (PackageSetting) pkg.mExtras;
14109            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14110        }
14111    }
14112
14113    /**
14114     * Reverts user permission state changes (permissions and flags).
14115     *
14116     * @param ps The package for which to reset.
14117     * @param userId The device user for which to do a reset.
14118     */
14119    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14120            final PackageSetting ps, final int userId) {
14121        if (ps.pkg == null) {
14122            return;
14123        }
14124
14125        // These are flags that can change base on user actions.
14126        final int userSettableMask = FLAG_PERMISSION_USER_SET
14127                | FLAG_PERMISSION_USER_FIXED
14128                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14129                | FLAG_PERMISSION_REVIEW_REQUIRED;
14130
14131        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14132                | FLAG_PERMISSION_POLICY_FIXED;
14133
14134        boolean writeInstallPermissions = false;
14135        boolean writeRuntimePermissions = false;
14136
14137        final int permissionCount = ps.pkg.requestedPermissions.size();
14138        for (int i = 0; i < permissionCount; i++) {
14139            String permission = ps.pkg.requestedPermissions.get(i);
14140
14141            BasePermission bp = mSettings.mPermissions.get(permission);
14142            if (bp == null) {
14143                continue;
14144            }
14145
14146            // If shared user we just reset the state to which only this app contributed.
14147            if (ps.sharedUser != null) {
14148                boolean used = false;
14149                final int packageCount = ps.sharedUser.packages.size();
14150                for (int j = 0; j < packageCount; j++) {
14151                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14152                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14153                            && pkg.pkg.requestedPermissions.contains(permission)) {
14154                        used = true;
14155                        break;
14156                    }
14157                }
14158                if (used) {
14159                    continue;
14160                }
14161            }
14162
14163            PermissionsState permissionsState = ps.getPermissionsState();
14164
14165            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14166
14167            // Always clear the user settable flags.
14168            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14169                    bp.name) != null;
14170            // If permission review is enabled and this is a legacy app, mark the
14171            // permission as requiring a review as this is the initial state.
14172            int flags = 0;
14173            if (Build.PERMISSIONS_REVIEW_REQUIRED
14174                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14175                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14176            }
14177            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14178                if (hasInstallState) {
14179                    writeInstallPermissions = true;
14180                } else {
14181                    writeRuntimePermissions = true;
14182                }
14183            }
14184
14185            // Below is only runtime permission handling.
14186            if (!bp.isRuntime()) {
14187                continue;
14188            }
14189
14190            // Never clobber system or policy.
14191            if ((oldFlags & policyOrSystemFlags) != 0) {
14192                continue;
14193            }
14194
14195            // If this permission was granted by default, make sure it is.
14196            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14197                if (permissionsState.grantRuntimePermission(bp, userId)
14198                        != PERMISSION_OPERATION_FAILURE) {
14199                    writeRuntimePermissions = true;
14200                }
14201            // If permission review is enabled the permissions for a legacy apps
14202            // are represented as constantly granted runtime ones, so don't revoke.
14203            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14204                // Otherwise, reset the permission.
14205                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14206                switch (revokeResult) {
14207                    case PERMISSION_OPERATION_SUCCESS: {
14208                        writeRuntimePermissions = true;
14209                    } break;
14210
14211                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14212                        writeRuntimePermissions = true;
14213                        final int appId = ps.appId;
14214                        mHandler.post(new Runnable() {
14215                            @Override
14216                            public void run() {
14217                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14218                            }
14219                        });
14220                    } break;
14221                }
14222            }
14223        }
14224
14225        // Synchronously write as we are taking permissions away.
14226        if (writeRuntimePermissions) {
14227            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14228        }
14229
14230        // Synchronously write as we are taking permissions away.
14231        if (writeInstallPermissions) {
14232            mSettings.writeLPr();
14233        }
14234    }
14235
14236    /**
14237     * Remove entries from the keystore daemon. Will only remove it if the
14238     * {@code appId} is valid.
14239     */
14240    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14241        if (appId < 0) {
14242            return;
14243        }
14244
14245        final KeyStore keyStore = KeyStore.getInstance();
14246        if (keyStore != null) {
14247            if (userId == UserHandle.USER_ALL) {
14248                for (final int individual : sUserManager.getUserIds()) {
14249                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14250                }
14251            } else {
14252                keyStore.clearUid(UserHandle.getUid(userId, appId));
14253            }
14254        } else {
14255            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14256        }
14257    }
14258
14259    @Override
14260    public void deleteApplicationCacheFiles(final String packageName,
14261            final IPackageDataObserver observer) {
14262        mContext.enforceCallingOrSelfPermission(
14263                android.Manifest.permission.DELETE_CACHE_FILES, null);
14264        // Queue up an async operation since the package deletion may take a little while.
14265        final int userId = UserHandle.getCallingUserId();
14266        mHandler.post(new Runnable() {
14267            public void run() {
14268                mHandler.removeCallbacks(this);
14269                final boolean succeded;
14270                synchronized (mInstallLock) {
14271                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14272                }
14273                clearExternalStorageDataSync(packageName, userId, false);
14274                if (observer != null) {
14275                    try {
14276                        observer.onRemoveCompleted(packageName, succeded);
14277                    } catch (RemoteException e) {
14278                        Log.i(TAG, "Observer no longer exists.");
14279                    }
14280                } //end if observer
14281            } //end run
14282        });
14283    }
14284
14285    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14286        if (packageName == null) {
14287            Slog.w(TAG, "Attempt to delete null packageName.");
14288            return false;
14289        }
14290        PackageParser.Package p;
14291        synchronized (mPackages) {
14292            p = mPackages.get(packageName);
14293        }
14294        if (p == null) {
14295            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14296            return false;
14297        }
14298        final ApplicationInfo applicationInfo = p.applicationInfo;
14299        if (applicationInfo == null) {
14300            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14301            return false;
14302        }
14303        // TODO: triage flags as part of 26466827
14304        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14305        try {
14306            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14307                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14308        } catch (InstallerException e) {
14309            Slog.w(TAG, "Couldn't remove cache files for package "
14310                    + packageName + " u" + userId, e);
14311            return false;
14312        }
14313        return true;
14314    }
14315
14316    @Override
14317    public void getPackageSizeInfo(final String packageName, int userHandle,
14318            final IPackageStatsObserver observer) {
14319        mContext.enforceCallingOrSelfPermission(
14320                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14321        if (packageName == null) {
14322            throw new IllegalArgumentException("Attempt to get size of null packageName");
14323        }
14324
14325        PackageStats stats = new PackageStats(packageName, userHandle);
14326
14327        /*
14328         * Queue up an async operation since the package measurement may take a
14329         * little while.
14330         */
14331        Message msg = mHandler.obtainMessage(INIT_COPY);
14332        msg.obj = new MeasureParams(stats, observer);
14333        mHandler.sendMessage(msg);
14334    }
14335
14336    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14337            PackageStats pStats) {
14338        if (packageName == null) {
14339            Slog.w(TAG, "Attempt to get size of null packageName.");
14340            return false;
14341        }
14342        PackageParser.Package p;
14343        boolean dataOnly = false;
14344        String libDirRoot = null;
14345        String asecPath = null;
14346        PackageSetting ps = null;
14347        synchronized (mPackages) {
14348            p = mPackages.get(packageName);
14349            ps = mSettings.mPackages.get(packageName);
14350            if(p == null) {
14351                dataOnly = true;
14352                if((ps == null) || (ps.pkg == null)) {
14353                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14354                    return false;
14355                }
14356                p = ps.pkg;
14357            }
14358            if (ps != null) {
14359                libDirRoot = ps.legacyNativeLibraryPathString;
14360            }
14361            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14362                final long token = Binder.clearCallingIdentity();
14363                try {
14364                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14365                    if (secureContainerId != null) {
14366                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14367                    }
14368                } finally {
14369                    Binder.restoreCallingIdentity(token);
14370                }
14371            }
14372        }
14373        String publicSrcDir = null;
14374        if(!dataOnly) {
14375            final ApplicationInfo applicationInfo = p.applicationInfo;
14376            if (applicationInfo == null) {
14377                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14378                return false;
14379            }
14380            if (p.isForwardLocked()) {
14381                publicSrcDir = applicationInfo.getBaseResourcePath();
14382            }
14383        }
14384        // TODO: extend to measure size of split APKs
14385        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14386        // not just the first level.
14387        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14388        // just the primary.
14389        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14390
14391        String apkPath;
14392        File packageDir = new File(p.codePath);
14393
14394        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14395            apkPath = packageDir.getAbsolutePath();
14396            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14397            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14398                libDirRoot = null;
14399            }
14400        } else {
14401            apkPath = p.baseCodePath;
14402        }
14403
14404        // TODO: triage flags as part of 26466827
14405        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14406        try {
14407            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
14408                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14409        } catch (InstallerException e) {
14410            return false;
14411        }
14412
14413        // Fix-up for forward-locked applications in ASEC containers.
14414        if (!isExternal(p)) {
14415            pStats.codeSize += pStats.externalCodeSize;
14416            pStats.externalCodeSize = 0L;
14417        }
14418
14419        return true;
14420    }
14421
14422
14423    @Override
14424    public void addPackageToPreferred(String packageName) {
14425        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14426    }
14427
14428    @Override
14429    public void removePackageFromPreferred(String packageName) {
14430        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14431    }
14432
14433    @Override
14434    public List<PackageInfo> getPreferredPackages(int flags) {
14435        return new ArrayList<PackageInfo>();
14436    }
14437
14438    private int getUidTargetSdkVersionLockedLPr(int uid) {
14439        Object obj = mSettings.getUserIdLPr(uid);
14440        if (obj instanceof SharedUserSetting) {
14441            final SharedUserSetting sus = (SharedUserSetting) obj;
14442            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14443            final Iterator<PackageSetting> it = sus.packages.iterator();
14444            while (it.hasNext()) {
14445                final PackageSetting ps = it.next();
14446                if (ps.pkg != null) {
14447                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14448                    if (v < vers) vers = v;
14449                }
14450            }
14451            return vers;
14452        } else if (obj instanceof PackageSetting) {
14453            final PackageSetting ps = (PackageSetting) obj;
14454            if (ps.pkg != null) {
14455                return ps.pkg.applicationInfo.targetSdkVersion;
14456            }
14457        }
14458        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14459    }
14460
14461    @Override
14462    public void addPreferredActivity(IntentFilter filter, int match,
14463            ComponentName[] set, ComponentName activity, int userId) {
14464        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14465                "Adding preferred");
14466    }
14467
14468    private void addPreferredActivityInternal(IntentFilter filter, int match,
14469            ComponentName[] set, ComponentName activity, boolean always, int userId,
14470            String opname) {
14471        // writer
14472        int callingUid = Binder.getCallingUid();
14473        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14474        if (filter.countActions() == 0) {
14475            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14476            return;
14477        }
14478        synchronized (mPackages) {
14479            if (mContext.checkCallingOrSelfPermission(
14480                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14481                    != PackageManager.PERMISSION_GRANTED) {
14482                if (getUidTargetSdkVersionLockedLPr(callingUid)
14483                        < Build.VERSION_CODES.FROYO) {
14484                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14485                            + callingUid);
14486                    return;
14487                }
14488                mContext.enforceCallingOrSelfPermission(
14489                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14490            }
14491
14492            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14493            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14494                    + userId + ":");
14495            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14496            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14497            scheduleWritePackageRestrictionsLocked(userId);
14498        }
14499    }
14500
14501    @Override
14502    public void replacePreferredActivity(IntentFilter filter, int match,
14503            ComponentName[] set, ComponentName activity, int userId) {
14504        if (filter.countActions() != 1) {
14505            throw new IllegalArgumentException(
14506                    "replacePreferredActivity expects filter to have only 1 action.");
14507        }
14508        if (filter.countDataAuthorities() != 0
14509                || filter.countDataPaths() != 0
14510                || filter.countDataSchemes() > 1
14511                || filter.countDataTypes() != 0) {
14512            throw new IllegalArgumentException(
14513                    "replacePreferredActivity expects filter to have no data authorities, " +
14514                    "paths, or types; and at most one scheme.");
14515        }
14516
14517        final int callingUid = Binder.getCallingUid();
14518        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14519        synchronized (mPackages) {
14520            if (mContext.checkCallingOrSelfPermission(
14521                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14522                    != PackageManager.PERMISSION_GRANTED) {
14523                if (getUidTargetSdkVersionLockedLPr(callingUid)
14524                        < Build.VERSION_CODES.FROYO) {
14525                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14526                            + Binder.getCallingUid());
14527                    return;
14528                }
14529                mContext.enforceCallingOrSelfPermission(
14530                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14531            }
14532
14533            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14534            if (pir != null) {
14535                // Get all of the existing entries that exactly match this filter.
14536                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14537                if (existing != null && existing.size() == 1) {
14538                    PreferredActivity cur = existing.get(0);
14539                    if (DEBUG_PREFERRED) {
14540                        Slog.i(TAG, "Checking replace of preferred:");
14541                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14542                        if (!cur.mPref.mAlways) {
14543                            Slog.i(TAG, "  -- CUR; not mAlways!");
14544                        } else {
14545                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14546                            Slog.i(TAG, "  -- CUR: mSet="
14547                                    + Arrays.toString(cur.mPref.mSetComponents));
14548                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14549                            Slog.i(TAG, "  -- NEW: mMatch="
14550                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14551                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14552                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14553                        }
14554                    }
14555                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14556                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14557                            && cur.mPref.sameSet(set)) {
14558                        // Setting the preferred activity to what it happens to be already
14559                        if (DEBUG_PREFERRED) {
14560                            Slog.i(TAG, "Replacing with same preferred activity "
14561                                    + cur.mPref.mShortComponent + " for user "
14562                                    + userId + ":");
14563                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14564                        }
14565                        return;
14566                    }
14567                }
14568
14569                if (existing != null) {
14570                    if (DEBUG_PREFERRED) {
14571                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14572                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14573                    }
14574                    for (int i = 0; i < existing.size(); i++) {
14575                        PreferredActivity pa = existing.get(i);
14576                        if (DEBUG_PREFERRED) {
14577                            Slog.i(TAG, "Removing existing preferred activity "
14578                                    + pa.mPref.mComponent + ":");
14579                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14580                        }
14581                        pir.removeFilter(pa);
14582                    }
14583                }
14584            }
14585            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14586                    "Replacing preferred");
14587        }
14588    }
14589
14590    @Override
14591    public void clearPackagePreferredActivities(String packageName) {
14592        final int uid = Binder.getCallingUid();
14593        // writer
14594        synchronized (mPackages) {
14595            PackageParser.Package pkg = mPackages.get(packageName);
14596            if (pkg == null || pkg.applicationInfo.uid != uid) {
14597                if (mContext.checkCallingOrSelfPermission(
14598                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14599                        != PackageManager.PERMISSION_GRANTED) {
14600                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14601                            < Build.VERSION_CODES.FROYO) {
14602                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14603                                + Binder.getCallingUid());
14604                        return;
14605                    }
14606                    mContext.enforceCallingOrSelfPermission(
14607                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14608                }
14609            }
14610
14611            int user = UserHandle.getCallingUserId();
14612            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14613                scheduleWritePackageRestrictionsLocked(user);
14614            }
14615        }
14616    }
14617
14618    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14619    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14620        ArrayList<PreferredActivity> removed = null;
14621        boolean changed = false;
14622        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14623            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14624            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14625            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14626                continue;
14627            }
14628            Iterator<PreferredActivity> it = pir.filterIterator();
14629            while (it.hasNext()) {
14630                PreferredActivity pa = it.next();
14631                // Mark entry for removal only if it matches the package name
14632                // and the entry is of type "always".
14633                if (packageName == null ||
14634                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14635                                && pa.mPref.mAlways)) {
14636                    if (removed == null) {
14637                        removed = new ArrayList<PreferredActivity>();
14638                    }
14639                    removed.add(pa);
14640                }
14641            }
14642            if (removed != null) {
14643                for (int j=0; j<removed.size(); j++) {
14644                    PreferredActivity pa = removed.get(j);
14645                    pir.removeFilter(pa);
14646                }
14647                changed = true;
14648            }
14649        }
14650        return changed;
14651    }
14652
14653    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14654    private void clearIntentFilterVerificationsLPw(int userId) {
14655        final int packageCount = mPackages.size();
14656        for (int i = 0; i < packageCount; i++) {
14657            PackageParser.Package pkg = mPackages.valueAt(i);
14658            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14659        }
14660    }
14661
14662    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14663    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14664        if (userId == UserHandle.USER_ALL) {
14665            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14666                    sUserManager.getUserIds())) {
14667                for (int oneUserId : sUserManager.getUserIds()) {
14668                    scheduleWritePackageRestrictionsLocked(oneUserId);
14669                }
14670            }
14671        } else {
14672            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14673                scheduleWritePackageRestrictionsLocked(userId);
14674            }
14675        }
14676    }
14677
14678    void clearDefaultBrowserIfNeeded(String packageName) {
14679        for (int oneUserId : sUserManager.getUserIds()) {
14680            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14681            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14682            if (packageName.equals(defaultBrowserPackageName)) {
14683                setDefaultBrowserPackageName(null, oneUserId);
14684            }
14685        }
14686    }
14687
14688    @Override
14689    public void resetApplicationPreferences(int userId) {
14690        mContext.enforceCallingOrSelfPermission(
14691                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14692        // writer
14693        synchronized (mPackages) {
14694            final long identity = Binder.clearCallingIdentity();
14695            try {
14696                clearPackagePreferredActivitiesLPw(null, userId);
14697                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14698                // TODO: We have to reset the default SMS and Phone. This requires
14699                // significant refactoring to keep all default apps in the package
14700                // manager (cleaner but more work) or have the services provide
14701                // callbacks to the package manager to request a default app reset.
14702                applyFactoryDefaultBrowserLPw(userId);
14703                clearIntentFilterVerificationsLPw(userId);
14704                primeDomainVerificationsLPw(userId);
14705                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14706                scheduleWritePackageRestrictionsLocked(userId);
14707            } finally {
14708                Binder.restoreCallingIdentity(identity);
14709            }
14710        }
14711    }
14712
14713    @Override
14714    public int getPreferredActivities(List<IntentFilter> outFilters,
14715            List<ComponentName> outActivities, String packageName) {
14716
14717        int num = 0;
14718        final int userId = UserHandle.getCallingUserId();
14719        // reader
14720        synchronized (mPackages) {
14721            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14722            if (pir != null) {
14723                final Iterator<PreferredActivity> it = pir.filterIterator();
14724                while (it.hasNext()) {
14725                    final PreferredActivity pa = it.next();
14726                    if (packageName == null
14727                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14728                                    && pa.mPref.mAlways)) {
14729                        if (outFilters != null) {
14730                            outFilters.add(new IntentFilter(pa));
14731                        }
14732                        if (outActivities != null) {
14733                            outActivities.add(pa.mPref.mComponent);
14734                        }
14735                    }
14736                }
14737            }
14738        }
14739
14740        return num;
14741    }
14742
14743    @Override
14744    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14745            int userId) {
14746        int callingUid = Binder.getCallingUid();
14747        if (callingUid != Process.SYSTEM_UID) {
14748            throw new SecurityException(
14749                    "addPersistentPreferredActivity can only be run by the system");
14750        }
14751        if (filter.countActions() == 0) {
14752            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14753            return;
14754        }
14755        synchronized (mPackages) {
14756            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14757                    ":");
14758            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14759            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14760                    new PersistentPreferredActivity(filter, activity));
14761            scheduleWritePackageRestrictionsLocked(userId);
14762        }
14763    }
14764
14765    @Override
14766    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14767        int callingUid = Binder.getCallingUid();
14768        if (callingUid != Process.SYSTEM_UID) {
14769            throw new SecurityException(
14770                    "clearPackagePersistentPreferredActivities can only be run by the system");
14771        }
14772        ArrayList<PersistentPreferredActivity> removed = null;
14773        boolean changed = false;
14774        synchronized (mPackages) {
14775            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14776                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14777                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14778                        .valueAt(i);
14779                if (userId != thisUserId) {
14780                    continue;
14781                }
14782                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14783                while (it.hasNext()) {
14784                    PersistentPreferredActivity ppa = it.next();
14785                    // Mark entry for removal only if it matches the package name.
14786                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14787                        if (removed == null) {
14788                            removed = new ArrayList<PersistentPreferredActivity>();
14789                        }
14790                        removed.add(ppa);
14791                    }
14792                }
14793                if (removed != null) {
14794                    for (int j=0; j<removed.size(); j++) {
14795                        PersistentPreferredActivity ppa = removed.get(j);
14796                        ppir.removeFilter(ppa);
14797                    }
14798                    changed = true;
14799                }
14800            }
14801
14802            if (changed) {
14803                scheduleWritePackageRestrictionsLocked(userId);
14804            }
14805        }
14806    }
14807
14808    /**
14809     * Common machinery for picking apart a restored XML blob and passing
14810     * it to a caller-supplied functor to be applied to the running system.
14811     */
14812    private void restoreFromXml(XmlPullParser parser, int userId,
14813            String expectedStartTag, BlobXmlRestorer functor)
14814            throws IOException, XmlPullParserException {
14815        int type;
14816        while ((type = parser.next()) != XmlPullParser.START_TAG
14817                && type != XmlPullParser.END_DOCUMENT) {
14818        }
14819        if (type != XmlPullParser.START_TAG) {
14820            // oops didn't find a start tag?!
14821            if (DEBUG_BACKUP) {
14822                Slog.e(TAG, "Didn't find start tag during restore");
14823            }
14824            return;
14825        }
14826
14827        // this is supposed to be TAG_PREFERRED_BACKUP
14828        if (!expectedStartTag.equals(parser.getName())) {
14829            if (DEBUG_BACKUP) {
14830                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14831            }
14832            return;
14833        }
14834
14835        // skip interfering stuff, then we're aligned with the backing implementation
14836        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14837        functor.apply(parser, userId);
14838    }
14839
14840    private interface BlobXmlRestorer {
14841        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14842    }
14843
14844    /**
14845     * Non-Binder method, support for the backup/restore mechanism: write the
14846     * full set of preferred activities in its canonical XML format.  Returns the
14847     * XML output as a byte array, or null if there is none.
14848     */
14849    @Override
14850    public byte[] getPreferredActivityBackup(int userId) {
14851        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14852            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14853        }
14854
14855        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14856        try {
14857            final XmlSerializer serializer = new FastXmlSerializer();
14858            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14859            serializer.startDocument(null, true);
14860            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14861
14862            synchronized (mPackages) {
14863                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14864            }
14865
14866            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14867            serializer.endDocument();
14868            serializer.flush();
14869        } catch (Exception e) {
14870            if (DEBUG_BACKUP) {
14871                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14872            }
14873            return null;
14874        }
14875
14876        return dataStream.toByteArray();
14877    }
14878
14879    @Override
14880    public void restorePreferredActivities(byte[] backup, int userId) {
14881        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14882            throw new SecurityException("Only the system may call restorePreferredActivities()");
14883        }
14884
14885        try {
14886            final XmlPullParser parser = Xml.newPullParser();
14887            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14888            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14889                    new BlobXmlRestorer() {
14890                        @Override
14891                        public void apply(XmlPullParser parser, int userId)
14892                                throws XmlPullParserException, IOException {
14893                            synchronized (mPackages) {
14894                                mSettings.readPreferredActivitiesLPw(parser, userId);
14895                            }
14896                        }
14897                    } );
14898        } catch (Exception e) {
14899            if (DEBUG_BACKUP) {
14900                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14901            }
14902        }
14903    }
14904
14905    /**
14906     * Non-Binder method, support for the backup/restore mechanism: write the
14907     * default browser (etc) settings in its canonical XML format.  Returns the default
14908     * browser XML representation as a byte array, or null if there is none.
14909     */
14910    @Override
14911    public byte[] getDefaultAppsBackup(int userId) {
14912        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14913            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14914        }
14915
14916        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14917        try {
14918            final XmlSerializer serializer = new FastXmlSerializer();
14919            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14920            serializer.startDocument(null, true);
14921            serializer.startTag(null, TAG_DEFAULT_APPS);
14922
14923            synchronized (mPackages) {
14924                mSettings.writeDefaultAppsLPr(serializer, userId);
14925            }
14926
14927            serializer.endTag(null, TAG_DEFAULT_APPS);
14928            serializer.endDocument();
14929            serializer.flush();
14930        } catch (Exception e) {
14931            if (DEBUG_BACKUP) {
14932                Slog.e(TAG, "Unable to write default apps for backup", e);
14933            }
14934            return null;
14935        }
14936
14937        return dataStream.toByteArray();
14938    }
14939
14940    @Override
14941    public void restoreDefaultApps(byte[] backup, int userId) {
14942        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14943            throw new SecurityException("Only the system may call restoreDefaultApps()");
14944        }
14945
14946        try {
14947            final XmlPullParser parser = Xml.newPullParser();
14948            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14949            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14950                    new BlobXmlRestorer() {
14951                        @Override
14952                        public void apply(XmlPullParser parser, int userId)
14953                                throws XmlPullParserException, IOException {
14954                            synchronized (mPackages) {
14955                                mSettings.readDefaultAppsLPw(parser, userId);
14956                            }
14957                        }
14958                    } );
14959        } catch (Exception e) {
14960            if (DEBUG_BACKUP) {
14961                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14962            }
14963        }
14964    }
14965
14966    @Override
14967    public byte[] getIntentFilterVerificationBackup(int userId) {
14968        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14969            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14970        }
14971
14972        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14973        try {
14974            final XmlSerializer serializer = new FastXmlSerializer();
14975            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14976            serializer.startDocument(null, true);
14977            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14978
14979            synchronized (mPackages) {
14980                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14981            }
14982
14983            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14984            serializer.endDocument();
14985            serializer.flush();
14986        } catch (Exception e) {
14987            if (DEBUG_BACKUP) {
14988                Slog.e(TAG, "Unable to write default apps for backup", e);
14989            }
14990            return null;
14991        }
14992
14993        return dataStream.toByteArray();
14994    }
14995
14996    @Override
14997    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14998        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14999            throw new SecurityException("Only the system may call restorePreferredActivities()");
15000        }
15001
15002        try {
15003            final XmlPullParser parser = Xml.newPullParser();
15004            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
15005            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
15006                    new BlobXmlRestorer() {
15007                        @Override
15008                        public void apply(XmlPullParser parser, int userId)
15009                                throws XmlPullParserException, IOException {
15010                            synchronized (mPackages) {
15011                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15012                                mSettings.writeLPr();
15013                            }
15014                        }
15015                    } );
15016        } catch (Exception e) {
15017            if (DEBUG_BACKUP) {
15018                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15019            }
15020        }
15021    }
15022
15023    @Override
15024    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15025            int sourceUserId, int targetUserId, int flags) {
15026        mContext.enforceCallingOrSelfPermission(
15027                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15028        int callingUid = Binder.getCallingUid();
15029        enforceOwnerRights(ownerPackage, callingUid);
15030        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15031        if (intentFilter.countActions() == 0) {
15032            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15033            return;
15034        }
15035        synchronized (mPackages) {
15036            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15037                    ownerPackage, targetUserId, flags);
15038            CrossProfileIntentResolver resolver =
15039                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15040            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15041            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15042            if (existing != null) {
15043                int size = existing.size();
15044                for (int i = 0; i < size; i++) {
15045                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15046                        return;
15047                    }
15048                }
15049            }
15050            resolver.addFilter(newFilter);
15051            scheduleWritePackageRestrictionsLocked(sourceUserId);
15052        }
15053    }
15054
15055    @Override
15056    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15057        mContext.enforceCallingOrSelfPermission(
15058                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15059        int callingUid = Binder.getCallingUid();
15060        enforceOwnerRights(ownerPackage, callingUid);
15061        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15062        synchronized (mPackages) {
15063            CrossProfileIntentResolver resolver =
15064                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15065            ArraySet<CrossProfileIntentFilter> set =
15066                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15067            for (CrossProfileIntentFilter filter : set) {
15068                if (filter.getOwnerPackage().equals(ownerPackage)) {
15069                    resolver.removeFilter(filter);
15070                }
15071            }
15072            scheduleWritePackageRestrictionsLocked(sourceUserId);
15073        }
15074    }
15075
15076    // Enforcing that callingUid is owning pkg on userId
15077    private void enforceOwnerRights(String pkg, int callingUid) {
15078        // The system owns everything.
15079        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15080            return;
15081        }
15082        int callingUserId = UserHandle.getUserId(callingUid);
15083        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15084        if (pi == null) {
15085            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15086                    + callingUserId);
15087        }
15088        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15089            throw new SecurityException("Calling uid " + callingUid
15090                    + " does not own package " + pkg);
15091        }
15092    }
15093
15094    @Override
15095    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15096        Intent intent = new Intent(Intent.ACTION_MAIN);
15097        intent.addCategory(Intent.CATEGORY_HOME);
15098
15099        final int callingUserId = UserHandle.getCallingUserId();
15100        List<ResolveInfo> list = queryIntentActivities(intent, null,
15101                PackageManager.GET_META_DATA, callingUserId);
15102        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15103                true, false, false, callingUserId);
15104
15105        allHomeCandidates.clear();
15106        if (list != null) {
15107            for (ResolveInfo ri : list) {
15108                allHomeCandidates.add(ri);
15109            }
15110        }
15111        return (preferred == null || preferred.activityInfo == null)
15112                ? null
15113                : new ComponentName(preferred.activityInfo.packageName,
15114                        preferred.activityInfo.name);
15115    }
15116
15117    @Override
15118    public void setApplicationEnabledSetting(String appPackageName,
15119            int newState, int flags, int userId, String callingPackage) {
15120        if (!sUserManager.exists(userId)) return;
15121        if (callingPackage == null) {
15122            callingPackage = Integer.toString(Binder.getCallingUid());
15123        }
15124        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15125    }
15126
15127    @Override
15128    public void setComponentEnabledSetting(ComponentName componentName,
15129            int newState, int flags, int userId) {
15130        if (!sUserManager.exists(userId)) return;
15131        setEnabledSetting(componentName.getPackageName(),
15132                componentName.getClassName(), newState, flags, userId, null);
15133    }
15134
15135    private void setEnabledSetting(final String packageName, String className, int newState,
15136            final int flags, int userId, String callingPackage) {
15137        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15138              || newState == COMPONENT_ENABLED_STATE_ENABLED
15139              || newState == COMPONENT_ENABLED_STATE_DISABLED
15140              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15141              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15142            throw new IllegalArgumentException("Invalid new component state: "
15143                    + newState);
15144        }
15145        PackageSetting pkgSetting;
15146        final int uid = Binder.getCallingUid();
15147        final int permission = mContext.checkCallingOrSelfPermission(
15148                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15149        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15150        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15151        boolean sendNow = false;
15152        boolean isApp = (className == null);
15153        String componentName = isApp ? packageName : className;
15154        int packageUid = -1;
15155        ArrayList<String> components;
15156
15157        // writer
15158        synchronized (mPackages) {
15159            pkgSetting = mSettings.mPackages.get(packageName);
15160            if (pkgSetting == null) {
15161                if (className == null) {
15162                    throw new IllegalArgumentException("Unknown package: " + packageName);
15163                }
15164                throw new IllegalArgumentException(
15165                        "Unknown component: " + packageName + "/" + className);
15166            }
15167            // Allow root and verify that userId is not being specified by a different user
15168            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15169                throw new SecurityException(
15170                        "Permission Denial: attempt to change component state from pid="
15171                        + Binder.getCallingPid()
15172                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15173            }
15174            if (className == null) {
15175                // We're dealing with an application/package level state change
15176                if (pkgSetting.getEnabled(userId) == newState) {
15177                    // Nothing to do
15178                    return;
15179                }
15180                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15181                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15182                    // Don't care about who enables an app.
15183                    callingPackage = null;
15184                }
15185                pkgSetting.setEnabled(newState, userId, callingPackage);
15186                // pkgSetting.pkg.mSetEnabled = newState;
15187            } else {
15188                // We're dealing with a component level state change
15189                // First, verify that this is a valid class name.
15190                PackageParser.Package pkg = pkgSetting.pkg;
15191                if (pkg == null || !pkg.hasComponentClassName(className)) {
15192                    if (pkg != null &&
15193                            pkg.applicationInfo.targetSdkVersion >=
15194                                    Build.VERSION_CODES.JELLY_BEAN) {
15195                        throw new IllegalArgumentException("Component class " + className
15196                                + " does not exist in " + packageName);
15197                    } else {
15198                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15199                                + className + " does not exist in " + packageName);
15200                    }
15201                }
15202                switch (newState) {
15203                case COMPONENT_ENABLED_STATE_ENABLED:
15204                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15205                        return;
15206                    }
15207                    break;
15208                case COMPONENT_ENABLED_STATE_DISABLED:
15209                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15210                        return;
15211                    }
15212                    break;
15213                case COMPONENT_ENABLED_STATE_DEFAULT:
15214                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15215                        return;
15216                    }
15217                    break;
15218                default:
15219                    Slog.e(TAG, "Invalid new component state: " + newState);
15220                    return;
15221                }
15222            }
15223            scheduleWritePackageRestrictionsLocked(userId);
15224            components = mPendingBroadcasts.get(userId, packageName);
15225            final boolean newPackage = components == null;
15226            if (newPackage) {
15227                components = new ArrayList<String>();
15228            }
15229            if (!components.contains(componentName)) {
15230                components.add(componentName);
15231            }
15232            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15233                sendNow = true;
15234                // Purge entry from pending broadcast list if another one exists already
15235                // since we are sending one right away.
15236                mPendingBroadcasts.remove(userId, packageName);
15237            } else {
15238                if (newPackage) {
15239                    mPendingBroadcasts.put(userId, packageName, components);
15240                }
15241                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15242                    // Schedule a message
15243                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15244                }
15245            }
15246        }
15247
15248        long callingId = Binder.clearCallingIdentity();
15249        try {
15250            if (sendNow) {
15251                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15252                sendPackageChangedBroadcast(packageName,
15253                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15254            }
15255        } finally {
15256            Binder.restoreCallingIdentity(callingId);
15257        }
15258    }
15259
15260    private void sendPackageChangedBroadcast(String packageName,
15261            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15262        if (DEBUG_INSTALL)
15263            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15264                    + componentNames);
15265        Bundle extras = new Bundle(4);
15266        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15267        String nameList[] = new String[componentNames.size()];
15268        componentNames.toArray(nameList);
15269        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15270        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15271        extras.putInt(Intent.EXTRA_UID, packageUid);
15272        // If this is not reporting a change of the overall package, then only send it
15273        // to registered receivers.  We don't want to launch a swath of apps for every
15274        // little component state change.
15275        final int flags = !componentNames.contains(packageName)
15276                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15277        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15278                new int[] {UserHandle.getUserId(packageUid)});
15279    }
15280
15281    @Override
15282    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15283        if (!sUserManager.exists(userId)) return;
15284        final int uid = Binder.getCallingUid();
15285        final int permission = mContext.checkCallingOrSelfPermission(
15286                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15287        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15288        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15289        // writer
15290        synchronized (mPackages) {
15291            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15292                    allowedByPermission, uid, userId)) {
15293                scheduleWritePackageRestrictionsLocked(userId);
15294            }
15295        }
15296    }
15297
15298    @Override
15299    public String getInstallerPackageName(String packageName) {
15300        // reader
15301        synchronized (mPackages) {
15302            return mSettings.getInstallerPackageNameLPr(packageName);
15303        }
15304    }
15305
15306    @Override
15307    public int getApplicationEnabledSetting(String packageName, int userId) {
15308        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15309        int uid = Binder.getCallingUid();
15310        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15311        // reader
15312        synchronized (mPackages) {
15313            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15314        }
15315    }
15316
15317    @Override
15318    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15319        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15320        int uid = Binder.getCallingUid();
15321        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15322        // reader
15323        synchronized (mPackages) {
15324            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15325        }
15326    }
15327
15328    @Override
15329    public void enterSafeMode() {
15330        enforceSystemOrRoot("Only the system can request entering safe mode");
15331
15332        if (!mSystemReady) {
15333            mSafeMode = true;
15334        }
15335    }
15336
15337    @Override
15338    public void systemReady() {
15339        mSystemReady = true;
15340
15341        // Read the compatibilty setting when the system is ready.
15342        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15343                mContext.getContentResolver(),
15344                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15345        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15346        if (DEBUG_SETTINGS) {
15347            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15348        }
15349
15350        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15351
15352        synchronized (mPackages) {
15353            // Verify that all of the preferred activity components actually
15354            // exist.  It is possible for applications to be updated and at
15355            // that point remove a previously declared activity component that
15356            // had been set as a preferred activity.  We try to clean this up
15357            // the next time we encounter that preferred activity, but it is
15358            // possible for the user flow to never be able to return to that
15359            // situation so here we do a sanity check to make sure we haven't
15360            // left any junk around.
15361            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15362            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15363                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15364                removed.clear();
15365                for (PreferredActivity pa : pir.filterSet()) {
15366                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15367                        removed.add(pa);
15368                    }
15369                }
15370                if (removed.size() > 0) {
15371                    for (int r=0; r<removed.size(); r++) {
15372                        PreferredActivity pa = removed.get(r);
15373                        Slog.w(TAG, "Removing dangling preferred activity: "
15374                                + pa.mPref.mComponent);
15375                        pir.removeFilter(pa);
15376                    }
15377                    mSettings.writePackageRestrictionsLPr(
15378                            mSettings.mPreferredActivities.keyAt(i));
15379                }
15380            }
15381
15382            for (int userId : UserManagerService.getInstance().getUserIds()) {
15383                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15384                    grantPermissionsUserIds = ArrayUtils.appendInt(
15385                            grantPermissionsUserIds, userId);
15386                }
15387            }
15388        }
15389        sUserManager.systemReady();
15390
15391        // If we upgraded grant all default permissions before kicking off.
15392        for (int userId : grantPermissionsUserIds) {
15393            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15394        }
15395
15396        // Kick off any messages waiting for system ready
15397        if (mPostSystemReadyMessages != null) {
15398            for (Message msg : mPostSystemReadyMessages) {
15399                msg.sendToTarget();
15400            }
15401            mPostSystemReadyMessages = null;
15402        }
15403
15404        // Watch for external volumes that come and go over time
15405        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15406        storage.registerListener(mStorageListener);
15407
15408        mInstallerService.systemReady();
15409        mPackageDexOptimizer.systemReady();
15410
15411        MountServiceInternal mountServiceInternal = LocalServices.getService(
15412                MountServiceInternal.class);
15413        mountServiceInternal.addExternalStoragePolicy(
15414                new MountServiceInternal.ExternalStorageMountPolicy() {
15415            @Override
15416            public int getMountMode(int uid, String packageName) {
15417                if (Process.isIsolated(uid)) {
15418                    return Zygote.MOUNT_EXTERNAL_NONE;
15419                }
15420                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15421                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15422                }
15423                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15424                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15425                }
15426                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15427                    return Zygote.MOUNT_EXTERNAL_READ;
15428                }
15429                return Zygote.MOUNT_EXTERNAL_WRITE;
15430            }
15431
15432            @Override
15433            public boolean hasExternalStorage(int uid, String packageName) {
15434                return true;
15435            }
15436        });
15437    }
15438
15439    @Override
15440    public boolean isSafeMode() {
15441        return mSafeMode;
15442    }
15443
15444    @Override
15445    public boolean hasSystemUidErrors() {
15446        return mHasSystemUidErrors;
15447    }
15448
15449    static String arrayToString(int[] array) {
15450        StringBuffer buf = new StringBuffer(128);
15451        buf.append('[');
15452        if (array != null) {
15453            for (int i=0; i<array.length; i++) {
15454                if (i > 0) buf.append(", ");
15455                buf.append(array[i]);
15456            }
15457        }
15458        buf.append(']');
15459        return buf.toString();
15460    }
15461
15462    static class DumpState {
15463        public static final int DUMP_LIBS = 1 << 0;
15464        public static final int DUMP_FEATURES = 1 << 1;
15465        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15466        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15467        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15468        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15469        public static final int DUMP_PERMISSIONS = 1 << 6;
15470        public static final int DUMP_PACKAGES = 1 << 7;
15471        public static final int DUMP_SHARED_USERS = 1 << 8;
15472        public static final int DUMP_MESSAGES = 1 << 9;
15473        public static final int DUMP_PROVIDERS = 1 << 10;
15474        public static final int DUMP_VERIFIERS = 1 << 11;
15475        public static final int DUMP_PREFERRED = 1 << 12;
15476        public static final int DUMP_PREFERRED_XML = 1 << 13;
15477        public static final int DUMP_KEYSETS = 1 << 14;
15478        public static final int DUMP_VERSION = 1 << 15;
15479        public static final int DUMP_INSTALLS = 1 << 16;
15480        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15481        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15482
15483        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15484
15485        private int mTypes;
15486
15487        private int mOptions;
15488
15489        private boolean mTitlePrinted;
15490
15491        private SharedUserSetting mSharedUser;
15492
15493        public boolean isDumping(int type) {
15494            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15495                return true;
15496            }
15497
15498            return (mTypes & type) != 0;
15499        }
15500
15501        public void setDump(int type) {
15502            mTypes |= type;
15503        }
15504
15505        public boolean isOptionEnabled(int option) {
15506            return (mOptions & option) != 0;
15507        }
15508
15509        public void setOptionEnabled(int option) {
15510            mOptions |= option;
15511        }
15512
15513        public boolean onTitlePrinted() {
15514            final boolean printed = mTitlePrinted;
15515            mTitlePrinted = true;
15516            return printed;
15517        }
15518
15519        public boolean getTitlePrinted() {
15520            return mTitlePrinted;
15521        }
15522
15523        public void setTitlePrinted(boolean enabled) {
15524            mTitlePrinted = enabled;
15525        }
15526
15527        public SharedUserSetting getSharedUser() {
15528            return mSharedUser;
15529        }
15530
15531        public void setSharedUser(SharedUserSetting user) {
15532            mSharedUser = user;
15533        }
15534    }
15535
15536    @Override
15537    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15538            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15539        (new PackageManagerShellCommand(this)).exec(
15540                this, in, out, err, args, resultReceiver);
15541    }
15542
15543    @Override
15544    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15545        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15546                != PackageManager.PERMISSION_GRANTED) {
15547            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15548                    + Binder.getCallingPid()
15549                    + ", uid=" + Binder.getCallingUid()
15550                    + " without permission "
15551                    + android.Manifest.permission.DUMP);
15552            return;
15553        }
15554
15555        DumpState dumpState = new DumpState();
15556        boolean fullPreferred = false;
15557        boolean checkin = false;
15558
15559        String packageName = null;
15560        ArraySet<String> permissionNames = null;
15561
15562        int opti = 0;
15563        while (opti < args.length) {
15564            String opt = args[opti];
15565            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15566                break;
15567            }
15568            opti++;
15569
15570            if ("-a".equals(opt)) {
15571                // Right now we only know how to print all.
15572            } else if ("-h".equals(opt)) {
15573                pw.println("Package manager dump options:");
15574                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15575                pw.println("    --checkin: dump for a checkin");
15576                pw.println("    -f: print details of intent filters");
15577                pw.println("    -h: print this help");
15578                pw.println("  cmd may be one of:");
15579                pw.println("    l[ibraries]: list known shared libraries");
15580                pw.println("    f[eatures]: list device features");
15581                pw.println("    k[eysets]: print known keysets");
15582                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15583                pw.println("    perm[issions]: dump permissions");
15584                pw.println("    permission [name ...]: dump declaration and use of given permission");
15585                pw.println("    pref[erred]: print preferred package settings");
15586                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15587                pw.println("    prov[iders]: dump content providers");
15588                pw.println("    p[ackages]: dump installed packages");
15589                pw.println("    s[hared-users]: dump shared user IDs");
15590                pw.println("    m[essages]: print collected runtime messages");
15591                pw.println("    v[erifiers]: print package verifier info");
15592                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15593                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15594                pw.println("    version: print database version info");
15595                pw.println("    write: write current settings now");
15596                pw.println("    installs: details about install sessions");
15597                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15598                pw.println("    <package.name>: info about given package");
15599                return;
15600            } else if ("--checkin".equals(opt)) {
15601                checkin = true;
15602            } else if ("-f".equals(opt)) {
15603                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15604            } else {
15605                pw.println("Unknown argument: " + opt + "; use -h for help");
15606            }
15607        }
15608
15609        // Is the caller requesting to dump a particular piece of data?
15610        if (opti < args.length) {
15611            String cmd = args[opti];
15612            opti++;
15613            // Is this a package name?
15614            if ("android".equals(cmd) || cmd.contains(".")) {
15615                packageName = cmd;
15616                // When dumping a single package, we always dump all of its
15617                // filter information since the amount of data will be reasonable.
15618                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15619            } else if ("check-permission".equals(cmd)) {
15620                if (opti >= args.length) {
15621                    pw.println("Error: check-permission missing permission argument");
15622                    return;
15623                }
15624                String perm = args[opti];
15625                opti++;
15626                if (opti >= args.length) {
15627                    pw.println("Error: check-permission missing package argument");
15628                    return;
15629                }
15630                String pkg = args[opti];
15631                opti++;
15632                int user = UserHandle.getUserId(Binder.getCallingUid());
15633                if (opti < args.length) {
15634                    try {
15635                        user = Integer.parseInt(args[opti]);
15636                    } catch (NumberFormatException e) {
15637                        pw.println("Error: check-permission user argument is not a number: "
15638                                + args[opti]);
15639                        return;
15640                    }
15641                }
15642                pw.println(checkPermission(perm, pkg, user));
15643                return;
15644            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15645                dumpState.setDump(DumpState.DUMP_LIBS);
15646            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15647                dumpState.setDump(DumpState.DUMP_FEATURES);
15648            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15649                if (opti >= args.length) {
15650                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15651                            | DumpState.DUMP_SERVICE_RESOLVERS
15652                            | DumpState.DUMP_RECEIVER_RESOLVERS
15653                            | DumpState.DUMP_CONTENT_RESOLVERS);
15654                } else {
15655                    while (opti < args.length) {
15656                        String name = args[opti];
15657                        if ("a".equals(name) || "activity".equals(name)) {
15658                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15659                        } else if ("s".equals(name) || "service".equals(name)) {
15660                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15661                        } else if ("r".equals(name) || "receiver".equals(name)) {
15662                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15663                        } else if ("c".equals(name) || "content".equals(name)) {
15664                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15665                        } else {
15666                            pw.println("Error: unknown resolver table type: " + name);
15667                            return;
15668                        }
15669                        opti++;
15670                    }
15671                }
15672            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15673                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15674            } else if ("permission".equals(cmd)) {
15675                if (opti >= args.length) {
15676                    pw.println("Error: permission requires permission name");
15677                    return;
15678                }
15679                permissionNames = new ArraySet<>();
15680                while (opti < args.length) {
15681                    permissionNames.add(args[opti]);
15682                    opti++;
15683                }
15684                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15685                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15686            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15687                dumpState.setDump(DumpState.DUMP_PREFERRED);
15688            } else if ("preferred-xml".equals(cmd)) {
15689                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15690                if (opti < args.length && "--full".equals(args[opti])) {
15691                    fullPreferred = true;
15692                    opti++;
15693                }
15694            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15695                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15696            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15697                dumpState.setDump(DumpState.DUMP_PACKAGES);
15698            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15699                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15700            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15701                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15702            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15703                dumpState.setDump(DumpState.DUMP_MESSAGES);
15704            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15705                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15706            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15707                    || "intent-filter-verifiers".equals(cmd)) {
15708                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15709            } else if ("version".equals(cmd)) {
15710                dumpState.setDump(DumpState.DUMP_VERSION);
15711            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15712                dumpState.setDump(DumpState.DUMP_KEYSETS);
15713            } else if ("installs".equals(cmd)) {
15714                dumpState.setDump(DumpState.DUMP_INSTALLS);
15715            } else if ("write".equals(cmd)) {
15716                synchronized (mPackages) {
15717                    mSettings.writeLPr();
15718                    pw.println("Settings written.");
15719                    return;
15720                }
15721            }
15722        }
15723
15724        if (checkin) {
15725            pw.println("vers,1");
15726        }
15727
15728        // reader
15729        synchronized (mPackages) {
15730            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15731                if (!checkin) {
15732                    if (dumpState.onTitlePrinted())
15733                        pw.println();
15734                    pw.println("Database versions:");
15735                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15736                }
15737            }
15738
15739            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15740                if (!checkin) {
15741                    if (dumpState.onTitlePrinted())
15742                        pw.println();
15743                    pw.println("Verifiers:");
15744                    pw.print("  Required: ");
15745                    pw.print(mRequiredVerifierPackage);
15746                    pw.print(" (uid=");
15747                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15748                            UserHandle.USER_SYSTEM));
15749                    pw.println(")");
15750                } else if (mRequiredVerifierPackage != null) {
15751                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15752                    pw.print(",");
15753                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15754                            UserHandle.USER_SYSTEM));
15755                }
15756            }
15757
15758            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15759                    packageName == null) {
15760                if (mIntentFilterVerifierComponent != null) {
15761                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15762                    if (!checkin) {
15763                        if (dumpState.onTitlePrinted())
15764                            pw.println();
15765                        pw.println("Intent Filter Verifier:");
15766                        pw.print("  Using: ");
15767                        pw.print(verifierPackageName);
15768                        pw.print(" (uid=");
15769                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15770                                UserHandle.USER_SYSTEM));
15771                        pw.println(")");
15772                    } else if (verifierPackageName != null) {
15773                        pw.print("ifv,"); pw.print(verifierPackageName);
15774                        pw.print(",");
15775                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15776                                UserHandle.USER_SYSTEM));
15777                    }
15778                } else {
15779                    pw.println();
15780                    pw.println("No Intent Filter Verifier available!");
15781                }
15782            }
15783
15784            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15785                boolean printedHeader = false;
15786                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15787                while (it.hasNext()) {
15788                    String name = it.next();
15789                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15790                    if (!checkin) {
15791                        if (!printedHeader) {
15792                            if (dumpState.onTitlePrinted())
15793                                pw.println();
15794                            pw.println("Libraries:");
15795                            printedHeader = true;
15796                        }
15797                        pw.print("  ");
15798                    } else {
15799                        pw.print("lib,");
15800                    }
15801                    pw.print(name);
15802                    if (!checkin) {
15803                        pw.print(" -> ");
15804                    }
15805                    if (ent.path != null) {
15806                        if (!checkin) {
15807                            pw.print("(jar) ");
15808                            pw.print(ent.path);
15809                        } else {
15810                            pw.print(",jar,");
15811                            pw.print(ent.path);
15812                        }
15813                    } else {
15814                        if (!checkin) {
15815                            pw.print("(apk) ");
15816                            pw.print(ent.apk);
15817                        } else {
15818                            pw.print(",apk,");
15819                            pw.print(ent.apk);
15820                        }
15821                    }
15822                    pw.println();
15823                }
15824            }
15825
15826            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15827                if (dumpState.onTitlePrinted())
15828                    pw.println();
15829                if (!checkin) {
15830                    pw.println("Features:");
15831                }
15832                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15833                while (it.hasNext()) {
15834                    String name = it.next();
15835                    if (!checkin) {
15836                        pw.print("  ");
15837                    } else {
15838                        pw.print("feat,");
15839                    }
15840                    pw.println(name);
15841                }
15842            }
15843
15844            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15845                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15846                        : "Activity Resolver Table:", "  ", packageName,
15847                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15848                    dumpState.setTitlePrinted(true);
15849                }
15850            }
15851            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15852                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15853                        : "Receiver Resolver Table:", "  ", packageName,
15854                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15855                    dumpState.setTitlePrinted(true);
15856                }
15857            }
15858            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15859                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15860                        : "Service Resolver Table:", "  ", packageName,
15861                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15862                    dumpState.setTitlePrinted(true);
15863                }
15864            }
15865            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15866                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15867                        : "Provider Resolver Table:", "  ", packageName,
15868                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15869                    dumpState.setTitlePrinted(true);
15870                }
15871            }
15872
15873            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15874                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15875                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15876                    int user = mSettings.mPreferredActivities.keyAt(i);
15877                    if (pir.dump(pw,
15878                            dumpState.getTitlePrinted()
15879                                ? "\nPreferred Activities User " + user + ":"
15880                                : "Preferred Activities User " + user + ":", "  ",
15881                            packageName, true, false)) {
15882                        dumpState.setTitlePrinted(true);
15883                    }
15884                }
15885            }
15886
15887            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15888                pw.flush();
15889                FileOutputStream fout = new FileOutputStream(fd);
15890                BufferedOutputStream str = new BufferedOutputStream(fout);
15891                XmlSerializer serializer = new FastXmlSerializer();
15892                try {
15893                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15894                    serializer.startDocument(null, true);
15895                    serializer.setFeature(
15896                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15897                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15898                    serializer.endDocument();
15899                    serializer.flush();
15900                } catch (IllegalArgumentException e) {
15901                    pw.println("Failed writing: " + e);
15902                } catch (IllegalStateException e) {
15903                    pw.println("Failed writing: " + e);
15904                } catch (IOException e) {
15905                    pw.println("Failed writing: " + e);
15906                }
15907            }
15908
15909            if (!checkin
15910                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15911                    && packageName == null) {
15912                pw.println();
15913                int count = mSettings.mPackages.size();
15914                if (count == 0) {
15915                    pw.println("No applications!");
15916                    pw.println();
15917                } else {
15918                    final String prefix = "  ";
15919                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15920                    if (allPackageSettings.size() == 0) {
15921                        pw.println("No domain preferred apps!");
15922                        pw.println();
15923                    } else {
15924                        pw.println("App verification status:");
15925                        pw.println();
15926                        count = 0;
15927                        for (PackageSetting ps : allPackageSettings) {
15928                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15929                            if (ivi == null || ivi.getPackageName() == null) continue;
15930                            pw.println(prefix + "Package: " + ivi.getPackageName());
15931                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15932                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15933                            pw.println();
15934                            count++;
15935                        }
15936                        if (count == 0) {
15937                            pw.println(prefix + "No app verification established.");
15938                            pw.println();
15939                        }
15940                        for (int userId : sUserManager.getUserIds()) {
15941                            pw.println("App linkages for user " + userId + ":");
15942                            pw.println();
15943                            count = 0;
15944                            for (PackageSetting ps : allPackageSettings) {
15945                                final long status = ps.getDomainVerificationStatusForUser(userId);
15946                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15947                                    continue;
15948                                }
15949                                pw.println(prefix + "Package: " + ps.name);
15950                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15951                                String statusStr = IntentFilterVerificationInfo.
15952                                        getStatusStringFromValue(status);
15953                                pw.println(prefix + "Status:  " + statusStr);
15954                                pw.println();
15955                                count++;
15956                            }
15957                            if (count == 0) {
15958                                pw.println(prefix + "No configured app linkages.");
15959                                pw.println();
15960                            }
15961                        }
15962                    }
15963                }
15964            }
15965
15966            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15967                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15968                if (packageName == null && permissionNames == null) {
15969                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15970                        if (iperm == 0) {
15971                            if (dumpState.onTitlePrinted())
15972                                pw.println();
15973                            pw.println("AppOp Permissions:");
15974                        }
15975                        pw.print("  AppOp Permission ");
15976                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15977                        pw.println(":");
15978                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15979                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15980                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15981                        }
15982                    }
15983                }
15984            }
15985
15986            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15987                boolean printedSomething = false;
15988                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15989                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15990                        continue;
15991                    }
15992                    if (!printedSomething) {
15993                        if (dumpState.onTitlePrinted())
15994                            pw.println();
15995                        pw.println("Registered ContentProviders:");
15996                        printedSomething = true;
15997                    }
15998                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15999                    pw.print("    "); pw.println(p.toString());
16000                }
16001                printedSomething = false;
16002                for (Map.Entry<String, PackageParser.Provider> entry :
16003                        mProvidersByAuthority.entrySet()) {
16004                    PackageParser.Provider p = entry.getValue();
16005                    if (packageName != null && !packageName.equals(p.info.packageName)) {
16006                        continue;
16007                    }
16008                    if (!printedSomething) {
16009                        if (dumpState.onTitlePrinted())
16010                            pw.println();
16011                        pw.println("ContentProvider Authorities:");
16012                        printedSomething = true;
16013                    }
16014                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16015                    pw.print("    "); pw.println(p.toString());
16016                    if (p.info != null && p.info.applicationInfo != null) {
16017                        final String appInfo = p.info.applicationInfo.toString();
16018                        pw.print("      applicationInfo="); pw.println(appInfo);
16019                    }
16020                }
16021            }
16022
16023            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16024                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16025            }
16026
16027            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16028                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16029            }
16030
16031            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16032                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16033            }
16034
16035            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16036                // XXX should handle packageName != null by dumping only install data that
16037                // the given package is involved with.
16038                if (dumpState.onTitlePrinted()) pw.println();
16039                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16040            }
16041
16042            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16043                if (dumpState.onTitlePrinted()) pw.println();
16044                mSettings.dumpReadMessagesLPr(pw, dumpState);
16045
16046                pw.println();
16047                pw.println("Package warning messages:");
16048                BufferedReader in = null;
16049                String line = null;
16050                try {
16051                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16052                    while ((line = in.readLine()) != null) {
16053                        if (line.contains("ignored: updated version")) continue;
16054                        pw.println(line);
16055                    }
16056                } catch (IOException ignored) {
16057                } finally {
16058                    IoUtils.closeQuietly(in);
16059                }
16060            }
16061
16062            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16063                BufferedReader in = null;
16064                String line = null;
16065                try {
16066                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16067                    while ((line = in.readLine()) != null) {
16068                        if (line.contains("ignored: updated version")) continue;
16069                        pw.print("msg,");
16070                        pw.println(line);
16071                    }
16072                } catch (IOException ignored) {
16073                } finally {
16074                    IoUtils.closeQuietly(in);
16075                }
16076            }
16077        }
16078    }
16079
16080    private String dumpDomainString(String packageName) {
16081        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16082        List<IntentFilter> filters = getAllIntentFilters(packageName);
16083
16084        ArraySet<String> result = new ArraySet<>();
16085        if (iviList.size() > 0) {
16086            for (IntentFilterVerificationInfo ivi : iviList) {
16087                for (String host : ivi.getDomains()) {
16088                    result.add(host);
16089                }
16090            }
16091        }
16092        if (filters != null && filters.size() > 0) {
16093            for (IntentFilter filter : filters) {
16094                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16095                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16096                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16097                    result.addAll(filter.getHostsList());
16098                }
16099            }
16100        }
16101
16102        StringBuilder sb = new StringBuilder(result.size() * 16);
16103        for (String domain : result) {
16104            if (sb.length() > 0) sb.append(" ");
16105            sb.append(domain);
16106        }
16107        return sb.toString();
16108    }
16109
16110    // ------- apps on sdcard specific code -------
16111    static final boolean DEBUG_SD_INSTALL = false;
16112
16113    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16114
16115    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16116
16117    private boolean mMediaMounted = false;
16118
16119    static String getEncryptKey() {
16120        try {
16121            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16122                    SD_ENCRYPTION_KEYSTORE_NAME);
16123            if (sdEncKey == null) {
16124                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16125                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16126                if (sdEncKey == null) {
16127                    Slog.e(TAG, "Failed to create encryption keys");
16128                    return null;
16129                }
16130            }
16131            return sdEncKey;
16132        } catch (NoSuchAlgorithmException nsae) {
16133            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16134            return null;
16135        } catch (IOException ioe) {
16136            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16137            return null;
16138        }
16139    }
16140
16141    /*
16142     * Update media status on PackageManager.
16143     */
16144    @Override
16145    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16146        int callingUid = Binder.getCallingUid();
16147        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16148            throw new SecurityException("Media status can only be updated by the system");
16149        }
16150        // reader; this apparently protects mMediaMounted, but should probably
16151        // be a different lock in that case.
16152        synchronized (mPackages) {
16153            Log.i(TAG, "Updating external media status from "
16154                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16155                    + (mediaStatus ? "mounted" : "unmounted"));
16156            if (DEBUG_SD_INSTALL)
16157                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16158                        + ", mMediaMounted=" + mMediaMounted);
16159            if (mediaStatus == mMediaMounted) {
16160                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16161                        : 0, -1);
16162                mHandler.sendMessage(msg);
16163                return;
16164            }
16165            mMediaMounted = mediaStatus;
16166        }
16167        // Queue up an async operation since the package installation may take a
16168        // little while.
16169        mHandler.post(new Runnable() {
16170            public void run() {
16171                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16172            }
16173        });
16174    }
16175
16176    /**
16177     * Called by MountService when the initial ASECs to scan are available.
16178     * Should block until all the ASEC containers are finished being scanned.
16179     */
16180    public void scanAvailableAsecs() {
16181        updateExternalMediaStatusInner(true, false, false);
16182        if (mShouldRestoreconData) {
16183            SELinuxMMAC.setRestoreconDone();
16184            mShouldRestoreconData = false;
16185        }
16186    }
16187
16188    /*
16189     * Collect information of applications on external media, map them against
16190     * existing containers and update information based on current mount status.
16191     * Please note that we always have to report status if reportStatus has been
16192     * set to true especially when unloading packages.
16193     */
16194    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16195            boolean externalStorage) {
16196        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16197        int[] uidArr = EmptyArray.INT;
16198
16199        final String[] list = PackageHelper.getSecureContainerList();
16200        if (ArrayUtils.isEmpty(list)) {
16201            Log.i(TAG, "No secure containers found");
16202        } else {
16203            // Process list of secure containers and categorize them
16204            // as active or stale based on their package internal state.
16205
16206            // reader
16207            synchronized (mPackages) {
16208                for (String cid : list) {
16209                    // Leave stages untouched for now; installer service owns them
16210                    if (PackageInstallerService.isStageName(cid)) continue;
16211
16212                    if (DEBUG_SD_INSTALL)
16213                        Log.i(TAG, "Processing container " + cid);
16214                    String pkgName = getAsecPackageName(cid);
16215                    if (pkgName == null) {
16216                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16217                        continue;
16218                    }
16219                    if (DEBUG_SD_INSTALL)
16220                        Log.i(TAG, "Looking for pkg : " + pkgName);
16221
16222                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16223                    if (ps == null) {
16224                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16225                        continue;
16226                    }
16227
16228                    /*
16229                     * Skip packages that are not external if we're unmounting
16230                     * external storage.
16231                     */
16232                    if (externalStorage && !isMounted && !isExternal(ps)) {
16233                        continue;
16234                    }
16235
16236                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16237                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16238                    // The package status is changed only if the code path
16239                    // matches between settings and the container id.
16240                    if (ps.codePathString != null
16241                            && ps.codePathString.startsWith(args.getCodePath())) {
16242                        if (DEBUG_SD_INSTALL) {
16243                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16244                                    + " at code path: " + ps.codePathString);
16245                        }
16246
16247                        // We do have a valid package installed on sdcard
16248                        processCids.put(args, ps.codePathString);
16249                        final int uid = ps.appId;
16250                        if (uid != -1) {
16251                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16252                        }
16253                    } else {
16254                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16255                                + ps.codePathString);
16256                    }
16257                }
16258            }
16259
16260            Arrays.sort(uidArr);
16261        }
16262
16263        // Process packages with valid entries.
16264        if (isMounted) {
16265            if (DEBUG_SD_INSTALL)
16266                Log.i(TAG, "Loading packages");
16267            loadMediaPackages(processCids, uidArr, externalStorage);
16268            startCleaningPackages();
16269            mInstallerService.onSecureContainersAvailable();
16270        } else {
16271            if (DEBUG_SD_INSTALL)
16272                Log.i(TAG, "Unloading packages");
16273            unloadMediaPackages(processCids, uidArr, reportStatus);
16274        }
16275    }
16276
16277    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16278            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16279        final int size = infos.size();
16280        final String[] packageNames = new String[size];
16281        final int[] packageUids = new int[size];
16282        for (int i = 0; i < size; i++) {
16283            final ApplicationInfo info = infos.get(i);
16284            packageNames[i] = info.packageName;
16285            packageUids[i] = info.uid;
16286        }
16287        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16288                finishedReceiver);
16289    }
16290
16291    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16292            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16293        sendResourcesChangedBroadcast(mediaStatus, replacing,
16294                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16295    }
16296
16297    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16298            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16299        int size = pkgList.length;
16300        if (size > 0) {
16301            // Send broadcasts here
16302            Bundle extras = new Bundle();
16303            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16304            if (uidArr != null) {
16305                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16306            }
16307            if (replacing) {
16308                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16309            }
16310            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16311                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16312            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16313        }
16314    }
16315
16316   /*
16317     * Look at potentially valid container ids from processCids If package
16318     * information doesn't match the one on record or package scanning fails,
16319     * the cid is added to list of removeCids. We currently don't delete stale
16320     * containers.
16321     */
16322    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16323            boolean externalStorage) {
16324        ArrayList<String> pkgList = new ArrayList<String>();
16325        Set<AsecInstallArgs> keys = processCids.keySet();
16326
16327        for (AsecInstallArgs args : keys) {
16328            String codePath = processCids.get(args);
16329            if (DEBUG_SD_INSTALL)
16330                Log.i(TAG, "Loading container : " + args.cid);
16331            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16332            try {
16333                // Make sure there are no container errors first.
16334                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16335                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16336                            + " when installing from sdcard");
16337                    continue;
16338                }
16339                // Check code path here.
16340                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16341                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16342                            + " does not match one in settings " + codePath);
16343                    continue;
16344                }
16345                // Parse package
16346                int parseFlags = mDefParseFlags;
16347                if (args.isExternalAsec()) {
16348                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16349                }
16350                if (args.isFwdLocked()) {
16351                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16352                }
16353
16354                synchronized (mInstallLock) {
16355                    PackageParser.Package pkg = null;
16356                    try {
16357                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16358                    } catch (PackageManagerException e) {
16359                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16360                    }
16361                    // Scan the package
16362                    if (pkg != null) {
16363                        /*
16364                         * TODO why is the lock being held? doPostInstall is
16365                         * called in other places without the lock. This needs
16366                         * to be straightened out.
16367                         */
16368                        // writer
16369                        synchronized (mPackages) {
16370                            retCode = PackageManager.INSTALL_SUCCEEDED;
16371                            pkgList.add(pkg.packageName);
16372                            // Post process args
16373                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16374                                    pkg.applicationInfo.uid);
16375                        }
16376                    } else {
16377                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16378                    }
16379                }
16380
16381            } finally {
16382                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16383                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16384                }
16385            }
16386        }
16387        // writer
16388        synchronized (mPackages) {
16389            // If the platform SDK has changed since the last time we booted,
16390            // we need to re-grant app permission to catch any new ones that
16391            // appear. This is really a hack, and means that apps can in some
16392            // cases get permissions that the user didn't initially explicitly
16393            // allow... it would be nice to have some better way to handle
16394            // this situation.
16395            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16396                    : mSettings.getInternalVersion();
16397            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16398                    : StorageManager.UUID_PRIVATE_INTERNAL;
16399
16400            int updateFlags = UPDATE_PERMISSIONS_ALL;
16401            if (ver.sdkVersion != mSdkVersion) {
16402                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16403                        + mSdkVersion + "; regranting permissions for external");
16404                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16405            }
16406            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16407
16408            // Yay, everything is now upgraded
16409            ver.forceCurrent();
16410
16411            // can downgrade to reader
16412            // Persist settings
16413            mSettings.writeLPr();
16414        }
16415        // Send a broadcast to let everyone know we are done processing
16416        if (pkgList.size() > 0) {
16417            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16418        }
16419    }
16420
16421   /*
16422     * Utility method to unload a list of specified containers
16423     */
16424    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16425        // Just unmount all valid containers.
16426        for (AsecInstallArgs arg : cidArgs) {
16427            synchronized (mInstallLock) {
16428                arg.doPostDeleteLI(false);
16429           }
16430       }
16431   }
16432
16433    /*
16434     * Unload packages mounted on external media. This involves deleting package
16435     * data from internal structures, sending broadcasts about diabled packages,
16436     * gc'ing to free up references, unmounting all secure containers
16437     * corresponding to packages on external media, and posting a
16438     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16439     * that we always have to post this message if status has been requested no
16440     * matter what.
16441     */
16442    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16443            final boolean reportStatus) {
16444        if (DEBUG_SD_INSTALL)
16445            Log.i(TAG, "unloading media packages");
16446        ArrayList<String> pkgList = new ArrayList<String>();
16447        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16448        final Set<AsecInstallArgs> keys = processCids.keySet();
16449        for (AsecInstallArgs args : keys) {
16450            String pkgName = args.getPackageName();
16451            if (DEBUG_SD_INSTALL)
16452                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16453            // Delete package internally
16454            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16455            synchronized (mInstallLock) {
16456                boolean res = deletePackageLI(pkgName, null, false, null, null,
16457                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16458                if (res) {
16459                    pkgList.add(pkgName);
16460                } else {
16461                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16462                    failedList.add(args);
16463                }
16464            }
16465        }
16466
16467        // reader
16468        synchronized (mPackages) {
16469            // We didn't update the settings after removing each package;
16470            // write them now for all packages.
16471            mSettings.writeLPr();
16472        }
16473
16474        // We have to absolutely send UPDATED_MEDIA_STATUS only
16475        // after confirming that all the receivers processed the ordered
16476        // broadcast when packages get disabled, force a gc to clean things up.
16477        // and unload all the containers.
16478        if (pkgList.size() > 0) {
16479            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16480                    new IIntentReceiver.Stub() {
16481                public void performReceive(Intent intent, int resultCode, String data,
16482                        Bundle extras, boolean ordered, boolean sticky,
16483                        int sendingUser) throws RemoteException {
16484                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16485                            reportStatus ? 1 : 0, 1, keys);
16486                    mHandler.sendMessage(msg);
16487                }
16488            });
16489        } else {
16490            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16491                    keys);
16492            mHandler.sendMessage(msg);
16493        }
16494    }
16495
16496    private void loadPrivatePackages(final VolumeInfo vol) {
16497        mHandler.post(new Runnable() {
16498            @Override
16499            public void run() {
16500                loadPrivatePackagesInner(vol);
16501            }
16502        });
16503    }
16504
16505    private void loadPrivatePackagesInner(VolumeInfo vol) {
16506        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16507        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16508
16509        final VersionInfo ver;
16510        final List<PackageSetting> packages;
16511        synchronized (mPackages) {
16512            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16513            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16514        }
16515
16516        for (PackageSetting ps : packages) {
16517            synchronized (mInstallLock) {
16518                final PackageParser.Package pkg;
16519                try {
16520                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16521                    loaded.add(pkg.applicationInfo);
16522                } catch (PackageManagerException e) {
16523                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16524                }
16525
16526                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16527                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16528                }
16529            }
16530        }
16531
16532        synchronized (mPackages) {
16533            int updateFlags = UPDATE_PERMISSIONS_ALL;
16534            if (ver.sdkVersion != mSdkVersion) {
16535                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16536                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16537                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16538            }
16539            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16540
16541            // Yay, everything is now upgraded
16542            ver.forceCurrent();
16543
16544            mSettings.writeLPr();
16545        }
16546
16547        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16548        sendResourcesChangedBroadcast(true, false, loaded, null);
16549    }
16550
16551    private void unloadPrivatePackages(final VolumeInfo vol) {
16552        mHandler.post(new Runnable() {
16553            @Override
16554            public void run() {
16555                unloadPrivatePackagesInner(vol);
16556            }
16557        });
16558    }
16559
16560    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16561        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16562        synchronized (mInstallLock) {
16563        synchronized (mPackages) {
16564            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16565            for (PackageSetting ps : packages) {
16566                if (ps.pkg == null) continue;
16567
16568                final ApplicationInfo info = ps.pkg.applicationInfo;
16569                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16570                if (deletePackageLI(ps.name, null, false, null, null,
16571                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16572                    unloaded.add(info);
16573                } else {
16574                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16575                }
16576            }
16577
16578            mSettings.writeLPr();
16579        }
16580        }
16581
16582        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16583        sendResourcesChangedBroadcast(false, false, unloaded, null);
16584    }
16585
16586    /**
16587     * Examine all users present on given mounted volume, and destroy data
16588     * belonging to users that are no longer valid, or whose user ID has been
16589     * recycled.
16590     */
16591    private void reconcileUsers(String volumeUuid) {
16592        final File[] files = FileUtils
16593                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16594        for (File file : files) {
16595            if (!file.isDirectory()) continue;
16596
16597            final int userId;
16598            final UserInfo info;
16599            try {
16600                userId = Integer.parseInt(file.getName());
16601                info = sUserManager.getUserInfo(userId);
16602            } catch (NumberFormatException e) {
16603                Slog.w(TAG, "Invalid user directory " + file);
16604                continue;
16605            }
16606
16607            boolean destroyUser = false;
16608            if (info == null) {
16609                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16610                        + " because no matching user was found");
16611                destroyUser = true;
16612            } else {
16613                try {
16614                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16615                } catch (IOException e) {
16616                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16617                            + " because we failed to enforce serial number: " + e);
16618                    destroyUser = true;
16619                }
16620            }
16621
16622            if (destroyUser) {
16623                synchronized (mInstallLock) {
16624                    try {
16625                        mInstaller.removeUserDataDirs(volumeUuid, userId);
16626                    } catch (InstallerException e) {
16627                        Slog.w(TAG, "Failed to clean up user dirs", e);
16628                    }
16629                }
16630            }
16631        }
16632
16633        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16634        final UserManager um = mContext.getSystemService(UserManager.class);
16635        for (UserInfo user : um.getUsers()) {
16636            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16637            if (userDir.exists()) continue;
16638
16639            try {
16640                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16641                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16642            } catch (IOException e) {
16643                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16644            }
16645        }
16646    }
16647
16648    /**
16649     * Examine all apps present on given mounted volume, and destroy apps that
16650     * aren't expected, either due to uninstallation or reinstallation on
16651     * another volume.
16652     */
16653    private void reconcileApps(String volumeUuid) {
16654        final File[] files = FileUtils
16655                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16656        for (File file : files) {
16657            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16658                    && !PackageInstallerService.isStageName(file.getName());
16659            if (!isPackage) {
16660                // Ignore entries which are not packages
16661                continue;
16662            }
16663
16664            boolean destroyApp = false;
16665            String packageName = null;
16666            try {
16667                final PackageLite pkg = PackageParser.parsePackageLite(file,
16668                        PackageParser.PARSE_MUST_BE_APK);
16669                packageName = pkg.packageName;
16670
16671                synchronized (mPackages) {
16672                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16673                    if (ps == null) {
16674                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16675                                + volumeUuid + " because we found no install record");
16676                        destroyApp = true;
16677                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16678                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16679                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16680                        destroyApp = true;
16681                    }
16682                }
16683
16684            } catch (PackageParserException e) {
16685                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16686                destroyApp = true;
16687            }
16688
16689            if (destroyApp) {
16690                synchronized (mInstallLock) {
16691                    if (packageName != null) {
16692                        removeDataDirsLI(volumeUuid, packageName);
16693                    }
16694                    removeCodePathLI(file);
16695                }
16696            }
16697        }
16698    }
16699
16700    private void unfreezePackage(String packageName) {
16701        synchronized (mPackages) {
16702            final PackageSetting ps = mSettings.mPackages.get(packageName);
16703            if (ps != null) {
16704                ps.frozen = false;
16705            }
16706        }
16707    }
16708
16709    @Override
16710    public int movePackage(final String packageName, final String volumeUuid) {
16711        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16712
16713        final int moveId = mNextMoveId.getAndIncrement();
16714        mHandler.post(new Runnable() {
16715            @Override
16716            public void run() {
16717                try {
16718                    movePackageInternal(packageName, volumeUuid, moveId);
16719                } catch (PackageManagerException e) {
16720                    Slog.w(TAG, "Failed to move " + packageName, e);
16721                    mMoveCallbacks.notifyStatusChanged(moveId,
16722                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16723                }
16724            }
16725        });
16726        return moveId;
16727    }
16728
16729    private void movePackageInternal(final String packageName, final String volumeUuid,
16730            final int moveId) throws PackageManagerException {
16731        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16732        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16733        final PackageManager pm = mContext.getPackageManager();
16734
16735        final boolean currentAsec;
16736        final String currentVolumeUuid;
16737        final File codeFile;
16738        final String installerPackageName;
16739        final String packageAbiOverride;
16740        final int appId;
16741        final String seinfo;
16742        final String label;
16743
16744        // reader
16745        synchronized (mPackages) {
16746            final PackageParser.Package pkg = mPackages.get(packageName);
16747            final PackageSetting ps = mSettings.mPackages.get(packageName);
16748            if (pkg == null || ps == null) {
16749                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16750            }
16751
16752            if (pkg.applicationInfo.isSystemApp()) {
16753                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16754                        "Cannot move system application");
16755            }
16756
16757            if (pkg.applicationInfo.isExternalAsec()) {
16758                currentAsec = true;
16759                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16760            } else if (pkg.applicationInfo.isForwardLocked()) {
16761                currentAsec = true;
16762                currentVolumeUuid = "forward_locked";
16763            } else {
16764                currentAsec = false;
16765                currentVolumeUuid = ps.volumeUuid;
16766
16767                final File probe = new File(pkg.codePath);
16768                final File probeOat = new File(probe, "oat");
16769                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16770                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16771                            "Move only supported for modern cluster style installs");
16772                }
16773            }
16774
16775            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16776                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16777                        "Package already moved to " + volumeUuid);
16778            }
16779
16780            if (ps.frozen) {
16781                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16782                        "Failed to move already frozen package");
16783            }
16784            ps.frozen = true;
16785
16786            codeFile = new File(pkg.codePath);
16787            installerPackageName = ps.installerPackageName;
16788            packageAbiOverride = ps.cpuAbiOverrideString;
16789            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16790            seinfo = pkg.applicationInfo.seinfo;
16791            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16792        }
16793
16794        // Now that we're guarded by frozen state, kill app during move
16795        final long token = Binder.clearCallingIdentity();
16796        try {
16797            killApplication(packageName, appId, "move pkg");
16798        } finally {
16799            Binder.restoreCallingIdentity(token);
16800        }
16801
16802        final Bundle extras = new Bundle();
16803        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16804        extras.putString(Intent.EXTRA_TITLE, label);
16805        mMoveCallbacks.notifyCreated(moveId, extras);
16806
16807        int installFlags;
16808        final boolean moveCompleteApp;
16809        final File measurePath;
16810
16811        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16812            installFlags = INSTALL_INTERNAL;
16813            moveCompleteApp = !currentAsec;
16814            measurePath = Environment.getDataAppDirectory(volumeUuid);
16815        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16816            installFlags = INSTALL_EXTERNAL;
16817            moveCompleteApp = false;
16818            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16819        } else {
16820            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16821            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16822                    || !volume.isMountedWritable()) {
16823                unfreezePackage(packageName);
16824                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16825                        "Move location not mounted private volume");
16826            }
16827
16828            Preconditions.checkState(!currentAsec);
16829
16830            installFlags = INSTALL_INTERNAL;
16831            moveCompleteApp = true;
16832            measurePath = Environment.getDataAppDirectory(volumeUuid);
16833        }
16834
16835        final PackageStats stats = new PackageStats(null, -1);
16836        synchronized (mInstaller) {
16837            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16838                unfreezePackage(packageName);
16839                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16840                        "Failed to measure package size");
16841            }
16842        }
16843
16844        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16845                + stats.dataSize);
16846
16847        final long startFreeBytes = measurePath.getFreeSpace();
16848        final long sizeBytes;
16849        if (moveCompleteApp) {
16850            sizeBytes = stats.codeSize + stats.dataSize;
16851        } else {
16852            sizeBytes = stats.codeSize;
16853        }
16854
16855        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16856            unfreezePackage(packageName);
16857            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16858                    "Not enough free space to move");
16859        }
16860
16861        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16862
16863        final CountDownLatch installedLatch = new CountDownLatch(1);
16864        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16865            @Override
16866            public void onUserActionRequired(Intent intent) throws RemoteException {
16867                throw new IllegalStateException();
16868            }
16869
16870            @Override
16871            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16872                    Bundle extras) throws RemoteException {
16873                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16874                        + PackageManager.installStatusToString(returnCode, msg));
16875
16876                installedLatch.countDown();
16877
16878                // Regardless of success or failure of the move operation,
16879                // always unfreeze the package
16880                unfreezePackage(packageName);
16881
16882                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16883                switch (status) {
16884                    case PackageInstaller.STATUS_SUCCESS:
16885                        mMoveCallbacks.notifyStatusChanged(moveId,
16886                                PackageManager.MOVE_SUCCEEDED);
16887                        break;
16888                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16889                        mMoveCallbacks.notifyStatusChanged(moveId,
16890                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16891                        break;
16892                    default:
16893                        mMoveCallbacks.notifyStatusChanged(moveId,
16894                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16895                        break;
16896                }
16897            }
16898        };
16899
16900        final MoveInfo move;
16901        if (moveCompleteApp) {
16902            // Kick off a thread to report progress estimates
16903            new Thread() {
16904                @Override
16905                public void run() {
16906                    while (true) {
16907                        try {
16908                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16909                                break;
16910                            }
16911                        } catch (InterruptedException ignored) {
16912                        }
16913
16914                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16915                        final int progress = 10 + (int) MathUtils.constrain(
16916                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16917                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16918                    }
16919                }
16920            }.start();
16921
16922            final String dataAppName = codeFile.getName();
16923            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16924                    dataAppName, appId, seinfo);
16925        } else {
16926            move = null;
16927        }
16928
16929        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16930
16931        final Message msg = mHandler.obtainMessage(INIT_COPY);
16932        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16933        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16934                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16935        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16936        msg.obj = params;
16937
16938        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16939                System.identityHashCode(msg.obj));
16940        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16941                System.identityHashCode(msg.obj));
16942
16943        mHandler.sendMessage(msg);
16944    }
16945
16946    @Override
16947    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16948        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16949
16950        final int realMoveId = mNextMoveId.getAndIncrement();
16951        final Bundle extras = new Bundle();
16952        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16953        mMoveCallbacks.notifyCreated(realMoveId, extras);
16954
16955        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16956            @Override
16957            public void onCreated(int moveId, Bundle extras) {
16958                // Ignored
16959            }
16960
16961            @Override
16962            public void onStatusChanged(int moveId, int status, long estMillis) {
16963                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16964            }
16965        };
16966
16967        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16968        storage.setPrimaryStorageUuid(volumeUuid, callback);
16969        return realMoveId;
16970    }
16971
16972    @Override
16973    public int getMoveStatus(int moveId) {
16974        mContext.enforceCallingOrSelfPermission(
16975                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16976        return mMoveCallbacks.mLastStatus.get(moveId);
16977    }
16978
16979    @Override
16980    public void registerMoveCallback(IPackageMoveObserver callback) {
16981        mContext.enforceCallingOrSelfPermission(
16982                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16983        mMoveCallbacks.register(callback);
16984    }
16985
16986    @Override
16987    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16988        mContext.enforceCallingOrSelfPermission(
16989                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16990        mMoveCallbacks.unregister(callback);
16991    }
16992
16993    @Override
16994    public boolean setInstallLocation(int loc) {
16995        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16996                null);
16997        if (getInstallLocation() == loc) {
16998            return true;
16999        }
17000        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
17001                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
17002            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
17003                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
17004            return true;
17005        }
17006        return false;
17007   }
17008
17009    @Override
17010    public int getInstallLocation() {
17011        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
17012                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
17013                PackageHelper.APP_INSTALL_AUTO);
17014    }
17015
17016    /** Called by UserManagerService */
17017    void cleanUpUser(UserManagerService userManager, int userHandle) {
17018        synchronized (mPackages) {
17019            mDirtyUsers.remove(userHandle);
17020            mUserNeedsBadging.delete(userHandle);
17021            mSettings.removeUserLPw(userHandle);
17022            mPendingBroadcasts.remove(userHandle);
17023            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17024        }
17025        synchronized (mInstallLock) {
17026            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17027            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17028                final String volumeUuid = vol.getFsUuid();
17029                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17030                try {
17031                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17032                } catch (InstallerException e) {
17033                    Slog.w(TAG, "Failed to remove user data", e);
17034                }
17035            }
17036            synchronized (mPackages) {
17037                removeUnusedPackagesLILPw(userManager, userHandle);
17038            }
17039        }
17040    }
17041
17042    /**
17043     * We're removing userHandle and would like to remove any downloaded packages
17044     * that are no longer in use by any other user.
17045     * @param userHandle the user being removed
17046     */
17047    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17048        final boolean DEBUG_CLEAN_APKS = false;
17049        int [] users = userManager.getUserIds();
17050        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17051        while (psit.hasNext()) {
17052            PackageSetting ps = psit.next();
17053            if (ps.pkg == null) {
17054                continue;
17055            }
17056            final String packageName = ps.pkg.packageName;
17057            // Skip over if system app
17058            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17059                continue;
17060            }
17061            if (DEBUG_CLEAN_APKS) {
17062                Slog.i(TAG, "Checking package " + packageName);
17063            }
17064            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17065            if (keep) {
17066                if (DEBUG_CLEAN_APKS) {
17067                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17068                }
17069            } else {
17070                for (int i = 0; i < users.length; i++) {
17071                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17072                        keep = true;
17073                        if (DEBUG_CLEAN_APKS) {
17074                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17075                                    + users[i]);
17076                        }
17077                        break;
17078                    }
17079                }
17080            }
17081            if (!keep) {
17082                if (DEBUG_CLEAN_APKS) {
17083                    Slog.i(TAG, "  Removing package " + packageName);
17084                }
17085                mHandler.post(new Runnable() {
17086                    public void run() {
17087                        deletePackageX(packageName, userHandle, 0);
17088                    } //end run
17089                });
17090            }
17091        }
17092    }
17093
17094    /** Called by UserManagerService */
17095    void createNewUser(int userHandle) {
17096        synchronized (mInstallLock) {
17097            try {
17098                mInstaller.createUserConfig(userHandle);
17099            } catch (InstallerException e) {
17100                Slog.w(TAG, "Failed to create user config", e);
17101            }
17102            mSettings.createNewUserLI(this, mInstaller, userHandle);
17103        }
17104        synchronized (mPackages) {
17105            applyFactoryDefaultBrowserLPw(userHandle);
17106            primeDomainVerificationsLPw(userHandle);
17107        }
17108    }
17109
17110    void newUserCreated(final int userHandle) {
17111        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17112        // If permission review for legacy apps is required, we represent
17113        // dagerous permissions for such apps as always granted runtime
17114        // permissions to keep per user flag state whether review is needed.
17115        // Hence, if a new user is added we have to propagate dangerous
17116        // permission grants for these legacy apps.
17117        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17118            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17119                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17120        }
17121    }
17122
17123    @Override
17124    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17125        mContext.enforceCallingOrSelfPermission(
17126                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17127                "Only package verification agents can read the verifier device identity");
17128
17129        synchronized (mPackages) {
17130            return mSettings.getVerifierDeviceIdentityLPw();
17131        }
17132    }
17133
17134    @Override
17135    public void setPermissionEnforced(String permission, boolean enforced) {
17136        // TODO: Now that we no longer change GID for storage, this should to away.
17137        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17138                "setPermissionEnforced");
17139        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17140            synchronized (mPackages) {
17141                if (mSettings.mReadExternalStorageEnforced == null
17142                        || mSettings.mReadExternalStorageEnforced != enforced) {
17143                    mSettings.mReadExternalStorageEnforced = enforced;
17144                    mSettings.writeLPr();
17145                }
17146            }
17147            // kill any non-foreground processes so we restart them and
17148            // grant/revoke the GID.
17149            final IActivityManager am = ActivityManagerNative.getDefault();
17150            if (am != null) {
17151                final long token = Binder.clearCallingIdentity();
17152                try {
17153                    am.killProcessesBelowForeground("setPermissionEnforcement");
17154                } catch (RemoteException e) {
17155                } finally {
17156                    Binder.restoreCallingIdentity(token);
17157                }
17158            }
17159        } else {
17160            throw new IllegalArgumentException("No selective enforcement for " + permission);
17161        }
17162    }
17163
17164    @Override
17165    @Deprecated
17166    public boolean isPermissionEnforced(String permission) {
17167        return true;
17168    }
17169
17170    @Override
17171    public boolean isStorageLow() {
17172        final long token = Binder.clearCallingIdentity();
17173        try {
17174            final DeviceStorageMonitorInternal
17175                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17176            if (dsm != null) {
17177                return dsm.isMemoryLow();
17178            } else {
17179                return false;
17180            }
17181        } finally {
17182            Binder.restoreCallingIdentity(token);
17183        }
17184    }
17185
17186    @Override
17187    public IPackageInstaller getPackageInstaller() {
17188        return mInstallerService;
17189    }
17190
17191    private boolean userNeedsBadging(int userId) {
17192        int index = mUserNeedsBadging.indexOfKey(userId);
17193        if (index < 0) {
17194            final UserInfo userInfo;
17195            final long token = Binder.clearCallingIdentity();
17196            try {
17197                userInfo = sUserManager.getUserInfo(userId);
17198            } finally {
17199                Binder.restoreCallingIdentity(token);
17200            }
17201            final boolean b;
17202            if (userInfo != null && userInfo.isManagedProfile()) {
17203                b = true;
17204            } else {
17205                b = false;
17206            }
17207            mUserNeedsBadging.put(userId, b);
17208            return b;
17209        }
17210        return mUserNeedsBadging.valueAt(index);
17211    }
17212
17213    @Override
17214    public KeySet getKeySetByAlias(String packageName, String alias) {
17215        if (packageName == null || alias == null) {
17216            return null;
17217        }
17218        synchronized(mPackages) {
17219            final PackageParser.Package pkg = mPackages.get(packageName);
17220            if (pkg == null) {
17221                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17222                throw new IllegalArgumentException("Unknown package: " + packageName);
17223            }
17224            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17225            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17226        }
17227    }
17228
17229    @Override
17230    public KeySet getSigningKeySet(String packageName) {
17231        if (packageName == null) {
17232            return null;
17233        }
17234        synchronized(mPackages) {
17235            final PackageParser.Package pkg = mPackages.get(packageName);
17236            if (pkg == null) {
17237                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17238                throw new IllegalArgumentException("Unknown package: " + packageName);
17239            }
17240            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17241                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17242                throw new SecurityException("May not access signing KeySet of other apps.");
17243            }
17244            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17245            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17246        }
17247    }
17248
17249    @Override
17250    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17251        if (packageName == null || ks == null) {
17252            return false;
17253        }
17254        synchronized(mPackages) {
17255            final PackageParser.Package pkg = mPackages.get(packageName);
17256            if (pkg == null) {
17257                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17258                throw new IllegalArgumentException("Unknown package: " + packageName);
17259            }
17260            IBinder ksh = ks.getToken();
17261            if (ksh instanceof KeySetHandle) {
17262                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17263                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17264            }
17265            return false;
17266        }
17267    }
17268
17269    @Override
17270    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17271        if (packageName == null || ks == null) {
17272            return false;
17273        }
17274        synchronized(mPackages) {
17275            final PackageParser.Package pkg = mPackages.get(packageName);
17276            if (pkg == null) {
17277                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17278                throw new IllegalArgumentException("Unknown package: " + packageName);
17279            }
17280            IBinder ksh = ks.getToken();
17281            if (ksh instanceof KeySetHandle) {
17282                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17283                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17284            }
17285            return false;
17286        }
17287    }
17288
17289    private void deletePackageIfUnusedLPr(final String packageName) {
17290        PackageSetting ps = mSettings.mPackages.get(packageName);
17291        if (ps == null) {
17292            return;
17293        }
17294        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17295            // TODO Implement atomic delete if package is unused
17296            // It is currently possible that the package will be deleted even if it is installed
17297            // after this method returns.
17298            mHandler.post(new Runnable() {
17299                public void run() {
17300                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17301                }
17302            });
17303        }
17304    }
17305
17306    /**
17307     * Check and throw if the given before/after packages would be considered a
17308     * downgrade.
17309     */
17310    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17311            throws PackageManagerException {
17312        if (after.versionCode < before.mVersionCode) {
17313            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17314                    "Update version code " + after.versionCode + " is older than current "
17315                    + before.mVersionCode);
17316        } else if (after.versionCode == before.mVersionCode) {
17317            if (after.baseRevisionCode < before.baseRevisionCode) {
17318                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17319                        "Update base revision code " + after.baseRevisionCode
17320                        + " is older than current " + before.baseRevisionCode);
17321            }
17322
17323            if (!ArrayUtils.isEmpty(after.splitNames)) {
17324                for (int i = 0; i < after.splitNames.length; i++) {
17325                    final String splitName = after.splitNames[i];
17326                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17327                    if (j != -1) {
17328                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17329                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17330                                    "Update split " + splitName + " revision code "
17331                                    + after.splitRevisionCodes[i] + " is older than current "
17332                                    + before.splitRevisionCodes[j]);
17333                        }
17334                    }
17335                }
17336            }
17337        }
17338    }
17339
17340    private static class MoveCallbacks extends Handler {
17341        private static final int MSG_CREATED = 1;
17342        private static final int MSG_STATUS_CHANGED = 2;
17343
17344        private final RemoteCallbackList<IPackageMoveObserver>
17345                mCallbacks = new RemoteCallbackList<>();
17346
17347        private final SparseIntArray mLastStatus = new SparseIntArray();
17348
17349        public MoveCallbacks(Looper looper) {
17350            super(looper);
17351        }
17352
17353        public void register(IPackageMoveObserver callback) {
17354            mCallbacks.register(callback);
17355        }
17356
17357        public void unregister(IPackageMoveObserver callback) {
17358            mCallbacks.unregister(callback);
17359        }
17360
17361        @Override
17362        public void handleMessage(Message msg) {
17363            final SomeArgs args = (SomeArgs) msg.obj;
17364            final int n = mCallbacks.beginBroadcast();
17365            for (int i = 0; i < n; i++) {
17366                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17367                try {
17368                    invokeCallback(callback, msg.what, args);
17369                } catch (RemoteException ignored) {
17370                }
17371            }
17372            mCallbacks.finishBroadcast();
17373            args.recycle();
17374        }
17375
17376        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17377                throws RemoteException {
17378            switch (what) {
17379                case MSG_CREATED: {
17380                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17381                    break;
17382                }
17383                case MSG_STATUS_CHANGED: {
17384                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17385                    break;
17386                }
17387            }
17388        }
17389
17390        private void notifyCreated(int moveId, Bundle extras) {
17391            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17392
17393            final SomeArgs args = SomeArgs.obtain();
17394            args.argi1 = moveId;
17395            args.arg2 = extras;
17396            obtainMessage(MSG_CREATED, args).sendToTarget();
17397        }
17398
17399        private void notifyStatusChanged(int moveId, int status) {
17400            notifyStatusChanged(moveId, status, -1);
17401        }
17402
17403        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17404            Slog.v(TAG, "Move " + moveId + " status " + status);
17405
17406            final SomeArgs args = SomeArgs.obtain();
17407            args.argi1 = moveId;
17408            args.argi2 = status;
17409            args.arg3 = estMillis;
17410            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17411
17412            synchronized (mLastStatus) {
17413                mLastStatus.put(moveId, status);
17414            }
17415        }
17416    }
17417
17418    private final static class OnPermissionChangeListeners extends Handler {
17419        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17420
17421        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17422                new RemoteCallbackList<>();
17423
17424        public OnPermissionChangeListeners(Looper looper) {
17425            super(looper);
17426        }
17427
17428        @Override
17429        public void handleMessage(Message msg) {
17430            switch (msg.what) {
17431                case MSG_ON_PERMISSIONS_CHANGED: {
17432                    final int uid = msg.arg1;
17433                    handleOnPermissionsChanged(uid);
17434                } break;
17435            }
17436        }
17437
17438        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17439            mPermissionListeners.register(listener);
17440
17441        }
17442
17443        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17444            mPermissionListeners.unregister(listener);
17445        }
17446
17447        public void onPermissionsChanged(int uid) {
17448            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17449                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17450            }
17451        }
17452
17453        private void handleOnPermissionsChanged(int uid) {
17454            final int count = mPermissionListeners.beginBroadcast();
17455            try {
17456                for (int i = 0; i < count; i++) {
17457                    IOnPermissionsChangeListener callback = mPermissionListeners
17458                            .getBroadcastItem(i);
17459                    try {
17460                        callback.onPermissionsChanged(uid);
17461                    } catch (RemoteException e) {
17462                        Log.e(TAG, "Permission listener is dead", e);
17463                    }
17464                }
17465            } finally {
17466                mPermissionListeners.finishBroadcast();
17467            }
17468        }
17469    }
17470
17471    private class PackageManagerInternalImpl extends PackageManagerInternal {
17472        @Override
17473        public void setLocationPackagesProvider(PackagesProvider provider) {
17474            synchronized (mPackages) {
17475                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17476            }
17477        }
17478
17479        @Override
17480        public void setImePackagesProvider(PackagesProvider provider) {
17481            synchronized (mPackages) {
17482                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17483            }
17484        }
17485
17486        @Override
17487        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17488            synchronized (mPackages) {
17489                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17490            }
17491        }
17492
17493        @Override
17494        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17495            synchronized (mPackages) {
17496                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17497            }
17498        }
17499
17500        @Override
17501        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17502            synchronized (mPackages) {
17503                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17504            }
17505        }
17506
17507        @Override
17508        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17509            synchronized (mPackages) {
17510                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17511            }
17512        }
17513
17514        @Override
17515        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17516            synchronized (mPackages) {
17517                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17518            }
17519        }
17520
17521        @Override
17522        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17523            synchronized (mPackages) {
17524                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17525                        packageName, userId);
17526            }
17527        }
17528
17529        @Override
17530        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17531            synchronized (mPackages) {
17532                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17533                        packageName, userId);
17534            }
17535        }
17536
17537        @Override
17538        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17539            synchronized (mPackages) {
17540                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17541                        packageName, userId);
17542            }
17543        }
17544
17545        @Override
17546        public void setKeepUninstalledPackages(final List<String> packageList) {
17547            Preconditions.checkNotNull(packageList);
17548            List<String> removedFromList = null;
17549            synchronized (mPackages) {
17550                if (mKeepUninstalledPackages != null) {
17551                    final int packagesCount = mKeepUninstalledPackages.size();
17552                    for (int i = 0; i < packagesCount; i++) {
17553                        String oldPackage = mKeepUninstalledPackages.get(i);
17554                        if (packageList != null && packageList.contains(oldPackage)) {
17555                            continue;
17556                        }
17557                        if (removedFromList == null) {
17558                            removedFromList = new ArrayList<>();
17559                        }
17560                        removedFromList.add(oldPackage);
17561                    }
17562                }
17563                mKeepUninstalledPackages = new ArrayList<>(packageList);
17564                if (removedFromList != null) {
17565                    final int removedCount = removedFromList.size();
17566                    for (int i = 0; i < removedCount; i++) {
17567                        deletePackageIfUnusedLPr(removedFromList.get(i));
17568                    }
17569                }
17570            }
17571        }
17572
17573        @Override
17574        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17575            synchronized (mPackages) {
17576                // If we do not support permission review, done.
17577                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17578                    return false;
17579                }
17580
17581                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17582                if (packageSetting == null) {
17583                    return false;
17584                }
17585
17586                // Permission review applies only to apps not supporting the new permission model.
17587                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17588                    return false;
17589                }
17590
17591                // Legacy apps have the permission and get user consent on launch.
17592                PermissionsState permissionsState = packageSetting.getPermissionsState();
17593                return permissionsState.isPermissionReviewRequired(userId);
17594            }
17595        }
17596    }
17597
17598    @Override
17599    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17600        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17601        synchronized (mPackages) {
17602            final long identity = Binder.clearCallingIdentity();
17603            try {
17604                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17605                        packageNames, userId);
17606            } finally {
17607                Binder.restoreCallingIdentity(identity);
17608            }
17609        }
17610    }
17611
17612    private static void enforceSystemOrPhoneCaller(String tag) {
17613        int callingUid = Binder.getCallingUid();
17614        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17615            throw new SecurityException(
17616                    "Cannot call " + tag + " from UID " + callingUid);
17617        }
17618    }
17619}
17620