PackageManagerService.java revision 0e62384ccbd00e9f78851929ca88b919679ee32e
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_UPDATE_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
51import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
52import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
53import static android.content.pm.PackageManager.INSTALL_INTERNAL;
54import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
55import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.MATCH_ALL;
61import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
62import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
63import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
64import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
65import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
66import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
67import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
68import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
69import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
70import static android.content.pm.PackageManager.PERMISSION_DENIED;
71import static android.content.pm.PackageManager.PERMISSION_GRANTED;
72import static android.content.pm.PackageParser.isApkFile;
73import static android.os.Process.PACKAGE_INFO_GID;
74import static android.os.Process.SYSTEM_UID;
75import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
76import static android.system.OsConstants.O_CREAT;
77import static android.system.OsConstants.O_RDWR;
78
79import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
81import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
82import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
83import static com.android.internal.util.ArrayUtils.appendInt;
84import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
85import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
86import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
88import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
89import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
90import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
93
94import android.Manifest;
95import android.annotation.NonNull;
96import android.annotation.Nullable;
97import android.app.ActivityManager;
98import android.app.ActivityManagerNative;
99import android.app.AppGlobals;
100import android.app.IActivityManager;
101import android.app.admin.IDevicePolicyManager;
102import android.app.backup.IBackupManager;
103import android.content.BroadcastReceiver;
104import android.content.ComponentName;
105import android.content.Context;
106import android.content.IIntentReceiver;
107import android.content.Intent;
108import android.content.IntentFilter;
109import android.content.IntentSender;
110import android.content.IntentSender.SendIntentException;
111import android.content.ServiceConnection;
112import android.content.pm.ActivityInfo;
113import android.content.pm.ApplicationInfo;
114import android.content.pm.AppsQueryHelper;
115import android.content.pm.ComponentInfo;
116import android.content.pm.EphemeralApplicationInfo;
117import android.content.pm.EphemeralResolveInfo;
118import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
119import android.content.pm.FeatureInfo;
120import android.content.pm.IOnPermissionsChangeListener;
121import android.content.pm.IPackageDataObserver;
122import android.content.pm.IPackageDeleteObserver;
123import android.content.pm.IPackageDeleteObserver2;
124import android.content.pm.IPackageInstallObserver2;
125import android.content.pm.IPackageInstaller;
126import android.content.pm.IPackageManager;
127import android.content.pm.IPackageMoveObserver;
128import android.content.pm.IPackageStatsObserver;
129import android.content.pm.InstrumentationInfo;
130import android.content.pm.IntentFilterVerificationInfo;
131import android.content.pm.KeySet;
132import android.content.pm.PackageCleanItem;
133import android.content.pm.PackageInfo;
134import android.content.pm.PackageInfoLite;
135import android.content.pm.PackageInstaller;
136import android.content.pm.PackageManager;
137import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
138import android.content.pm.PackageManagerInternal;
139import android.content.pm.PackageParser;
140import android.content.pm.PackageParser.ActivityIntentInfo;
141import android.content.pm.PackageParser.PackageLite;
142import android.content.pm.PackageParser.PackageParserException;
143import android.content.pm.PackageStats;
144import android.content.pm.PackageUserState;
145import android.content.pm.ParceledListSlice;
146import android.content.pm.PermissionGroupInfo;
147import android.content.pm.PermissionInfo;
148import android.content.pm.ProviderInfo;
149import android.content.pm.ResolveInfo;
150import android.content.pm.ServiceInfo;
151import android.content.pm.Signature;
152import android.content.pm.UserInfo;
153import android.content.pm.VerificationParams;
154import android.content.pm.VerifierDeviceIdentity;
155import android.content.pm.VerifierInfo;
156import android.content.res.Resources;
157import android.graphics.Bitmap;
158import android.hardware.display.DisplayManager;
159import android.net.Uri;
160import android.os.Binder;
161import android.os.Build;
162import android.os.Bundle;
163import android.os.Debug;
164import android.os.Environment;
165import android.os.Environment.UserEnvironment;
166import android.os.FileUtils;
167import android.os.Handler;
168import android.os.IBinder;
169import android.os.Looper;
170import android.os.Message;
171import android.os.Parcel;
172import android.os.ParcelFileDescriptor;
173import android.os.Process;
174import android.os.RemoteCallbackList;
175import android.os.RemoteException;
176import android.os.ResultReceiver;
177import android.os.SELinux;
178import android.os.ServiceManager;
179import android.os.SystemClock;
180import android.os.SystemProperties;
181import android.os.Trace;
182import android.os.UserHandle;
183import android.os.UserManager;
184import android.os.storage.IMountService;
185import android.os.storage.MountServiceInternal;
186import android.os.storage.StorageEventListener;
187import android.os.storage.StorageManager;
188import android.os.storage.VolumeInfo;
189import android.os.storage.VolumeRecord;
190import android.security.KeyStore;
191import android.security.SystemKeyStore;
192import android.system.ErrnoException;
193import android.system.Os;
194import android.text.TextUtils;
195import android.text.format.DateUtils;
196import android.util.ArrayMap;
197import android.util.ArraySet;
198import android.util.AtomicFile;
199import android.util.DisplayMetrics;
200import android.util.EventLog;
201import android.util.ExceptionUtils;
202import android.util.Log;
203import android.util.LogPrinter;
204import android.util.MathUtils;
205import android.util.PrintStreamPrinter;
206import android.util.Slog;
207import android.util.SparseArray;
208import android.util.SparseBooleanArray;
209import android.util.SparseIntArray;
210import android.util.Xml;
211import android.view.Display;
212
213import com.android.internal.R;
214import com.android.internal.annotations.GuardedBy;
215import com.android.internal.app.IMediaContainerService;
216import com.android.internal.app.ResolverActivity;
217import com.android.internal.content.NativeLibraryHelper;
218import com.android.internal.content.PackageHelper;
219import com.android.internal.os.IParcelFileDescriptorFactory;
220import com.android.internal.os.InstallerConnection.InstallerException;
221import com.android.internal.os.SomeArgs;
222import com.android.internal.os.Zygote;
223import com.android.internal.util.ArrayUtils;
224import com.android.internal.util.FastPrintWriter;
225import com.android.internal.util.FastXmlSerializer;
226import com.android.internal.util.IndentingPrintWriter;
227import com.android.internal.util.Preconditions;
228import com.android.server.EventLogTags;
229import com.android.server.FgThread;
230import com.android.server.IntentResolver;
231import com.android.server.LocalServices;
232import com.android.server.ServiceThread;
233import com.android.server.SystemConfig;
234import com.android.server.Watchdog;
235import com.android.server.pm.Installer.StorageFlags;
236import com.android.server.pm.PermissionsState.PermissionState;
237import com.android.server.pm.Settings.DatabaseVersion;
238import com.android.server.pm.Settings.VersionInfo;
239import com.android.server.storage.DeviceStorageMonitorInternal;
240
241import dalvik.system.DexFile;
242import dalvik.system.VMRuntime;
243
244import libcore.io.IoUtils;
245import libcore.util.EmptyArray;
246
247import org.xmlpull.v1.XmlPullParser;
248import org.xmlpull.v1.XmlPullParserException;
249import org.xmlpull.v1.XmlSerializer;
250
251import java.io.BufferedInputStream;
252import java.io.BufferedOutputStream;
253import java.io.BufferedReader;
254import java.io.ByteArrayInputStream;
255import java.io.ByteArrayOutputStream;
256import java.io.File;
257import java.io.FileDescriptor;
258import java.io.FileNotFoundException;
259import java.io.FileOutputStream;
260import java.io.FileReader;
261import java.io.FilenameFilter;
262import java.io.IOException;
263import java.io.InputStream;
264import java.io.PrintWriter;
265import java.nio.charset.StandardCharsets;
266import java.security.MessageDigest;
267import java.security.NoSuchAlgorithmException;
268import java.security.PublicKey;
269import java.security.cert.CertificateEncodingException;
270import java.security.cert.CertificateException;
271import java.text.SimpleDateFormat;
272import java.util.ArrayList;
273import java.util.Arrays;
274import java.util.Collection;
275import java.util.Collections;
276import java.util.Comparator;
277import java.util.Date;
278import java.util.Iterator;
279import java.util.List;
280import java.util.Map;
281import java.util.Objects;
282import java.util.Set;
283import java.util.concurrent.CountDownLatch;
284import java.util.concurrent.TimeUnit;
285import java.util.concurrent.atomic.AtomicBoolean;
286import java.util.concurrent.atomic.AtomicInteger;
287import java.util.concurrent.atomic.AtomicLong;
288
289/**
290 * Keep track of all those .apks everywhere.
291 *
292 * This is very central to the platform's security; please run the unit
293 * tests whenever making modifications here:
294 *
295runtest -c android.content.pm.PackageManagerTests frameworks-core
296 *
297 * {@hide}
298 */
299public class PackageManagerService extends IPackageManager.Stub {
300    static final String TAG = "PackageManager";
301    static final boolean DEBUG_SETTINGS = false;
302    static final boolean DEBUG_PREFERRED = false;
303    static final boolean DEBUG_UPGRADE = false;
304    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
305    private static final boolean DEBUG_BACKUP = false;
306    private static final boolean DEBUG_INSTALL = false;
307    private static final boolean DEBUG_REMOVE = false;
308    private static final boolean DEBUG_BROADCASTS = false;
309    private static final boolean DEBUG_SHOW_INFO = false;
310    private static final boolean DEBUG_PACKAGE_INFO = false;
311    private static final boolean DEBUG_INTENT_MATCHING = false;
312    private static final boolean DEBUG_PACKAGE_SCANNING = false;
313    private static final boolean DEBUG_VERIFY = false;
314    private static final boolean DEBUG_DEXOPT = false;
315    private static final boolean DEBUG_ABI_SELECTION = false;
316    private static final boolean DEBUG_EPHEMERAL = false;
317    private static final boolean DEBUG_TRIAGED_MISSING = false;
318    private static final boolean DEBUG_APP_DATA = 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    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
522
523    public static final class SharedLibraryEntry {
524        public final String path;
525        public final String apk;
526
527        SharedLibraryEntry(String _path, String _apk) {
528            path = _path;
529            apk = _apk;
530        }
531    }
532
533    // Currently known shared libraries.
534    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
535            new ArrayMap<String, SharedLibraryEntry>();
536
537    // All available activities, for your resolving pleasure.
538    final ActivityIntentResolver mActivities =
539            new ActivityIntentResolver();
540
541    // All available receivers, for your resolving pleasure.
542    final ActivityIntentResolver mReceivers =
543            new ActivityIntentResolver();
544
545    // All available services, for your resolving pleasure.
546    final ServiceIntentResolver mServices = new ServiceIntentResolver();
547
548    // All available providers, for your resolving pleasure.
549    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
550
551    // Mapping from provider base names (first directory in content URI codePath)
552    // to the provider information.
553    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
554            new ArrayMap<String, PackageParser.Provider>();
555
556    // Mapping from instrumentation class names to info about them.
557    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
558            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
559
560    // Mapping from permission names to info about them.
561    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
562            new ArrayMap<String, PackageParser.PermissionGroup>();
563
564    // Packages whose data we have transfered into another package, thus
565    // should no longer exist.
566    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
567
568    // Broadcast actions that are only available to the system.
569    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
570
571    /** List of packages waiting for verification. */
572    final SparseArray<PackageVerificationState> mPendingVerification
573            = new SparseArray<PackageVerificationState>();
574
575    /** Set of packages associated with each app op permission. */
576    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
577
578    final PackageInstallerService mInstallerService;
579
580    private final PackageDexOptimizer mPackageDexOptimizer;
581
582    private AtomicInteger mNextMoveId = new AtomicInteger();
583    private final MoveCallbacks mMoveCallbacks;
584
585    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
586
587    // Cache of users who need badging.
588    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
589
590    /** Token for keys in mPendingVerification. */
591    private int mPendingVerificationToken = 0;
592
593    volatile boolean mSystemReady;
594    volatile boolean mSafeMode;
595    volatile boolean mHasSystemUidErrors;
596
597    ApplicationInfo mAndroidApplication;
598    final ActivityInfo mResolveActivity = new ActivityInfo();
599    final ResolveInfo mResolveInfo = new ResolveInfo();
600    ComponentName mResolveComponentName;
601    PackageParser.Package mPlatformPackage;
602    ComponentName mCustomResolverComponentName;
603
604    boolean mResolverReplaced = false;
605
606    private final @Nullable ComponentName mIntentFilterVerifierComponent;
607    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
608
609    private int mIntentFilterVerificationToken = 0;
610
611    /** Component that knows whether or not an ephemeral application exists */
612    final ComponentName mEphemeralResolverComponent;
613    /** The service connection to the ephemeral resolver */
614    final EphemeralResolverConnection mEphemeralResolverConnection;
615
616    /** Component used to install ephemeral applications */
617    final ComponentName mEphemeralInstallerComponent;
618    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
619    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
620
621    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
622            = new SparseArray<IntentFilterVerificationState>();
623
624    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
625            new DefaultPermissionGrantPolicy(this);
626
627    // List of packages names to keep cached, even if they are uninstalled for all users
628    private List<String> mKeepUninstalledPackages;
629
630    private static class IFVerificationParams {
631        PackageParser.Package pkg;
632        boolean replacing;
633        int userId;
634        int verifierUid;
635
636        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
637                int _userId, int _verifierUid) {
638            pkg = _pkg;
639            replacing = _replacing;
640            userId = _userId;
641            replacing = _replacing;
642            verifierUid = _verifierUid;
643        }
644    }
645
646    private interface IntentFilterVerifier<T extends IntentFilter> {
647        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
648                                               T filter, String packageName);
649        void startVerifications(int userId);
650        void receiveVerificationResponse(int verificationId);
651    }
652
653    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
654        private Context mContext;
655        private ComponentName mIntentFilterVerifierComponent;
656        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
657
658        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
659            mContext = context;
660            mIntentFilterVerifierComponent = verifierComponent;
661        }
662
663        private String getDefaultScheme() {
664            return IntentFilter.SCHEME_HTTPS;
665        }
666
667        @Override
668        public void startVerifications(int userId) {
669            // Launch verifications requests
670            int count = mCurrentIntentFilterVerifications.size();
671            for (int n=0; n<count; n++) {
672                int verificationId = mCurrentIntentFilterVerifications.get(n);
673                final IntentFilterVerificationState ivs =
674                        mIntentFilterVerificationStates.get(verificationId);
675
676                String packageName = ivs.getPackageName();
677
678                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
679                final int filterCount = filters.size();
680                ArraySet<String> domainsSet = new ArraySet<>();
681                for (int m=0; m<filterCount; m++) {
682                    PackageParser.ActivityIntentInfo filter = filters.get(m);
683                    domainsSet.addAll(filter.getHostsList());
684                }
685                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
686                synchronized (mPackages) {
687                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
688                            packageName, domainsList) != null) {
689                        scheduleWriteSettingsLocked();
690                    }
691                }
692                sendVerificationRequest(userId, verificationId, ivs);
693            }
694            mCurrentIntentFilterVerifications.clear();
695        }
696
697        private void sendVerificationRequest(int userId, int verificationId,
698                IntentFilterVerificationState ivs) {
699
700            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
701            verificationIntent.putExtra(
702                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
703                    verificationId);
704            verificationIntent.putExtra(
705                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
706                    getDefaultScheme());
707            verificationIntent.putExtra(
708                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
709                    ivs.getHostsString());
710            verificationIntent.putExtra(
711                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
712                    ivs.getPackageName());
713            verificationIntent.setComponent(mIntentFilterVerifierComponent);
714            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
715
716            UserHandle user = new UserHandle(userId);
717            mContext.sendBroadcastAsUser(verificationIntent, user);
718            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
719                    "Sending IntentFilter verification broadcast");
720        }
721
722        public void receiveVerificationResponse(int verificationId) {
723            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
724
725            final boolean verified = ivs.isVerified();
726
727            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
728            final int count = filters.size();
729            if (DEBUG_DOMAIN_VERIFICATION) {
730                Slog.i(TAG, "Received verification response " + verificationId
731                        + " for " + count + " filters, verified=" + verified);
732            }
733            for (int n=0; n<count; n++) {
734                PackageParser.ActivityIntentInfo filter = filters.get(n);
735                filter.setVerified(verified);
736
737                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
738                        + " verified with result:" + verified + " and hosts:"
739                        + ivs.getHostsString());
740            }
741
742            mIntentFilterVerificationStates.remove(verificationId);
743
744            final String packageName = ivs.getPackageName();
745            IntentFilterVerificationInfo ivi = null;
746
747            synchronized (mPackages) {
748                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
749            }
750            if (ivi == null) {
751                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
752                        + verificationId + " packageName:" + packageName);
753                return;
754            }
755            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
756                    "Updating IntentFilterVerificationInfo for package " + packageName
757                            +" verificationId:" + verificationId);
758
759            synchronized (mPackages) {
760                if (verified) {
761                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
762                } else {
763                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
764                }
765                scheduleWriteSettingsLocked();
766
767                final int userId = ivs.getUserId();
768                if (userId != UserHandle.USER_ALL) {
769                    final int userStatus =
770                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
771
772                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
773                    boolean needUpdate = false;
774
775                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
776                    // already been set by the User thru the Disambiguation dialog
777                    switch (userStatus) {
778                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
779                            if (verified) {
780                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
781                            } else {
782                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
783                            }
784                            needUpdate = true;
785                            break;
786
787                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
788                            if (verified) {
789                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
790                                needUpdate = true;
791                            }
792                            break;
793
794                        default:
795                            // Nothing to do
796                    }
797
798                    if (needUpdate) {
799                        mSettings.updateIntentFilterVerificationStatusLPw(
800                                packageName, updatedStatus, userId);
801                        scheduleWritePackageRestrictionsLocked(userId);
802                    }
803                }
804            }
805        }
806
807        @Override
808        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
809                    ActivityIntentInfo filter, String packageName) {
810            if (!hasValidDomains(filter)) {
811                return false;
812            }
813            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
814            if (ivs == null) {
815                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
816                        packageName);
817            }
818            if (DEBUG_DOMAIN_VERIFICATION) {
819                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
820            }
821            ivs.addFilter(filter);
822            return true;
823        }
824
825        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
826                int userId, int verificationId, String packageName) {
827            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
828                    verifierUid, userId, packageName);
829            ivs.setPendingState();
830            synchronized (mPackages) {
831                mIntentFilterVerificationStates.append(verificationId, ivs);
832                mCurrentIntentFilterVerifications.add(verificationId);
833            }
834            return ivs;
835        }
836    }
837
838    private static boolean hasValidDomains(ActivityIntentInfo filter) {
839        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
840                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
841                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
842    }
843
844    // Set of pending broadcasts for aggregating enable/disable of components.
845    static class PendingPackageBroadcasts {
846        // for each user id, a map of <package name -> components within that package>
847        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
848
849        public PendingPackageBroadcasts() {
850            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
851        }
852
853        public ArrayList<String> get(int userId, String packageName) {
854            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
855            return packages.get(packageName);
856        }
857
858        public void put(int userId, String packageName, ArrayList<String> components) {
859            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
860            packages.put(packageName, components);
861        }
862
863        public void remove(int userId, String packageName) {
864            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
865            if (packages != null) {
866                packages.remove(packageName);
867            }
868        }
869
870        public void remove(int userId) {
871            mUidMap.remove(userId);
872        }
873
874        public int userIdCount() {
875            return mUidMap.size();
876        }
877
878        public int userIdAt(int n) {
879            return mUidMap.keyAt(n);
880        }
881
882        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
883            return mUidMap.get(userId);
884        }
885
886        public int size() {
887            // total number of pending broadcast entries across all userIds
888            int num = 0;
889            for (int i = 0; i< mUidMap.size(); i++) {
890                num += mUidMap.valueAt(i).size();
891            }
892            return num;
893        }
894
895        public void clear() {
896            mUidMap.clear();
897        }
898
899        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
900            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
901            if (map == null) {
902                map = new ArrayMap<String, ArrayList<String>>();
903                mUidMap.put(userId, map);
904            }
905            return map;
906        }
907    }
908    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
909
910    // Service Connection to remote media container service to copy
911    // package uri's from external media onto secure containers
912    // or internal storage.
913    private IMediaContainerService mContainerService = null;
914
915    static final int SEND_PENDING_BROADCAST = 1;
916    static final int MCS_BOUND = 3;
917    static final int END_COPY = 4;
918    static final int INIT_COPY = 5;
919    static final int MCS_UNBIND = 6;
920    static final int START_CLEANING_PACKAGE = 7;
921    static final int FIND_INSTALL_LOC = 8;
922    static final int POST_INSTALL = 9;
923    static final int MCS_RECONNECT = 10;
924    static final int MCS_GIVE_UP = 11;
925    static final int UPDATED_MEDIA_STATUS = 12;
926    static final int WRITE_SETTINGS = 13;
927    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
928    static final int PACKAGE_VERIFIED = 15;
929    static final int CHECK_PENDING_VERIFICATION = 16;
930    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
931    static final int INTENT_FILTER_VERIFIED = 18;
932
933    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
934
935    // Delay time in millisecs
936    static final int BROADCAST_DELAY = 10 * 1000;
937
938    static UserManagerService sUserManager;
939
940    // Stores a list of users whose package restrictions file needs to be updated
941    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
942
943    final private DefaultContainerConnection mDefContainerConn =
944            new DefaultContainerConnection();
945    class DefaultContainerConnection implements ServiceConnection {
946        public void onServiceConnected(ComponentName name, IBinder service) {
947            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
948            IMediaContainerService imcs =
949                IMediaContainerService.Stub.asInterface(service);
950            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
951        }
952
953        public void onServiceDisconnected(ComponentName name) {
954            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
955        }
956    }
957
958    // Recordkeeping of restore-after-install operations that are currently in flight
959    // between the Package Manager and the Backup Manager
960    static class PostInstallData {
961        public InstallArgs args;
962        public PackageInstalledInfo res;
963
964        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
965            args = _a;
966            res = _r;
967        }
968    }
969
970    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
971    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
972
973    // XML tags for backup/restore of various bits of state
974    private static final String TAG_PREFERRED_BACKUP = "pa";
975    private static final String TAG_DEFAULT_APPS = "da";
976    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
977
978    final @Nullable String mRequiredVerifierPackage;
979    final @Nullable String mRequiredInstallerPackage;
980
981    private final PackageUsage mPackageUsage = new PackageUsage();
982
983    private class PackageUsage {
984        private static final int WRITE_INTERVAL
985            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
986
987        private final Object mFileLock = new Object();
988        private final AtomicLong mLastWritten = new AtomicLong(0);
989        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
990
991        private boolean mIsHistoricalPackageUsageAvailable = true;
992
993        boolean isHistoricalPackageUsageAvailable() {
994            return mIsHistoricalPackageUsageAvailable;
995        }
996
997        void write(boolean force) {
998            if (force) {
999                writeInternal();
1000                return;
1001            }
1002            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1003                && !DEBUG_DEXOPT) {
1004                return;
1005            }
1006            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1007                new Thread("PackageUsage_DiskWriter") {
1008                    @Override
1009                    public void run() {
1010                        try {
1011                            writeInternal();
1012                        } finally {
1013                            mBackgroundWriteRunning.set(false);
1014                        }
1015                    }
1016                }.start();
1017            }
1018        }
1019
1020        private void writeInternal() {
1021            synchronized (mPackages) {
1022                synchronized (mFileLock) {
1023                    AtomicFile file = getFile();
1024                    FileOutputStream f = null;
1025                    try {
1026                        f = file.startWrite();
1027                        BufferedOutputStream out = new BufferedOutputStream(f);
1028                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1029                        StringBuilder sb = new StringBuilder();
1030                        for (PackageParser.Package pkg : mPackages.values()) {
1031                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1032                                continue;
1033                            }
1034                            sb.setLength(0);
1035                            sb.append(pkg.packageName);
1036                            sb.append(' ');
1037                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1038                            sb.append('\n');
1039                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1040                        }
1041                        out.flush();
1042                        file.finishWrite(f);
1043                    } catch (IOException e) {
1044                        if (f != null) {
1045                            file.failWrite(f);
1046                        }
1047                        Log.e(TAG, "Failed to write package usage times", e);
1048                    }
1049                }
1050            }
1051            mLastWritten.set(SystemClock.elapsedRealtime());
1052        }
1053
1054        void readLP() {
1055            synchronized (mFileLock) {
1056                AtomicFile file = getFile();
1057                BufferedInputStream in = null;
1058                try {
1059                    in = new BufferedInputStream(file.openRead());
1060                    StringBuffer sb = new StringBuffer();
1061                    while (true) {
1062                        String packageName = readToken(in, sb, ' ');
1063                        if (packageName == null) {
1064                            break;
1065                        }
1066                        String timeInMillisString = readToken(in, sb, '\n');
1067                        if (timeInMillisString == null) {
1068                            throw new IOException("Failed to find last usage time for package "
1069                                                  + packageName);
1070                        }
1071                        PackageParser.Package pkg = mPackages.get(packageName);
1072                        if (pkg == null) {
1073                            continue;
1074                        }
1075                        long timeInMillis;
1076                        try {
1077                            timeInMillis = Long.parseLong(timeInMillisString);
1078                        } catch (NumberFormatException e) {
1079                            throw new IOException("Failed to parse " + timeInMillisString
1080                                                  + " as a long.", e);
1081                        }
1082                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1083                    }
1084                } catch (FileNotFoundException expected) {
1085                    mIsHistoricalPackageUsageAvailable = false;
1086                } catch (IOException e) {
1087                    Log.w(TAG, "Failed to read package usage times", e);
1088                } finally {
1089                    IoUtils.closeQuietly(in);
1090                }
1091            }
1092            mLastWritten.set(SystemClock.elapsedRealtime());
1093        }
1094
1095        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1096                throws IOException {
1097            sb.setLength(0);
1098            while (true) {
1099                int ch = in.read();
1100                if (ch == -1) {
1101                    if (sb.length() == 0) {
1102                        return null;
1103                    }
1104                    throw new IOException("Unexpected EOF");
1105                }
1106                if (ch == endOfToken) {
1107                    return sb.toString();
1108                }
1109                sb.append((char)ch);
1110            }
1111        }
1112
1113        private AtomicFile getFile() {
1114            File dataDir = Environment.getDataDirectory();
1115            File systemDir = new File(dataDir, "system");
1116            File fname = new File(systemDir, "package-usage.list");
1117            return new AtomicFile(fname);
1118        }
1119    }
1120
1121    class PackageHandler extends Handler {
1122        private boolean mBound = false;
1123        final ArrayList<HandlerParams> mPendingInstalls =
1124            new ArrayList<HandlerParams>();
1125
1126        private boolean connectToService() {
1127            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1128                    " DefaultContainerService");
1129            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1130            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1131            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1132                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1133                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1134                mBound = true;
1135                return true;
1136            }
1137            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1138            return false;
1139        }
1140
1141        private void disconnectService() {
1142            mContainerService = null;
1143            mBound = false;
1144            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1145            mContext.unbindService(mDefContainerConn);
1146            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1147        }
1148
1149        PackageHandler(Looper looper) {
1150            super(looper);
1151        }
1152
1153        public void handleMessage(Message msg) {
1154            try {
1155                doHandleMessage(msg);
1156            } finally {
1157                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1158            }
1159        }
1160
1161        void doHandleMessage(Message msg) {
1162            switch (msg.what) {
1163                case INIT_COPY: {
1164                    HandlerParams params = (HandlerParams) msg.obj;
1165                    int idx = mPendingInstalls.size();
1166                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1167                    // If a bind was already initiated we dont really
1168                    // need to do anything. The pending install
1169                    // will be processed later on.
1170                    if (!mBound) {
1171                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1172                                System.identityHashCode(mHandler));
1173                        // If this is the only one pending we might
1174                        // have to bind to the service again.
1175                        if (!connectToService()) {
1176                            Slog.e(TAG, "Failed to bind to media container service");
1177                            params.serviceError();
1178                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1179                                    System.identityHashCode(mHandler));
1180                            if (params.traceMethod != null) {
1181                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1182                                        params.traceCookie);
1183                            }
1184                            return;
1185                        } else {
1186                            // Once we bind to the service, the first
1187                            // pending request will be processed.
1188                            mPendingInstalls.add(idx, params);
1189                        }
1190                    } else {
1191                        mPendingInstalls.add(idx, params);
1192                        // Already bound to the service. Just make
1193                        // sure we trigger off processing the first request.
1194                        if (idx == 0) {
1195                            mHandler.sendEmptyMessage(MCS_BOUND);
1196                        }
1197                    }
1198                    break;
1199                }
1200                case MCS_BOUND: {
1201                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1202                    if (msg.obj != null) {
1203                        mContainerService = (IMediaContainerService) msg.obj;
1204                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1205                                System.identityHashCode(mHandler));
1206                    }
1207                    if (mContainerService == null) {
1208                        if (!mBound) {
1209                            // Something seriously wrong since we are not bound and we are not
1210                            // waiting for connection. Bail out.
1211                            Slog.e(TAG, "Cannot bind to media container service");
1212                            for (HandlerParams params : mPendingInstalls) {
1213                                // Indicate service bind error
1214                                params.serviceError();
1215                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1216                                        System.identityHashCode(params));
1217                                if (params.traceMethod != null) {
1218                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1219                                            params.traceMethod, params.traceCookie);
1220                                }
1221                                return;
1222                            }
1223                            mPendingInstalls.clear();
1224                        } else {
1225                            Slog.w(TAG, "Waiting to connect to media container service");
1226                        }
1227                    } else if (mPendingInstalls.size() > 0) {
1228                        HandlerParams params = mPendingInstalls.get(0);
1229                        if (params != null) {
1230                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1231                                    System.identityHashCode(params));
1232                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1233                            if (params.startCopy()) {
1234                                // We are done...  look for more work or to
1235                                // go idle.
1236                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1237                                        "Checking for more work or unbind...");
1238                                // Delete pending install
1239                                if (mPendingInstalls.size() > 0) {
1240                                    mPendingInstalls.remove(0);
1241                                }
1242                                if (mPendingInstalls.size() == 0) {
1243                                    if (mBound) {
1244                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1245                                                "Posting delayed MCS_UNBIND");
1246                                        removeMessages(MCS_UNBIND);
1247                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1248                                        // Unbind after a little delay, to avoid
1249                                        // continual thrashing.
1250                                        sendMessageDelayed(ubmsg, 10000);
1251                                    }
1252                                } else {
1253                                    // There are more pending requests in queue.
1254                                    // Just post MCS_BOUND message to trigger processing
1255                                    // of next pending install.
1256                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1257                                            "Posting MCS_BOUND for next work");
1258                                    mHandler.sendEmptyMessage(MCS_BOUND);
1259                                }
1260                            }
1261                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1262                        }
1263                    } else {
1264                        // Should never happen ideally.
1265                        Slog.w(TAG, "Empty queue");
1266                    }
1267                    break;
1268                }
1269                case MCS_RECONNECT: {
1270                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1271                    if (mPendingInstalls.size() > 0) {
1272                        if (mBound) {
1273                            disconnectService();
1274                        }
1275                        if (!connectToService()) {
1276                            Slog.e(TAG, "Failed to bind to media container service");
1277                            for (HandlerParams params : mPendingInstalls) {
1278                                // Indicate service bind error
1279                                params.serviceError();
1280                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1281                                        System.identityHashCode(params));
1282                            }
1283                            mPendingInstalls.clear();
1284                        }
1285                    }
1286                    break;
1287                }
1288                case MCS_UNBIND: {
1289                    // If there is no actual work left, then time to unbind.
1290                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1291
1292                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1293                        if (mBound) {
1294                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1295
1296                            disconnectService();
1297                        }
1298                    } else if (mPendingInstalls.size() > 0) {
1299                        // There are more pending requests in queue.
1300                        // Just post MCS_BOUND message to trigger processing
1301                        // of next pending install.
1302                        mHandler.sendEmptyMessage(MCS_BOUND);
1303                    }
1304
1305                    break;
1306                }
1307                case MCS_GIVE_UP: {
1308                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1309                    HandlerParams params = mPendingInstalls.remove(0);
1310                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1311                            System.identityHashCode(params));
1312                    break;
1313                }
1314                case SEND_PENDING_BROADCAST: {
1315                    String packages[];
1316                    ArrayList<String> components[];
1317                    int size = 0;
1318                    int uids[];
1319                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1320                    synchronized (mPackages) {
1321                        if (mPendingBroadcasts == null) {
1322                            return;
1323                        }
1324                        size = mPendingBroadcasts.size();
1325                        if (size <= 0) {
1326                            // Nothing to be done. Just return
1327                            return;
1328                        }
1329                        packages = new String[size];
1330                        components = new ArrayList[size];
1331                        uids = new int[size];
1332                        int i = 0;  // filling out the above arrays
1333
1334                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1335                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1336                            Iterator<Map.Entry<String, ArrayList<String>>> it
1337                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1338                                            .entrySet().iterator();
1339                            while (it.hasNext() && i < size) {
1340                                Map.Entry<String, ArrayList<String>> ent = it.next();
1341                                packages[i] = ent.getKey();
1342                                components[i] = ent.getValue();
1343                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1344                                uids[i] = (ps != null)
1345                                        ? UserHandle.getUid(packageUserId, ps.appId)
1346                                        : -1;
1347                                i++;
1348                            }
1349                        }
1350                        size = i;
1351                        mPendingBroadcasts.clear();
1352                    }
1353                    // Send broadcasts
1354                    for (int i = 0; i < size; i++) {
1355                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1356                    }
1357                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1358                    break;
1359                }
1360                case START_CLEANING_PACKAGE: {
1361                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1362                    final String packageName = (String)msg.obj;
1363                    final int userId = msg.arg1;
1364                    final boolean andCode = msg.arg2 != 0;
1365                    synchronized (mPackages) {
1366                        if (userId == UserHandle.USER_ALL) {
1367                            int[] users = sUserManager.getUserIds();
1368                            for (int user : users) {
1369                                mSettings.addPackageToCleanLPw(
1370                                        new PackageCleanItem(user, packageName, andCode));
1371                            }
1372                        } else {
1373                            mSettings.addPackageToCleanLPw(
1374                                    new PackageCleanItem(userId, packageName, andCode));
1375                        }
1376                    }
1377                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1378                    startCleaningPackages();
1379                } break;
1380                case POST_INSTALL: {
1381                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1382
1383                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1384                    mRunningInstalls.delete(msg.arg1);
1385                    boolean deleteOld = false;
1386
1387                    if (data != null) {
1388                        InstallArgs args = data.args;
1389                        PackageInstalledInfo res = data.res;
1390
1391                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1392                            final String packageName = res.pkg.applicationInfo.packageName;
1393                            res.removedInfo.sendBroadcast(false, true, false);
1394                            Bundle extras = new Bundle(1);
1395                            extras.putInt(Intent.EXTRA_UID, res.uid);
1396
1397                            // Now that we successfully installed the package, grant runtime
1398                            // permissions if requested before broadcasting the install.
1399                            if ((args.installFlags
1400                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1401                                    && res.pkg.applicationInfo.targetSdkVersion
1402                                            >= Build.VERSION_CODES.M) {
1403                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1404                                        args.installGrantPermissions);
1405                            }
1406
1407                            synchronized (mPackages) {
1408                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1409                            }
1410
1411                            // Determine the set of users who are adding this
1412                            // package for the first time vs. those who are seeing
1413                            // an update.
1414                            int[] firstUsers;
1415                            int[] updateUsers = new int[0];
1416                            if (res.origUsers == null || res.origUsers.length == 0) {
1417                                firstUsers = res.newUsers;
1418                            } else {
1419                                firstUsers = new int[0];
1420                                for (int i=0; i<res.newUsers.length; i++) {
1421                                    int user = res.newUsers[i];
1422                                    boolean isNew = true;
1423                                    for (int j=0; j<res.origUsers.length; j++) {
1424                                        if (res.origUsers[j] == user) {
1425                                            isNew = false;
1426                                            break;
1427                                        }
1428                                    }
1429                                    if (isNew) {
1430                                        int[] newFirst = new int[firstUsers.length+1];
1431                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1432                                                firstUsers.length);
1433                                        newFirst[firstUsers.length] = user;
1434                                        firstUsers = newFirst;
1435                                    } else {
1436                                        int[] newUpdate = new int[updateUsers.length+1];
1437                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1438                                                updateUsers.length);
1439                                        newUpdate[updateUsers.length] = user;
1440                                        updateUsers = newUpdate;
1441                                    }
1442                                }
1443                            }
1444                            // don't broadcast for ephemeral installs/updates
1445                            final boolean isEphemeral = isEphemeral(res.pkg);
1446                            if (!isEphemeral) {
1447                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1448                                        extras, 0 /*flags*/, null /*targetPackage*/,
1449                                        null /*finishedReceiver*/, firstUsers);
1450                            }
1451                            final boolean update = res.removedInfo.removedPackage != null;
1452                            if (update) {
1453                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1454                            }
1455                            if (!isEphemeral) {
1456                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1457                                        extras, 0 /*flags*/, null /*targetPackage*/,
1458                                        null /*finishedReceiver*/, updateUsers);
1459                            }
1460                            if (update) {
1461                                if (!isEphemeral) {
1462                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1463                                            packageName, extras, 0 /*flags*/,
1464                                            null /*targetPackage*/, null /*finishedReceiver*/,
1465                                            updateUsers);
1466                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1467                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1468                                            packageName /*targetPackage*/,
1469                                            null /*finishedReceiver*/, updateUsers);
1470                                }
1471
1472                                // treat asec-hosted packages like removable media on upgrade
1473                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1474                                    if (DEBUG_INSTALL) {
1475                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1476                                                + " is ASEC-hosted -> AVAILABLE");
1477                                    }
1478                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1479                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1480                                    pkgList.add(packageName);
1481                                    sendResourcesChangedBroadcast(true, true,
1482                                            pkgList,uidArray, null);
1483                                }
1484                            }
1485                            if (res.removedInfo.args != null) {
1486                                // Remove the replaced package's older resources safely now
1487                                deleteOld = true;
1488                            }
1489
1490                            // If this app is a browser and it's newly-installed for some
1491                            // users, clear any default-browser state in those users
1492                            if (firstUsers.length > 0) {
1493                                // the app's nature doesn't depend on the user, so we can just
1494                                // check its browser nature in any user and generalize.
1495                                if (packageIsBrowser(packageName, firstUsers[0])) {
1496                                    synchronized (mPackages) {
1497                                        for (int userId : firstUsers) {
1498                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1499                                        }
1500                                    }
1501                                }
1502                            }
1503                            // Log current value of "unknown sources" setting
1504                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1505                                getUnknownSourcesSettings());
1506                        }
1507                        // Force a gc to clear up things
1508                        Runtime.getRuntime().gc();
1509                        // We delete after a gc for applications  on sdcard.
1510                        if (deleteOld) {
1511                            synchronized (mInstallLock) {
1512                                res.removedInfo.args.doPostDeleteLI(true);
1513                            }
1514                        }
1515                        if (args.observer != null) {
1516                            try {
1517                                Bundle extras = extrasForInstallResult(res);
1518                                args.observer.onPackageInstalled(res.name, res.returnCode,
1519                                        res.returnMsg, extras);
1520                            } catch (RemoteException e) {
1521                                Slog.i(TAG, "Observer no longer exists.");
1522                            }
1523                        }
1524                        if (args.traceMethod != null) {
1525                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1526                                    args.traceCookie);
1527                        }
1528                        return;
1529                    } else {
1530                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1531                    }
1532
1533                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1534                } break;
1535                case UPDATED_MEDIA_STATUS: {
1536                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1537                    boolean reportStatus = msg.arg1 == 1;
1538                    boolean doGc = msg.arg2 == 1;
1539                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1540                    if (doGc) {
1541                        // Force a gc to clear up stale containers.
1542                        Runtime.getRuntime().gc();
1543                    }
1544                    if (msg.obj != null) {
1545                        @SuppressWarnings("unchecked")
1546                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1547                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1548                        // Unload containers
1549                        unloadAllContainers(args);
1550                    }
1551                    if (reportStatus) {
1552                        try {
1553                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1554                            PackageHelper.getMountService().finishMediaUpdate();
1555                        } catch (RemoteException e) {
1556                            Log.e(TAG, "MountService not running?");
1557                        }
1558                    }
1559                } break;
1560                case WRITE_SETTINGS: {
1561                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1562                    synchronized (mPackages) {
1563                        removeMessages(WRITE_SETTINGS);
1564                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1565                        mSettings.writeLPr();
1566                        mDirtyUsers.clear();
1567                    }
1568                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1569                } break;
1570                case WRITE_PACKAGE_RESTRICTIONS: {
1571                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1572                    synchronized (mPackages) {
1573                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1574                        for (int userId : mDirtyUsers) {
1575                            mSettings.writePackageRestrictionsLPr(userId);
1576                        }
1577                        mDirtyUsers.clear();
1578                    }
1579                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1580                } break;
1581                case CHECK_PENDING_VERIFICATION: {
1582                    final int verificationId = msg.arg1;
1583                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1584
1585                    if ((state != null) && !state.timeoutExtended()) {
1586                        final InstallArgs args = state.getInstallArgs();
1587                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1588
1589                        Slog.i(TAG, "Verification timed out for " + originUri);
1590                        mPendingVerification.remove(verificationId);
1591
1592                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1593
1594                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1595                            Slog.i(TAG, "Continuing with installation of " + originUri);
1596                            state.setVerifierResponse(Binder.getCallingUid(),
1597                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1598                            broadcastPackageVerified(verificationId, originUri,
1599                                    PackageManager.VERIFICATION_ALLOW,
1600                                    state.getInstallArgs().getUser());
1601                            try {
1602                                ret = args.copyApk(mContainerService, true);
1603                            } catch (RemoteException e) {
1604                                Slog.e(TAG, "Could not contact the ContainerService");
1605                            }
1606                        } else {
1607                            broadcastPackageVerified(verificationId, originUri,
1608                                    PackageManager.VERIFICATION_REJECT,
1609                                    state.getInstallArgs().getUser());
1610                        }
1611
1612                        Trace.asyncTraceEnd(
1613                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1614
1615                        processPendingInstall(args, ret);
1616                        mHandler.sendEmptyMessage(MCS_UNBIND);
1617                    }
1618                    break;
1619                }
1620                case PACKAGE_VERIFIED: {
1621                    final int verificationId = msg.arg1;
1622
1623                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1624                    if (state == null) {
1625                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1626                        break;
1627                    }
1628
1629                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1630
1631                    state.setVerifierResponse(response.callerUid, response.code);
1632
1633                    if (state.isVerificationComplete()) {
1634                        mPendingVerification.remove(verificationId);
1635
1636                        final InstallArgs args = state.getInstallArgs();
1637                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1638
1639                        int ret;
1640                        if (state.isInstallAllowed()) {
1641                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1642                            broadcastPackageVerified(verificationId, originUri,
1643                                    response.code, state.getInstallArgs().getUser());
1644                            try {
1645                                ret = args.copyApk(mContainerService, true);
1646                            } catch (RemoteException e) {
1647                                Slog.e(TAG, "Could not contact the ContainerService");
1648                            }
1649                        } else {
1650                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1651                        }
1652
1653                        Trace.asyncTraceEnd(
1654                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1655
1656                        processPendingInstall(args, ret);
1657                        mHandler.sendEmptyMessage(MCS_UNBIND);
1658                    }
1659
1660                    break;
1661                }
1662                case START_INTENT_FILTER_VERIFICATIONS: {
1663                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1664                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1665                            params.replacing, params.pkg);
1666                    break;
1667                }
1668                case INTENT_FILTER_VERIFIED: {
1669                    final int verificationId = msg.arg1;
1670
1671                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1672                            verificationId);
1673                    if (state == null) {
1674                        Slog.w(TAG, "Invalid IntentFilter verification token "
1675                                + verificationId + " received");
1676                        break;
1677                    }
1678
1679                    final int userId = state.getUserId();
1680
1681                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1682                            "Processing IntentFilter verification with token:"
1683                            + verificationId + " and userId:" + userId);
1684
1685                    final IntentFilterVerificationResponse response =
1686                            (IntentFilterVerificationResponse) msg.obj;
1687
1688                    state.setVerifierResponse(response.callerUid, response.code);
1689
1690                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1691                            "IntentFilter verification with token:" + verificationId
1692                            + " and userId:" + userId
1693                            + " is settings verifier response with response code:"
1694                            + response.code);
1695
1696                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1697                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1698                                + response.getFailedDomainsString());
1699                    }
1700
1701                    if (state.isVerificationComplete()) {
1702                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1703                    } else {
1704                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1705                                "IntentFilter verification with token:" + verificationId
1706                                + " was not said to be complete");
1707                    }
1708
1709                    break;
1710                }
1711            }
1712        }
1713    }
1714
1715    private StorageEventListener mStorageListener = new StorageEventListener() {
1716        @Override
1717        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1718            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1719                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1720                    final String volumeUuid = vol.getFsUuid();
1721
1722                    // Clean up any users or apps that were removed or recreated
1723                    // while this volume was missing
1724                    reconcileUsers(volumeUuid);
1725                    reconcileApps(volumeUuid);
1726
1727                    // Clean up any install sessions that expired or were
1728                    // cancelled while this volume was missing
1729                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1730
1731                    loadPrivatePackages(vol);
1732
1733                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1734                    unloadPrivatePackages(vol);
1735                }
1736            }
1737
1738            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1739                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1740                    updateExternalMediaStatus(true, false);
1741                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1742                    updateExternalMediaStatus(false, false);
1743                }
1744            }
1745        }
1746
1747        @Override
1748        public void onVolumeForgotten(String fsUuid) {
1749            if (TextUtils.isEmpty(fsUuid)) {
1750                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1751                return;
1752            }
1753
1754            // Remove any apps installed on the forgotten volume
1755            synchronized (mPackages) {
1756                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1757                for (PackageSetting ps : packages) {
1758                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1759                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1760                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1761                }
1762
1763                mSettings.onVolumeForgotten(fsUuid);
1764                mSettings.writeLPr();
1765            }
1766        }
1767    };
1768
1769    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1770            String[] grantedPermissions) {
1771        if (userId >= UserHandle.USER_SYSTEM) {
1772            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1773        } else if (userId == UserHandle.USER_ALL) {
1774            final int[] userIds;
1775            synchronized (mPackages) {
1776                userIds = UserManagerService.getInstance().getUserIds();
1777            }
1778            for (int someUserId : userIds) {
1779                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1780            }
1781        }
1782
1783        // We could have touched GID membership, so flush out packages.list
1784        synchronized (mPackages) {
1785            mSettings.writePackageListLPr();
1786        }
1787    }
1788
1789    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1790            String[] grantedPermissions) {
1791        SettingBase sb = (SettingBase) pkg.mExtras;
1792        if (sb == null) {
1793            return;
1794        }
1795
1796        PermissionsState permissionsState = sb.getPermissionsState();
1797
1798        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1799                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1800
1801        synchronized (mPackages) {
1802            for (String permission : pkg.requestedPermissions) {
1803                BasePermission bp = mSettings.mPermissions.get(permission);
1804                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1805                        && (grantedPermissions == null
1806                               || ArrayUtils.contains(grantedPermissions, permission))) {
1807                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1808                    // Installer cannot change immutable permissions.
1809                    if ((flags & immutableFlags) == 0) {
1810                        grantRuntimePermission(pkg.packageName, permission, userId);
1811                    }
1812                }
1813            }
1814        }
1815    }
1816
1817    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1818        Bundle extras = null;
1819        switch (res.returnCode) {
1820            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1821                extras = new Bundle();
1822                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1823                        res.origPermission);
1824                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1825                        res.origPackage);
1826                break;
1827            }
1828            case PackageManager.INSTALL_SUCCEEDED: {
1829                extras = new Bundle();
1830                extras.putBoolean(Intent.EXTRA_REPLACING,
1831                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1832                break;
1833            }
1834        }
1835        return extras;
1836    }
1837
1838    void scheduleWriteSettingsLocked() {
1839        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1840            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1841        }
1842    }
1843
1844    void scheduleWritePackageRestrictionsLocked(int userId) {
1845        if (!sUserManager.exists(userId)) return;
1846        mDirtyUsers.add(userId);
1847        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1848            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1849        }
1850    }
1851
1852    public static PackageManagerService main(Context context, Installer installer,
1853            boolean factoryTest, boolean onlyCore) {
1854        PackageManagerService m = new PackageManagerService(context, installer,
1855                factoryTest, onlyCore);
1856        m.enableSystemUserPackages();
1857        ServiceManager.addService("package", m);
1858        return m;
1859    }
1860
1861    private void enableSystemUserPackages() {
1862        if (!UserManager.isSplitSystemUser()) {
1863            return;
1864        }
1865        // For system user, enable apps based on the following conditions:
1866        // - app is whitelisted or belong to one of these groups:
1867        //   -- system app which has no launcher icons
1868        //   -- system app which has INTERACT_ACROSS_USERS permission
1869        //   -- system IME app
1870        // - app is not in the blacklist
1871        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1872        Set<String> enableApps = new ArraySet<>();
1873        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1874                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1875                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1876        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1877        enableApps.addAll(wlApps);
1878        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1879                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1880        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1881        enableApps.removeAll(blApps);
1882        Log.i(TAG, "Applications installed for system user: " + enableApps);
1883        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1884                UserHandle.SYSTEM);
1885        final int allAppsSize = allAps.size();
1886        synchronized (mPackages) {
1887            for (int i = 0; i < allAppsSize; i++) {
1888                String pName = allAps.get(i);
1889                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1890                // Should not happen, but we shouldn't be failing if it does
1891                if (pkgSetting == null) {
1892                    continue;
1893                }
1894                boolean install = enableApps.contains(pName);
1895                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1896                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1897                            + " for system user");
1898                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1899                }
1900            }
1901        }
1902    }
1903
1904    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1905        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1906                Context.DISPLAY_SERVICE);
1907        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1908    }
1909
1910    public PackageManagerService(Context context, Installer installer,
1911            boolean factoryTest, boolean onlyCore) {
1912        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1913                SystemClock.uptimeMillis());
1914
1915        if (mSdkVersion <= 0) {
1916            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1917        }
1918
1919        mContext = context;
1920        mFactoryTest = factoryTest;
1921        mOnlyCore = onlyCore;
1922        mMetrics = new DisplayMetrics();
1923        mSettings = new Settings(mPackages);
1924        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1925                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1926        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1927                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1928        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1929                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1930        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1931                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1932        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1933                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1934        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1935                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1936
1937        String separateProcesses = SystemProperties.get("debug.separate_processes");
1938        if (separateProcesses != null && separateProcesses.length() > 0) {
1939            if ("*".equals(separateProcesses)) {
1940                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1941                mSeparateProcesses = null;
1942                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1943            } else {
1944                mDefParseFlags = 0;
1945                mSeparateProcesses = separateProcesses.split(",");
1946                Slog.w(TAG, "Running with debug.separate_processes: "
1947                        + separateProcesses);
1948            }
1949        } else {
1950            mDefParseFlags = 0;
1951            mSeparateProcesses = null;
1952        }
1953
1954        mInstaller = installer;
1955        mPackageDexOptimizer = new PackageDexOptimizer(this);
1956        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1957
1958        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1959                FgThread.get().getLooper());
1960
1961        getDefaultDisplayMetrics(context, mMetrics);
1962
1963        SystemConfig systemConfig = SystemConfig.getInstance();
1964        mGlobalGids = systemConfig.getGlobalGids();
1965        mSystemPermissions = systemConfig.getSystemPermissions();
1966        mAvailableFeatures = systemConfig.getAvailableFeatures();
1967
1968        synchronized (mInstallLock) {
1969        // writer
1970        synchronized (mPackages) {
1971            mHandlerThread = new ServiceThread(TAG,
1972                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1973            mHandlerThread.start();
1974            mHandler = new PackageHandler(mHandlerThread.getLooper());
1975            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1976
1977            File dataDir = Environment.getDataDirectory();
1978            mAppInstallDir = new File(dataDir, "app");
1979            mAppLib32InstallDir = new File(dataDir, "app-lib");
1980            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1981            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1982            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1983
1984            sUserManager = new UserManagerService(context, this, mPackages);
1985
1986            // Propagate permission configuration in to package manager.
1987            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1988                    = systemConfig.getPermissions();
1989            for (int i=0; i<permConfig.size(); i++) {
1990                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1991                BasePermission bp = mSettings.mPermissions.get(perm.name);
1992                if (bp == null) {
1993                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1994                    mSettings.mPermissions.put(perm.name, bp);
1995                }
1996                if (perm.gids != null) {
1997                    bp.setGids(perm.gids, perm.perUser);
1998                }
1999            }
2000
2001            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2002            for (int i=0; i<libConfig.size(); i++) {
2003                mSharedLibraries.put(libConfig.keyAt(i),
2004                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2005            }
2006
2007            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2008
2009            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2010
2011            String customResolverActivity = Resources.getSystem().getString(
2012                    R.string.config_customResolverActivity);
2013            if (TextUtils.isEmpty(customResolverActivity)) {
2014                customResolverActivity = null;
2015            } else {
2016                mCustomResolverComponentName = ComponentName.unflattenFromString(
2017                        customResolverActivity);
2018            }
2019
2020            long startTime = SystemClock.uptimeMillis();
2021
2022            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2023                    startTime);
2024
2025            // Set flag to monitor and not change apk file paths when
2026            // scanning install directories.
2027            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2028
2029            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2030            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2031
2032            if (bootClassPath == null) {
2033                Slog.w(TAG, "No BOOTCLASSPATH found!");
2034            }
2035
2036            if (systemServerClassPath == null) {
2037                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2038            }
2039
2040            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2041            final String[] dexCodeInstructionSets =
2042                    getDexCodeInstructionSets(
2043                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2044
2045            /**
2046             * Ensure all external libraries have had dexopt run on them.
2047             */
2048            if (mSharedLibraries.size() > 0) {
2049                // NOTE: For now, we're compiling these system "shared libraries"
2050                // (and framework jars) into all available architectures. It's possible
2051                // to compile them only when we come across an app that uses them (there's
2052                // already logic for that in scanPackageLI) but that adds some complexity.
2053                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2054                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2055                        final String lib = libEntry.path;
2056                        if (lib == null) {
2057                            continue;
2058                        }
2059
2060                        try {
2061                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2062                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2063                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2064                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2065                            }
2066                        } catch (FileNotFoundException e) {
2067                            Slog.w(TAG, "Library not found: " + lib);
2068                        } catch (IOException | InstallerException e) {
2069                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2070                                    + e.getMessage());
2071                        }
2072                    }
2073                }
2074            }
2075
2076            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2077
2078            final VersionInfo ver = mSettings.getInternalVersion();
2079            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2080            // when upgrading from pre-M, promote system app permissions from install to runtime
2081            mPromoteSystemApps =
2082                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2083
2084            // save off the names of pre-existing system packages prior to scanning; we don't
2085            // want to automatically grant runtime permissions for new system apps
2086            if (mPromoteSystemApps) {
2087                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2088                while (pkgSettingIter.hasNext()) {
2089                    PackageSetting ps = pkgSettingIter.next();
2090                    if (isSystemApp(ps)) {
2091                        mExistingSystemPackages.add(ps.name);
2092                    }
2093                }
2094            }
2095
2096            // Collect vendor overlay packages.
2097            // (Do this before scanning any apps.)
2098            // For security and version matching reason, only consider
2099            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2100            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2101            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2102                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2103
2104            // Find base frameworks (resource packages without code).
2105            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2106                    | PackageParser.PARSE_IS_SYSTEM_DIR
2107                    | PackageParser.PARSE_IS_PRIVILEGED,
2108                    scanFlags | SCAN_NO_DEX, 0);
2109
2110            // Collected privileged system packages.
2111            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2112            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2113                    | PackageParser.PARSE_IS_SYSTEM_DIR
2114                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2115
2116            // Collect ordinary system packages.
2117            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2118            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2119                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2120
2121            // Collect all vendor packages.
2122            File vendorAppDir = new File("/vendor/app");
2123            try {
2124                vendorAppDir = vendorAppDir.getCanonicalFile();
2125            } catch (IOException e) {
2126                // failed to look up canonical path, continue with original one
2127            }
2128            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2129                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2130
2131            // Collect all OEM packages.
2132            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2133            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2134                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2135
2136            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2137            try {
2138                mInstaller.moveFiles();
2139            } catch (InstallerException e) {
2140                logCriticalInfo(Log.WARN, "Update commands failed: " + e);
2141            }
2142
2143            // Prune any system packages that no longer exist.
2144            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2145            if (!mOnlyCore) {
2146                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2147                while (psit.hasNext()) {
2148                    PackageSetting ps = psit.next();
2149
2150                    /*
2151                     * If this is not a system app, it can't be a
2152                     * disable system app.
2153                     */
2154                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2155                        continue;
2156                    }
2157
2158                    /*
2159                     * If the package is scanned, it's not erased.
2160                     */
2161                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2162                    if (scannedPkg != null) {
2163                        /*
2164                         * If the system app is both scanned and in the
2165                         * disabled packages list, then it must have been
2166                         * added via OTA. Remove it from the currently
2167                         * scanned package so the previously user-installed
2168                         * application can be scanned.
2169                         */
2170                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2171                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2172                                    + ps.name + "; removing system app.  Last known codePath="
2173                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2174                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2175                                    + scannedPkg.mVersionCode);
2176                            removePackageLI(ps, true);
2177                            mExpectingBetter.put(ps.name, ps.codePath);
2178                        }
2179
2180                        continue;
2181                    }
2182
2183                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2184                        psit.remove();
2185                        logCriticalInfo(Log.WARN, "System package " + ps.name
2186                                + " no longer exists; wiping its data");
2187                        removeDataDirsLI(null, ps.name);
2188                    } else {
2189                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2190                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2191                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2192                        }
2193                    }
2194                }
2195            }
2196
2197            //look for any incomplete package installations
2198            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2199            //clean up list
2200            for(int i = 0; i < deletePkgsList.size(); i++) {
2201                //clean up here
2202                cleanupInstallFailedPackage(deletePkgsList.get(i));
2203            }
2204            //delete tmp files
2205            deleteTempPackageFiles();
2206
2207            // Remove any shared userIDs that have no associated packages
2208            mSettings.pruneSharedUsersLPw();
2209
2210            if (!mOnlyCore) {
2211                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2212                        SystemClock.uptimeMillis());
2213                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2214
2215                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2216                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2217
2218                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2219                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2220
2221                /**
2222                 * Remove disable package settings for any updated system
2223                 * apps that were removed via an OTA. If they're not a
2224                 * previously-updated app, remove them completely.
2225                 * Otherwise, just revoke their system-level permissions.
2226                 */
2227                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2228                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2229                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2230
2231                    String msg;
2232                    if (deletedPkg == null) {
2233                        msg = "Updated system package " + deletedAppName
2234                                + " no longer exists; wiping its data";
2235                        removeDataDirsLI(null, deletedAppName);
2236                    } else {
2237                        msg = "Updated system app + " + deletedAppName
2238                                + " no longer present; removing system privileges for "
2239                                + deletedAppName;
2240
2241                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2242
2243                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2244                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2245                    }
2246                    logCriticalInfo(Log.WARN, msg);
2247                }
2248
2249                /**
2250                 * Make sure all system apps that we expected to appear on
2251                 * the userdata partition actually showed up. If they never
2252                 * appeared, crawl back and revive the system version.
2253                 */
2254                for (int i = 0; i < mExpectingBetter.size(); i++) {
2255                    final String packageName = mExpectingBetter.keyAt(i);
2256                    if (!mPackages.containsKey(packageName)) {
2257                        final File scanFile = mExpectingBetter.valueAt(i);
2258
2259                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2260                                + " but never showed up; reverting to system");
2261
2262                        final int reparseFlags;
2263                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2264                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2265                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2266                                    | PackageParser.PARSE_IS_PRIVILEGED;
2267                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2268                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2269                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2270                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2271                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2272                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2273                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2274                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2275                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2276                        } else {
2277                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2278                            continue;
2279                        }
2280
2281                        mSettings.enableSystemPackageLPw(packageName);
2282
2283                        try {
2284                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2285                        } catch (PackageManagerException e) {
2286                            Slog.e(TAG, "Failed to parse original system package: "
2287                                    + e.getMessage());
2288                        }
2289                    }
2290                }
2291            }
2292            mExpectingBetter.clear();
2293
2294            // Now that we know all of the shared libraries, update all clients to have
2295            // the correct library paths.
2296            updateAllSharedLibrariesLPw();
2297
2298            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2299                // NOTE: We ignore potential failures here during a system scan (like
2300                // the rest of the commands above) because there's precious little we
2301                // can do about it. A settings error is reported, though.
2302                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2303                        false /* boot complete */);
2304            }
2305
2306            // Now that we know all the packages we are keeping,
2307            // read and update their last usage times.
2308            mPackageUsage.readLP();
2309
2310            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2311                    SystemClock.uptimeMillis());
2312            Slog.i(TAG, "Time to scan packages: "
2313                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2314                    + " seconds");
2315
2316            // If the platform SDK has changed since the last time we booted,
2317            // we need to re-grant app permission to catch any new ones that
2318            // appear.  This is really a hack, and means that apps can in some
2319            // cases get permissions that the user didn't initially explicitly
2320            // allow...  it would be nice to have some better way to handle
2321            // this situation.
2322            int updateFlags = UPDATE_PERMISSIONS_ALL;
2323            if (ver.sdkVersion != mSdkVersion) {
2324                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2325                        + mSdkVersion + "; regranting permissions for internal storage");
2326                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2327            }
2328            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2329            ver.sdkVersion = mSdkVersion;
2330
2331            // If this is the first boot or an update from pre-M, and it is a normal
2332            // boot, then we need to initialize the default preferred apps across
2333            // all defined users.
2334            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2335                for (UserInfo user : sUserManager.getUsers(true)) {
2336                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2337                    applyFactoryDefaultBrowserLPw(user.id);
2338                    primeDomainVerificationsLPw(user.id);
2339                }
2340            }
2341
2342            // Prepare storage for system user really early during boot,
2343            // since core system apps like SettingsProvider and SystemUI
2344            // can't wait for user to start
2345            final int flags;
2346            if (StorageManager.isFileBasedEncryptionEnabled()) {
2347                flags = Installer.FLAG_DE_STORAGE;
2348            } else {
2349                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
2350            }
2351            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, flags);
2352
2353            // If this is first boot after an OTA, and a normal boot, then
2354            // we need to clear code cache directories.
2355            if (mIsUpgrade && !onlyCore) {
2356                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2357                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2358                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2359                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2360                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2361                    }
2362                }
2363                ver.fingerprint = Build.FINGERPRINT;
2364            }
2365
2366            checkDefaultBrowser();
2367
2368            // clear only after permissions and other defaults have been updated
2369            mExistingSystemPackages.clear();
2370            mPromoteSystemApps = false;
2371
2372            // All the changes are done during package scanning.
2373            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2374
2375            // can downgrade to reader
2376            mSettings.writeLPr();
2377
2378            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2379                    SystemClock.uptimeMillis());
2380
2381            if (!mOnlyCore) {
2382                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2383                mRequiredInstallerPackage = getRequiredInstallerLPr();
2384                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2385                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2386                        mIntentFilterVerifierComponent);
2387            } else {
2388                mRequiredVerifierPackage = null;
2389                mRequiredInstallerPackage = null;
2390                mIntentFilterVerifierComponent = null;
2391                mIntentFilterVerifier = null;
2392            }
2393
2394            mInstallerService = new PackageInstallerService(context, this);
2395
2396            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2397            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2398            // both the installer and resolver must be present to enable ephemeral
2399            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2400                if (DEBUG_EPHEMERAL) {
2401                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2402                            + " installer:" + ephemeralInstallerComponent);
2403                }
2404                mEphemeralResolverComponent = ephemeralResolverComponent;
2405                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2406                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2407                mEphemeralResolverConnection =
2408                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2409            } else {
2410                if (DEBUG_EPHEMERAL) {
2411                    final String missingComponent =
2412                            (ephemeralResolverComponent == null)
2413                            ? (ephemeralInstallerComponent == null)
2414                                    ? "resolver and installer"
2415                                    : "resolver"
2416                            : "installer";
2417                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2418                }
2419                mEphemeralResolverComponent = null;
2420                mEphemeralInstallerComponent = null;
2421                mEphemeralResolverConnection = null;
2422            }
2423
2424            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2425        } // synchronized (mPackages)
2426        } // synchronized (mInstallLock)
2427
2428        // Now after opening every single application zip, make sure they
2429        // are all flushed.  Not really needed, but keeps things nice and
2430        // tidy.
2431        Runtime.getRuntime().gc();
2432
2433        // The initial scanning above does many calls into installd while
2434        // holding the mPackages lock, but we're mostly interested in yelling
2435        // once we have a booted system.
2436        mInstaller.setWarnIfHeld(mPackages);
2437
2438        // Expose private service for system components to use.
2439        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2440    }
2441
2442    @Override
2443    public boolean isFirstBoot() {
2444        return !mRestoredSettings;
2445    }
2446
2447    @Override
2448    public boolean isOnlyCoreApps() {
2449        return mOnlyCore;
2450    }
2451
2452    @Override
2453    public boolean isUpgrade() {
2454        return mIsUpgrade;
2455    }
2456
2457    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2458        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2459
2460        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2461                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2462        if (matches.size() == 1) {
2463            return matches.get(0).getComponentInfo().packageName;
2464        } else {
2465            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2466            return null;
2467        }
2468    }
2469
2470    private @NonNull String getRequiredInstallerLPr() {
2471        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2472        intent.addCategory(Intent.CATEGORY_DEFAULT);
2473        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2474
2475        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2476                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2477        if (matches.size() == 1) {
2478            return matches.get(0).getComponentInfo().packageName;
2479        } else {
2480            throw new RuntimeException("There must be exactly one installer; found " + matches);
2481        }
2482    }
2483
2484    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2485        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2486
2487        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2488                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2489        ResolveInfo best = null;
2490        final int N = matches.size();
2491        for (int i = 0; i < N; i++) {
2492            final ResolveInfo cur = matches.get(i);
2493            final String packageName = cur.getComponentInfo().packageName;
2494            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2495                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2496                continue;
2497            }
2498
2499            if (best == null || cur.priority > best.priority) {
2500                best = cur;
2501            }
2502        }
2503
2504        if (best != null) {
2505            return best.getComponentInfo().getComponentName();
2506        } else {
2507            throw new RuntimeException("There must be at least one intent filter verifier");
2508        }
2509    }
2510
2511    private @Nullable ComponentName getEphemeralResolverLPr() {
2512        final String[] packageArray =
2513                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2514        if (packageArray.length == 0) {
2515            if (DEBUG_EPHEMERAL) {
2516                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2517            }
2518            return null;
2519        }
2520
2521        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2522        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2523                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2524
2525        final int N = resolvers.size();
2526        if (N == 0) {
2527            if (DEBUG_EPHEMERAL) {
2528                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2529            }
2530            return null;
2531        }
2532
2533        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2534        for (int i = 0; i < N; i++) {
2535            final ResolveInfo info = resolvers.get(i);
2536
2537            if (info.serviceInfo == null) {
2538                continue;
2539            }
2540
2541            final String packageName = info.serviceInfo.packageName;
2542            if (!possiblePackages.contains(packageName)) {
2543                if (DEBUG_EPHEMERAL) {
2544                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2545                            + " pkg: " + packageName + ", info:" + info);
2546                }
2547                continue;
2548            }
2549
2550            if (DEBUG_EPHEMERAL) {
2551                Slog.v(TAG, "Ephemeral resolver found;"
2552                        + " pkg: " + packageName + ", info:" + info);
2553            }
2554            return new ComponentName(packageName, info.serviceInfo.name);
2555        }
2556        if (DEBUG_EPHEMERAL) {
2557            Slog.v(TAG, "Ephemeral resolver NOT found");
2558        }
2559        return null;
2560    }
2561
2562    private @Nullable ComponentName getEphemeralInstallerLPr() {
2563        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2564        intent.addCategory(Intent.CATEGORY_DEFAULT);
2565        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2566
2567        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2568                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2569        if (matches.size() == 0) {
2570            return null;
2571        } else if (matches.size() == 1) {
2572            return matches.get(0).getComponentInfo().getComponentName();
2573        } else {
2574            throw new RuntimeException(
2575                    "There must be at most one ephemeral installer; found " + matches);
2576        }
2577    }
2578
2579    private void primeDomainVerificationsLPw(int userId) {
2580        if (DEBUG_DOMAIN_VERIFICATION) {
2581            Slog.d(TAG, "Priming domain verifications in user " + userId);
2582        }
2583
2584        SystemConfig systemConfig = SystemConfig.getInstance();
2585        ArraySet<String> packages = systemConfig.getLinkedApps();
2586        ArraySet<String> domains = new ArraySet<String>();
2587
2588        for (String packageName : packages) {
2589            PackageParser.Package pkg = mPackages.get(packageName);
2590            if (pkg != null) {
2591                if (!pkg.isSystemApp()) {
2592                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2593                    continue;
2594                }
2595
2596                domains.clear();
2597                for (PackageParser.Activity a : pkg.activities) {
2598                    for (ActivityIntentInfo filter : a.intents) {
2599                        if (hasValidDomains(filter)) {
2600                            domains.addAll(filter.getHostsList());
2601                        }
2602                    }
2603                }
2604
2605                if (domains.size() > 0) {
2606                    if (DEBUG_DOMAIN_VERIFICATION) {
2607                        Slog.v(TAG, "      + " + packageName);
2608                    }
2609                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2610                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2611                    // and then 'always' in the per-user state actually used for intent resolution.
2612                    final IntentFilterVerificationInfo ivi;
2613                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2614                            new ArrayList<String>(domains));
2615                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2616                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2617                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2618                } else {
2619                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2620                            + "' does not handle web links");
2621                }
2622            } else {
2623                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2624            }
2625        }
2626
2627        scheduleWritePackageRestrictionsLocked(userId);
2628        scheduleWriteSettingsLocked();
2629    }
2630
2631    private void applyFactoryDefaultBrowserLPw(int userId) {
2632        // The default browser app's package name is stored in a string resource,
2633        // with a product-specific overlay used for vendor customization.
2634        String browserPkg = mContext.getResources().getString(
2635                com.android.internal.R.string.default_browser);
2636        if (!TextUtils.isEmpty(browserPkg)) {
2637            // non-empty string => required to be a known package
2638            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2639            if (ps == null) {
2640                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2641                browserPkg = null;
2642            } else {
2643                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2644            }
2645        }
2646
2647        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2648        // default.  If there's more than one, just leave everything alone.
2649        if (browserPkg == null) {
2650            calculateDefaultBrowserLPw(userId);
2651        }
2652    }
2653
2654    private void calculateDefaultBrowserLPw(int userId) {
2655        List<String> allBrowsers = resolveAllBrowserApps(userId);
2656        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2657        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2658    }
2659
2660    private List<String> resolveAllBrowserApps(int userId) {
2661        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2662        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2663                PackageManager.MATCH_ALL, userId);
2664
2665        final int count = list.size();
2666        List<String> result = new ArrayList<String>(count);
2667        for (int i=0; i<count; i++) {
2668            ResolveInfo info = list.get(i);
2669            if (info.activityInfo == null
2670                    || !info.handleAllWebDataURI
2671                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2672                    || result.contains(info.activityInfo.packageName)) {
2673                continue;
2674            }
2675            result.add(info.activityInfo.packageName);
2676        }
2677
2678        return result;
2679    }
2680
2681    private boolean packageIsBrowser(String packageName, int userId) {
2682        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2683                PackageManager.MATCH_ALL, userId);
2684        final int N = list.size();
2685        for (int i = 0; i < N; i++) {
2686            ResolveInfo info = list.get(i);
2687            if (packageName.equals(info.activityInfo.packageName)) {
2688                return true;
2689            }
2690        }
2691        return false;
2692    }
2693
2694    private void checkDefaultBrowser() {
2695        final int myUserId = UserHandle.myUserId();
2696        final String packageName = getDefaultBrowserPackageName(myUserId);
2697        if (packageName != null) {
2698            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2699            if (info == null) {
2700                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2701                synchronized (mPackages) {
2702                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2703                }
2704            }
2705        }
2706    }
2707
2708    @Override
2709    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2710            throws RemoteException {
2711        try {
2712            return super.onTransact(code, data, reply, flags);
2713        } catch (RuntimeException e) {
2714            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2715                Slog.wtf(TAG, "Package Manager Crash", e);
2716            }
2717            throw e;
2718        }
2719    }
2720
2721    void cleanupInstallFailedPackage(PackageSetting ps) {
2722        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2723
2724        removeDataDirsLI(ps.volumeUuid, ps.name);
2725        if (ps.codePath != null) {
2726            removeCodePathLI(ps.codePath);
2727        }
2728        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2729            if (ps.resourcePath.isDirectory()) {
2730                FileUtils.deleteContents(ps.resourcePath);
2731            }
2732            ps.resourcePath.delete();
2733        }
2734        mSettings.removePackageLPw(ps.name);
2735    }
2736
2737    static int[] appendInts(int[] cur, int[] add) {
2738        if (add == null) return cur;
2739        if (cur == null) return add;
2740        final int N = add.length;
2741        for (int i=0; i<N; i++) {
2742            cur = appendInt(cur, add[i]);
2743        }
2744        return cur;
2745    }
2746
2747    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2748        if (!sUserManager.exists(userId)) return null;
2749        final PackageSetting ps = (PackageSetting) p.mExtras;
2750        if (ps == null) {
2751            return null;
2752        }
2753
2754        final PermissionsState permissionsState = ps.getPermissionsState();
2755
2756        final int[] gids = permissionsState.computeGids(userId);
2757        final Set<String> permissions = permissionsState.getPermissions(userId);
2758        final PackageUserState state = ps.readUserState(userId);
2759
2760        return PackageParser.generatePackageInfo(p, gids, flags,
2761                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2762    }
2763
2764    @Override
2765    public void checkPackageStartable(String packageName, int userId) {
2766        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2767
2768        synchronized (mPackages) {
2769            final PackageSetting ps = mSettings.mPackages.get(packageName);
2770            if (ps == null) {
2771                throw new SecurityException("Package " + packageName + " was not found!");
2772            }
2773
2774            if (ps.frozen) {
2775                throw new SecurityException("Package " + packageName + " is currently frozen!");
2776            }
2777
2778            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2779                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2780                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2781            }
2782        }
2783    }
2784
2785    @Override
2786    public boolean isPackageAvailable(String packageName, int userId) {
2787        if (!sUserManager.exists(userId)) return false;
2788        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2789        synchronized (mPackages) {
2790            PackageParser.Package p = mPackages.get(packageName);
2791            if (p != null) {
2792                final PackageSetting ps = (PackageSetting) p.mExtras;
2793                if (ps != null) {
2794                    final PackageUserState state = ps.readUserState(userId);
2795                    if (state != null) {
2796                        return PackageParser.isAvailable(state);
2797                    }
2798                }
2799            }
2800        }
2801        return false;
2802    }
2803
2804    @Override
2805    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2806        if (!sUserManager.exists(userId)) return null;
2807        flags = updateFlagsForPackage(flags, userId, packageName);
2808        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2809        // reader
2810        synchronized (mPackages) {
2811            PackageParser.Package p = mPackages.get(packageName);
2812            if (DEBUG_PACKAGE_INFO)
2813                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2814            if (p != null) {
2815                return generatePackageInfo(p, flags, userId);
2816            }
2817            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2818                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2819            }
2820        }
2821        return null;
2822    }
2823
2824    @Override
2825    public String[] currentToCanonicalPackageNames(String[] names) {
2826        String[] out = new String[names.length];
2827        // reader
2828        synchronized (mPackages) {
2829            for (int i=names.length-1; i>=0; i--) {
2830                PackageSetting ps = mSettings.mPackages.get(names[i]);
2831                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2832            }
2833        }
2834        return out;
2835    }
2836
2837    @Override
2838    public String[] canonicalToCurrentPackageNames(String[] names) {
2839        String[] out = new String[names.length];
2840        // reader
2841        synchronized (mPackages) {
2842            for (int i=names.length-1; i>=0; i--) {
2843                String cur = mSettings.mRenamedPackages.get(names[i]);
2844                out[i] = cur != null ? cur : names[i];
2845            }
2846        }
2847        return out;
2848    }
2849
2850    @Override
2851    public int getPackageUid(String packageName, int flags, int userId) {
2852        if (!sUserManager.exists(userId)) return -1;
2853        flags = updateFlagsForPackage(flags, userId, packageName);
2854        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2855
2856        // reader
2857        synchronized (mPackages) {
2858            final PackageParser.Package p = mPackages.get(packageName);
2859            if (p != null && p.isMatch(flags)) {
2860                return UserHandle.getUid(userId, p.applicationInfo.uid);
2861            }
2862            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2863                final PackageSetting ps = mSettings.mPackages.get(packageName);
2864                if (ps != null && ps.isMatch(flags)) {
2865                    return UserHandle.getUid(userId, ps.appId);
2866                }
2867            }
2868        }
2869
2870        return -1;
2871    }
2872
2873    @Override
2874    public int[] getPackageGids(String packageName, int flags, int userId) {
2875        if (!sUserManager.exists(userId)) return null;
2876        flags = updateFlagsForPackage(flags, userId, packageName);
2877        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2878                "getPackageGids");
2879
2880        // reader
2881        synchronized (mPackages) {
2882            final PackageParser.Package p = mPackages.get(packageName);
2883            if (p != null && p.isMatch(flags)) {
2884                PackageSetting ps = (PackageSetting) p.mExtras;
2885                return ps.getPermissionsState().computeGids(userId);
2886            }
2887            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2888                final PackageSetting ps = mSettings.mPackages.get(packageName);
2889                if (ps != null && ps.isMatch(flags)) {
2890                    return ps.getPermissionsState().computeGids(userId);
2891                }
2892            }
2893        }
2894
2895        return null;
2896    }
2897
2898    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2899        if (bp.perm != null) {
2900            return PackageParser.generatePermissionInfo(bp.perm, flags);
2901        }
2902        PermissionInfo pi = new PermissionInfo();
2903        pi.name = bp.name;
2904        pi.packageName = bp.sourcePackage;
2905        pi.nonLocalizedLabel = bp.name;
2906        pi.protectionLevel = bp.protectionLevel;
2907        return pi;
2908    }
2909
2910    @Override
2911    public PermissionInfo getPermissionInfo(String name, int flags) {
2912        // reader
2913        synchronized (mPackages) {
2914            final BasePermission p = mSettings.mPermissions.get(name);
2915            if (p != null) {
2916                return generatePermissionInfo(p, flags);
2917            }
2918            return null;
2919        }
2920    }
2921
2922    @Override
2923    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2924        // reader
2925        synchronized (mPackages) {
2926            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2927            for (BasePermission p : mSettings.mPermissions.values()) {
2928                if (group == null) {
2929                    if (p.perm == null || p.perm.info.group == null) {
2930                        out.add(generatePermissionInfo(p, flags));
2931                    }
2932                } else {
2933                    if (p.perm != null && group.equals(p.perm.info.group)) {
2934                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2935                    }
2936                }
2937            }
2938
2939            if (out.size() > 0) {
2940                return out;
2941            }
2942            return mPermissionGroups.containsKey(group) ? out : null;
2943        }
2944    }
2945
2946    @Override
2947    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2948        // reader
2949        synchronized (mPackages) {
2950            return PackageParser.generatePermissionGroupInfo(
2951                    mPermissionGroups.get(name), flags);
2952        }
2953    }
2954
2955    @Override
2956    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2957        // reader
2958        synchronized (mPackages) {
2959            final int N = mPermissionGroups.size();
2960            ArrayList<PermissionGroupInfo> out
2961                    = new ArrayList<PermissionGroupInfo>(N);
2962            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2963                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2964            }
2965            return out;
2966        }
2967    }
2968
2969    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2970            int userId) {
2971        if (!sUserManager.exists(userId)) return null;
2972        PackageSetting ps = mSettings.mPackages.get(packageName);
2973        if (ps != null) {
2974            if (ps.pkg == null) {
2975                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2976                        flags, userId);
2977                if (pInfo != null) {
2978                    return pInfo.applicationInfo;
2979                }
2980                return null;
2981            }
2982            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2983                    ps.readUserState(userId), userId);
2984        }
2985        return null;
2986    }
2987
2988    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2989            int userId) {
2990        if (!sUserManager.exists(userId)) return null;
2991        PackageSetting ps = mSettings.mPackages.get(packageName);
2992        if (ps != null) {
2993            PackageParser.Package pkg = ps.pkg;
2994            if (pkg == null) {
2995                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
2996                    return null;
2997                }
2998                // Only data remains, so we aren't worried about code paths
2999                pkg = new PackageParser.Package(packageName);
3000                pkg.applicationInfo.packageName = packageName;
3001                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3002                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3003                pkg.applicationInfo.uid = ps.appId;
3004                pkg.applicationInfo.initForUser(userId);
3005                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3006                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3007            }
3008            return generatePackageInfo(pkg, flags, userId);
3009        }
3010        return null;
3011    }
3012
3013    @Override
3014    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3015        if (!sUserManager.exists(userId)) return null;
3016        flags = updateFlagsForApplication(flags, userId, packageName);
3017        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3018        // writer
3019        synchronized (mPackages) {
3020            PackageParser.Package p = mPackages.get(packageName);
3021            if (DEBUG_PACKAGE_INFO) Log.v(
3022                    TAG, "getApplicationInfo " + packageName
3023                    + ": " + p);
3024            if (p != null) {
3025                PackageSetting ps = mSettings.mPackages.get(packageName);
3026                if (ps == null) return null;
3027                // Note: isEnabledLP() does not apply here - always return info
3028                return PackageParser.generateApplicationInfo(
3029                        p, flags, ps.readUserState(userId), userId);
3030            }
3031            if ("android".equals(packageName)||"system".equals(packageName)) {
3032                return mAndroidApplication;
3033            }
3034            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3035                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3036            }
3037        }
3038        return null;
3039    }
3040
3041    @Override
3042    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3043            final IPackageDataObserver observer) {
3044        mContext.enforceCallingOrSelfPermission(
3045                android.Manifest.permission.CLEAR_APP_CACHE, null);
3046        // Queue up an async operation since clearing cache may take a little while.
3047        mHandler.post(new Runnable() {
3048            public void run() {
3049                mHandler.removeCallbacks(this);
3050                boolean success = true;
3051                synchronized (mInstallLock) {
3052                    try {
3053                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3054                    } catch (InstallerException e) {
3055                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3056                        success = false;
3057                    }
3058                }
3059                if (observer != null) {
3060                    try {
3061                        observer.onRemoveCompleted(null, success);
3062                    } catch (RemoteException e) {
3063                        Slog.w(TAG, "RemoveException when invoking call back");
3064                    }
3065                }
3066            }
3067        });
3068    }
3069
3070    @Override
3071    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3072            final IntentSender pi) {
3073        mContext.enforceCallingOrSelfPermission(
3074                android.Manifest.permission.CLEAR_APP_CACHE, null);
3075        // Queue up an async operation since clearing cache may take a little while.
3076        mHandler.post(new Runnable() {
3077            public void run() {
3078                mHandler.removeCallbacks(this);
3079                boolean success = true;
3080                synchronized (mInstallLock) {
3081                    try {
3082                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3083                    } catch (InstallerException e) {
3084                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3085                        success = false;
3086                    }
3087                }
3088                if(pi != null) {
3089                    try {
3090                        // Callback via pending intent
3091                        int code = success ? 1 : 0;
3092                        pi.sendIntent(null, code, null,
3093                                null, null);
3094                    } catch (SendIntentException e1) {
3095                        Slog.i(TAG, "Failed to send pending intent");
3096                    }
3097                }
3098            }
3099        });
3100    }
3101
3102    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3103        synchronized (mInstallLock) {
3104            try {
3105                mInstaller.freeCache(volumeUuid, freeStorageSize);
3106            } catch (InstallerException e) {
3107                throw new IOException("Failed to free enough space", e);
3108            }
3109        }
3110    }
3111
3112    /**
3113     * Return if the user key is currently unlocked.
3114     */
3115    private boolean isUserKeyUnlocked(int userId) {
3116        if (StorageManager.isFileBasedEncryptionEnabled()) {
3117            final IMountService mount = IMountService.Stub
3118                    .asInterface(ServiceManager.getService("mount"));
3119            if (mount == null) {
3120                Slog.w(TAG, "Early during boot, assuming locked");
3121                return false;
3122            }
3123            final long token = Binder.clearCallingIdentity();
3124            try {
3125                return mount.isUserKeyUnlocked(userId);
3126            } catch (RemoteException e) {
3127                throw e.rethrowAsRuntimeException();
3128            } finally {
3129                Binder.restoreCallingIdentity(token);
3130            }
3131        } else {
3132            return true;
3133        }
3134    }
3135
3136    /**
3137     * Update given flags based on encryption status of current user.
3138     */
3139    private int updateFlags(int flags, int userId) {
3140        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3141                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3142            // Caller expressed an explicit opinion about what encryption
3143            // aware/unaware components they want to see, so fall through and
3144            // give them what they want
3145        } else {
3146            // Caller expressed no opinion, so match based on user state
3147            if (isUserKeyUnlocked(userId)) {
3148                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3149            } else {
3150                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3151            }
3152        }
3153
3154        // Safe mode means we should ignore any third-party apps
3155        if (mSafeMode) {
3156            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3157        }
3158
3159        return flags;
3160    }
3161
3162    /**
3163     * Update given flags when being used to request {@link PackageInfo}.
3164     */
3165    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3166        boolean triaged = true;
3167        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3168                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3169            // Caller is asking for component details, so they'd better be
3170            // asking for specific encryption matching behavior, or be triaged
3171            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3172                    | PackageManager.MATCH_ENCRYPTION_AWARE
3173                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3174                triaged = false;
3175            }
3176        }
3177        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3178                | PackageManager.MATCH_SYSTEM_ONLY
3179                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3180            triaged = false;
3181        }
3182        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3183            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3184                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3185        }
3186        return updateFlags(flags, userId);
3187    }
3188
3189    /**
3190     * Update given flags when being used to request {@link ApplicationInfo}.
3191     */
3192    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3193        return updateFlagsForPackage(flags, userId, cookie);
3194    }
3195
3196    /**
3197     * Update given flags when being used to request {@link ComponentInfo}.
3198     */
3199    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3200        if (cookie instanceof Intent) {
3201            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3202                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3203            }
3204        }
3205
3206        boolean triaged = true;
3207        // Caller is asking for component details, so they'd better be
3208        // asking for specific encryption matching behavior, or be triaged
3209        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3210                | PackageManager.MATCH_ENCRYPTION_AWARE
3211                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3212            triaged = false;
3213        }
3214        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3215            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3216                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3217        }
3218        return updateFlags(flags, userId);
3219    }
3220
3221    /**
3222     * Update given flags when being used to request {@link ResolveInfo}.
3223     */
3224    private int updateFlagsForResolve(int flags, int userId, Object cookie) {
3225        return updateFlagsForComponent(flags, userId, cookie);
3226    }
3227
3228    @Override
3229    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3230        if (!sUserManager.exists(userId)) return null;
3231        flags = updateFlagsForComponent(flags, userId, component);
3232        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3233        synchronized (mPackages) {
3234            PackageParser.Activity a = mActivities.mActivities.get(component);
3235
3236            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3237            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3238                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3239                if (ps == null) return null;
3240                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3241                        userId);
3242            }
3243            if (mResolveComponentName.equals(component)) {
3244                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3245                        new PackageUserState(), userId);
3246            }
3247        }
3248        return null;
3249    }
3250
3251    @Override
3252    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3253            String resolvedType) {
3254        synchronized (mPackages) {
3255            if (component.equals(mResolveComponentName)) {
3256                // The resolver supports EVERYTHING!
3257                return true;
3258            }
3259            PackageParser.Activity a = mActivities.mActivities.get(component);
3260            if (a == null) {
3261                return false;
3262            }
3263            for (int i=0; i<a.intents.size(); i++) {
3264                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3265                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3266                    return true;
3267                }
3268            }
3269            return false;
3270        }
3271    }
3272
3273    @Override
3274    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3275        if (!sUserManager.exists(userId)) return null;
3276        flags = updateFlagsForComponent(flags, userId, component);
3277        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3278        synchronized (mPackages) {
3279            PackageParser.Activity a = mReceivers.mActivities.get(component);
3280            if (DEBUG_PACKAGE_INFO) Log.v(
3281                TAG, "getReceiverInfo " + component + ": " + a);
3282            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3283                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3284                if (ps == null) return null;
3285                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3286                        userId);
3287            }
3288        }
3289        return null;
3290    }
3291
3292    @Override
3293    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3294        if (!sUserManager.exists(userId)) return null;
3295        flags = updateFlagsForComponent(flags, userId, component);
3296        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3297        synchronized (mPackages) {
3298            PackageParser.Service s = mServices.mServices.get(component);
3299            if (DEBUG_PACKAGE_INFO) Log.v(
3300                TAG, "getServiceInfo " + component + ": " + s);
3301            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3302                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3303                if (ps == null) return null;
3304                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3305                        userId);
3306            }
3307        }
3308        return null;
3309    }
3310
3311    @Override
3312    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3313        if (!sUserManager.exists(userId)) return null;
3314        flags = updateFlagsForComponent(flags, userId, component);
3315        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3316        synchronized (mPackages) {
3317            PackageParser.Provider p = mProviders.mProviders.get(component);
3318            if (DEBUG_PACKAGE_INFO) Log.v(
3319                TAG, "getProviderInfo " + component + ": " + p);
3320            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3321                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3322                if (ps == null) return null;
3323                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3324                        userId);
3325            }
3326        }
3327        return null;
3328    }
3329
3330    @Override
3331    public String[] getSystemSharedLibraryNames() {
3332        Set<String> libSet;
3333        synchronized (mPackages) {
3334            libSet = mSharedLibraries.keySet();
3335            int size = libSet.size();
3336            if (size > 0) {
3337                String[] libs = new String[size];
3338                libSet.toArray(libs);
3339                return libs;
3340            }
3341        }
3342        return null;
3343    }
3344
3345    /**
3346     * @hide
3347     */
3348    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3349        synchronized (mPackages) {
3350            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3351            if (lib != null && lib.apk != null) {
3352                return mPackages.get(lib.apk);
3353            }
3354        }
3355        return null;
3356    }
3357
3358    @Override
3359    public FeatureInfo[] getSystemAvailableFeatures() {
3360        Collection<FeatureInfo> featSet;
3361        synchronized (mPackages) {
3362            featSet = mAvailableFeatures.values();
3363            int size = featSet.size();
3364            if (size > 0) {
3365                FeatureInfo[] features = new FeatureInfo[size+1];
3366                featSet.toArray(features);
3367                FeatureInfo fi = new FeatureInfo();
3368                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3369                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3370                features[size] = fi;
3371                return features;
3372            }
3373        }
3374        return null;
3375    }
3376
3377    @Override
3378    public boolean hasSystemFeature(String name) {
3379        synchronized (mPackages) {
3380            return mAvailableFeatures.containsKey(name);
3381        }
3382    }
3383
3384    @Override
3385    public int checkPermission(String permName, String pkgName, int userId) {
3386        if (!sUserManager.exists(userId)) {
3387            return PackageManager.PERMISSION_DENIED;
3388        }
3389
3390        synchronized (mPackages) {
3391            final PackageParser.Package p = mPackages.get(pkgName);
3392            if (p != null && p.mExtras != null) {
3393                final PackageSetting ps = (PackageSetting) p.mExtras;
3394                final PermissionsState permissionsState = ps.getPermissionsState();
3395                if (permissionsState.hasPermission(permName, userId)) {
3396                    return PackageManager.PERMISSION_GRANTED;
3397                }
3398                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3399                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3400                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3401                    return PackageManager.PERMISSION_GRANTED;
3402                }
3403            }
3404        }
3405
3406        return PackageManager.PERMISSION_DENIED;
3407    }
3408
3409    @Override
3410    public int checkUidPermission(String permName, int uid) {
3411        final int userId = UserHandle.getUserId(uid);
3412
3413        if (!sUserManager.exists(userId)) {
3414            return PackageManager.PERMISSION_DENIED;
3415        }
3416
3417        synchronized (mPackages) {
3418            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3419            if (obj != null) {
3420                final SettingBase ps = (SettingBase) obj;
3421                final PermissionsState permissionsState = ps.getPermissionsState();
3422                if (permissionsState.hasPermission(permName, userId)) {
3423                    return PackageManager.PERMISSION_GRANTED;
3424                }
3425                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3426                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3427                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3428                    return PackageManager.PERMISSION_GRANTED;
3429                }
3430            } else {
3431                ArraySet<String> perms = mSystemPermissions.get(uid);
3432                if (perms != null) {
3433                    if (perms.contains(permName)) {
3434                        return PackageManager.PERMISSION_GRANTED;
3435                    }
3436                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3437                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3438                        return PackageManager.PERMISSION_GRANTED;
3439                    }
3440                }
3441            }
3442        }
3443
3444        return PackageManager.PERMISSION_DENIED;
3445    }
3446
3447    @Override
3448    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3449        if (UserHandle.getCallingUserId() != userId) {
3450            mContext.enforceCallingPermission(
3451                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3452                    "isPermissionRevokedByPolicy for user " + userId);
3453        }
3454
3455        if (checkPermission(permission, packageName, userId)
3456                == PackageManager.PERMISSION_GRANTED) {
3457            return false;
3458        }
3459
3460        final long identity = Binder.clearCallingIdentity();
3461        try {
3462            final int flags = getPermissionFlags(permission, packageName, userId);
3463            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3464        } finally {
3465            Binder.restoreCallingIdentity(identity);
3466        }
3467    }
3468
3469    @Override
3470    public String getPermissionControllerPackageName() {
3471        synchronized (mPackages) {
3472            return mRequiredInstallerPackage;
3473        }
3474    }
3475
3476    /**
3477     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3478     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3479     * @param checkShell TODO(yamasani):
3480     * @param message the message to log on security exception
3481     */
3482    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3483            boolean checkShell, String message) {
3484        if (userId < 0) {
3485            throw new IllegalArgumentException("Invalid userId " + userId);
3486        }
3487        if (checkShell) {
3488            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3489        }
3490        if (userId == UserHandle.getUserId(callingUid)) return;
3491        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3492            if (requireFullPermission) {
3493                mContext.enforceCallingOrSelfPermission(
3494                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3495            } else {
3496                try {
3497                    mContext.enforceCallingOrSelfPermission(
3498                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3499                } catch (SecurityException se) {
3500                    mContext.enforceCallingOrSelfPermission(
3501                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3502                }
3503            }
3504        }
3505    }
3506
3507    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3508        if (callingUid == Process.SHELL_UID) {
3509            if (userHandle >= 0
3510                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3511                throw new SecurityException("Shell does not have permission to access user "
3512                        + userHandle);
3513            } else if (userHandle < 0) {
3514                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3515                        + Debug.getCallers(3));
3516            }
3517        }
3518    }
3519
3520    private BasePermission findPermissionTreeLP(String permName) {
3521        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3522            if (permName.startsWith(bp.name) &&
3523                    permName.length() > bp.name.length() &&
3524                    permName.charAt(bp.name.length()) == '.') {
3525                return bp;
3526            }
3527        }
3528        return null;
3529    }
3530
3531    private BasePermission checkPermissionTreeLP(String permName) {
3532        if (permName != null) {
3533            BasePermission bp = findPermissionTreeLP(permName);
3534            if (bp != null) {
3535                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3536                    return bp;
3537                }
3538                throw new SecurityException("Calling uid "
3539                        + Binder.getCallingUid()
3540                        + " is not allowed to add to permission tree "
3541                        + bp.name + " owned by uid " + bp.uid);
3542            }
3543        }
3544        throw new SecurityException("No permission tree found for " + permName);
3545    }
3546
3547    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3548        if (s1 == null) {
3549            return s2 == null;
3550        }
3551        if (s2 == null) {
3552            return false;
3553        }
3554        if (s1.getClass() != s2.getClass()) {
3555            return false;
3556        }
3557        return s1.equals(s2);
3558    }
3559
3560    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3561        if (pi1.icon != pi2.icon) return false;
3562        if (pi1.logo != pi2.logo) return false;
3563        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3564        if (!compareStrings(pi1.name, pi2.name)) return false;
3565        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3566        // We'll take care of setting this one.
3567        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3568        // These are not currently stored in settings.
3569        //if (!compareStrings(pi1.group, pi2.group)) return false;
3570        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3571        //if (pi1.labelRes != pi2.labelRes) return false;
3572        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3573        return true;
3574    }
3575
3576    int permissionInfoFootprint(PermissionInfo info) {
3577        int size = info.name.length();
3578        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3579        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3580        return size;
3581    }
3582
3583    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3584        int size = 0;
3585        for (BasePermission perm : mSettings.mPermissions.values()) {
3586            if (perm.uid == tree.uid) {
3587                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3588            }
3589        }
3590        return size;
3591    }
3592
3593    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3594        // We calculate the max size of permissions defined by this uid and throw
3595        // if that plus the size of 'info' would exceed our stated maximum.
3596        if (tree.uid != Process.SYSTEM_UID) {
3597            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3598            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3599                throw new SecurityException("Permission tree size cap exceeded");
3600            }
3601        }
3602    }
3603
3604    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3605        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3606            throw new SecurityException("Label must be specified in permission");
3607        }
3608        BasePermission tree = checkPermissionTreeLP(info.name);
3609        BasePermission bp = mSettings.mPermissions.get(info.name);
3610        boolean added = bp == null;
3611        boolean changed = true;
3612        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3613        if (added) {
3614            enforcePermissionCapLocked(info, tree);
3615            bp = new BasePermission(info.name, tree.sourcePackage,
3616                    BasePermission.TYPE_DYNAMIC);
3617        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3618            throw new SecurityException(
3619                    "Not allowed to modify non-dynamic permission "
3620                    + info.name);
3621        } else {
3622            if (bp.protectionLevel == fixedLevel
3623                    && bp.perm.owner.equals(tree.perm.owner)
3624                    && bp.uid == tree.uid
3625                    && comparePermissionInfos(bp.perm.info, info)) {
3626                changed = false;
3627            }
3628        }
3629        bp.protectionLevel = fixedLevel;
3630        info = new PermissionInfo(info);
3631        info.protectionLevel = fixedLevel;
3632        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3633        bp.perm.info.packageName = tree.perm.info.packageName;
3634        bp.uid = tree.uid;
3635        if (added) {
3636            mSettings.mPermissions.put(info.name, bp);
3637        }
3638        if (changed) {
3639            if (!async) {
3640                mSettings.writeLPr();
3641            } else {
3642                scheduleWriteSettingsLocked();
3643            }
3644        }
3645        return added;
3646    }
3647
3648    @Override
3649    public boolean addPermission(PermissionInfo info) {
3650        synchronized (mPackages) {
3651            return addPermissionLocked(info, false);
3652        }
3653    }
3654
3655    @Override
3656    public boolean addPermissionAsync(PermissionInfo info) {
3657        synchronized (mPackages) {
3658            return addPermissionLocked(info, true);
3659        }
3660    }
3661
3662    @Override
3663    public void removePermission(String name) {
3664        synchronized (mPackages) {
3665            checkPermissionTreeLP(name);
3666            BasePermission bp = mSettings.mPermissions.get(name);
3667            if (bp != null) {
3668                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3669                    throw new SecurityException(
3670                            "Not allowed to modify non-dynamic permission "
3671                            + name);
3672                }
3673                mSettings.mPermissions.remove(name);
3674                mSettings.writeLPr();
3675            }
3676        }
3677    }
3678
3679    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3680            BasePermission bp) {
3681        int index = pkg.requestedPermissions.indexOf(bp.name);
3682        if (index == -1) {
3683            throw new SecurityException("Package " + pkg.packageName
3684                    + " has not requested permission " + bp.name);
3685        }
3686        if (!bp.isRuntime() && !bp.isDevelopment()) {
3687            throw new SecurityException("Permission " + bp.name
3688                    + " is not a changeable permission type");
3689        }
3690    }
3691
3692    @Override
3693    public void grantRuntimePermission(String packageName, String name, final int userId) {
3694        if (!sUserManager.exists(userId)) {
3695            Log.e(TAG, "No such user:" + userId);
3696            return;
3697        }
3698
3699        mContext.enforceCallingOrSelfPermission(
3700                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3701                "grantRuntimePermission");
3702
3703        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3704                "grantRuntimePermission");
3705
3706        final int uid;
3707        final SettingBase sb;
3708
3709        synchronized (mPackages) {
3710            final PackageParser.Package pkg = mPackages.get(packageName);
3711            if (pkg == null) {
3712                throw new IllegalArgumentException("Unknown package: " + packageName);
3713            }
3714
3715            final BasePermission bp = mSettings.mPermissions.get(name);
3716            if (bp == null) {
3717                throw new IllegalArgumentException("Unknown permission: " + name);
3718            }
3719
3720            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3721
3722            // If a permission review is required for legacy apps we represent
3723            // their permissions as always granted runtime ones since we need
3724            // to keep the review required permission flag per user while an
3725            // install permission's state is shared across all users.
3726            if (Build.PERMISSIONS_REVIEW_REQUIRED
3727                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3728                    && bp.isRuntime()) {
3729                return;
3730            }
3731
3732            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3733            sb = (SettingBase) pkg.mExtras;
3734            if (sb == null) {
3735                throw new IllegalArgumentException("Unknown package: " + packageName);
3736            }
3737
3738            final PermissionsState permissionsState = sb.getPermissionsState();
3739
3740            final int flags = permissionsState.getPermissionFlags(name, userId);
3741            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3742                throw new SecurityException("Cannot grant system fixed permission "
3743                        + name + " for package " + packageName);
3744            }
3745
3746            if (bp.isDevelopment()) {
3747                // Development permissions must be handled specially, since they are not
3748                // normal runtime permissions.  For now they apply to all users.
3749                if (permissionsState.grantInstallPermission(bp) !=
3750                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3751                    scheduleWriteSettingsLocked();
3752                }
3753                return;
3754            }
3755
3756            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3757                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3758                return;
3759            }
3760
3761            final int result = permissionsState.grantRuntimePermission(bp, userId);
3762            switch (result) {
3763                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3764                    return;
3765                }
3766
3767                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3768                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3769                    mHandler.post(new Runnable() {
3770                        @Override
3771                        public void run() {
3772                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3773                        }
3774                    });
3775                }
3776                break;
3777            }
3778
3779            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3780
3781            // Not critical if that is lost - app has to request again.
3782            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3783        }
3784
3785        // Only need to do this if user is initialized. Otherwise it's a new user
3786        // and there are no processes running as the user yet and there's no need
3787        // to make an expensive call to remount processes for the changed permissions.
3788        if (READ_EXTERNAL_STORAGE.equals(name)
3789                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3790            final long token = Binder.clearCallingIdentity();
3791            try {
3792                if (sUserManager.isInitialized(userId)) {
3793                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3794                            MountServiceInternal.class);
3795                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3796                }
3797            } finally {
3798                Binder.restoreCallingIdentity(token);
3799            }
3800        }
3801    }
3802
3803    @Override
3804    public void revokeRuntimePermission(String packageName, String name, int userId) {
3805        if (!sUserManager.exists(userId)) {
3806            Log.e(TAG, "No such user:" + userId);
3807            return;
3808        }
3809
3810        mContext.enforceCallingOrSelfPermission(
3811                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3812                "revokeRuntimePermission");
3813
3814        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3815                "revokeRuntimePermission");
3816
3817        final int appId;
3818
3819        synchronized (mPackages) {
3820            final PackageParser.Package pkg = mPackages.get(packageName);
3821            if (pkg == null) {
3822                throw new IllegalArgumentException("Unknown package: " + packageName);
3823            }
3824
3825            final BasePermission bp = mSettings.mPermissions.get(name);
3826            if (bp == null) {
3827                throw new IllegalArgumentException("Unknown permission: " + name);
3828            }
3829
3830            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3831
3832            // If a permission review is required for legacy apps we represent
3833            // their permissions as always granted runtime ones since we need
3834            // to keep the review required permission flag per user while an
3835            // install permission's state is shared across all users.
3836            if (Build.PERMISSIONS_REVIEW_REQUIRED
3837                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3838                    && bp.isRuntime()) {
3839                return;
3840            }
3841
3842            SettingBase sb = (SettingBase) pkg.mExtras;
3843            if (sb == null) {
3844                throw new IllegalArgumentException("Unknown package: " + packageName);
3845            }
3846
3847            final PermissionsState permissionsState = sb.getPermissionsState();
3848
3849            final int flags = permissionsState.getPermissionFlags(name, userId);
3850            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3851                throw new SecurityException("Cannot revoke system fixed permission "
3852                        + name + " for package " + packageName);
3853            }
3854
3855            if (bp.isDevelopment()) {
3856                // Development permissions must be handled specially, since they are not
3857                // normal runtime permissions.  For now they apply to all users.
3858                if (permissionsState.revokeInstallPermission(bp) !=
3859                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3860                    scheduleWriteSettingsLocked();
3861                }
3862                return;
3863            }
3864
3865            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3866                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3867                return;
3868            }
3869
3870            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3871
3872            // Critical, after this call app should never have the permission.
3873            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3874
3875            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3876        }
3877
3878        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3879    }
3880
3881    @Override
3882    public void resetRuntimePermissions() {
3883        mContext.enforceCallingOrSelfPermission(
3884                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3885                "revokeRuntimePermission");
3886
3887        int callingUid = Binder.getCallingUid();
3888        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3889            mContext.enforceCallingOrSelfPermission(
3890                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3891                    "resetRuntimePermissions");
3892        }
3893
3894        synchronized (mPackages) {
3895            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3896            for (int userId : UserManagerService.getInstance().getUserIds()) {
3897                final int packageCount = mPackages.size();
3898                for (int i = 0; i < packageCount; i++) {
3899                    PackageParser.Package pkg = mPackages.valueAt(i);
3900                    if (!(pkg.mExtras instanceof PackageSetting)) {
3901                        continue;
3902                    }
3903                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3904                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3905                }
3906            }
3907        }
3908    }
3909
3910    @Override
3911    public int getPermissionFlags(String name, String packageName, int userId) {
3912        if (!sUserManager.exists(userId)) {
3913            return 0;
3914        }
3915
3916        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3917
3918        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3919                "getPermissionFlags");
3920
3921        synchronized (mPackages) {
3922            final PackageParser.Package pkg = mPackages.get(packageName);
3923            if (pkg == null) {
3924                throw new IllegalArgumentException("Unknown package: " + packageName);
3925            }
3926
3927            final BasePermission bp = mSettings.mPermissions.get(name);
3928            if (bp == null) {
3929                throw new IllegalArgumentException("Unknown permission: " + name);
3930            }
3931
3932            SettingBase sb = (SettingBase) pkg.mExtras;
3933            if (sb == null) {
3934                throw new IllegalArgumentException("Unknown package: " + packageName);
3935            }
3936
3937            PermissionsState permissionsState = sb.getPermissionsState();
3938            return permissionsState.getPermissionFlags(name, userId);
3939        }
3940    }
3941
3942    @Override
3943    public void updatePermissionFlags(String name, String packageName, int flagMask,
3944            int flagValues, int userId) {
3945        if (!sUserManager.exists(userId)) {
3946            return;
3947        }
3948
3949        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3950
3951        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3952                "updatePermissionFlags");
3953
3954        // Only the system can change these flags and nothing else.
3955        if (getCallingUid() != Process.SYSTEM_UID) {
3956            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3957            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3958            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3959            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3960            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3961        }
3962
3963        synchronized (mPackages) {
3964            final PackageParser.Package pkg = mPackages.get(packageName);
3965            if (pkg == null) {
3966                throw new IllegalArgumentException("Unknown package: " + packageName);
3967            }
3968
3969            final BasePermission bp = mSettings.mPermissions.get(name);
3970            if (bp == null) {
3971                throw new IllegalArgumentException("Unknown permission: " + name);
3972            }
3973
3974            SettingBase sb = (SettingBase) pkg.mExtras;
3975            if (sb == null) {
3976                throw new IllegalArgumentException("Unknown package: " + packageName);
3977            }
3978
3979            PermissionsState permissionsState = sb.getPermissionsState();
3980
3981            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3982
3983            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3984                // Install and runtime permissions are stored in different places,
3985                // so figure out what permission changed and persist the change.
3986                if (permissionsState.getInstallPermissionState(name) != null) {
3987                    scheduleWriteSettingsLocked();
3988                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3989                        || hadState) {
3990                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3991                }
3992            }
3993        }
3994    }
3995
3996    /**
3997     * Update the permission flags for all packages and runtime permissions of a user in order
3998     * to allow device or profile owner to remove POLICY_FIXED.
3999     */
4000    @Override
4001    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4002        if (!sUserManager.exists(userId)) {
4003            return;
4004        }
4005
4006        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4007
4008        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4009                "updatePermissionFlagsForAllApps");
4010
4011        // Only the system can change system fixed flags.
4012        if (getCallingUid() != Process.SYSTEM_UID) {
4013            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4014            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4015        }
4016
4017        synchronized (mPackages) {
4018            boolean changed = false;
4019            final int packageCount = mPackages.size();
4020            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4021                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4022                SettingBase sb = (SettingBase) pkg.mExtras;
4023                if (sb == null) {
4024                    continue;
4025                }
4026                PermissionsState permissionsState = sb.getPermissionsState();
4027                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4028                        userId, flagMask, flagValues);
4029            }
4030            if (changed) {
4031                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4032            }
4033        }
4034    }
4035
4036    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4037        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4038                != PackageManager.PERMISSION_GRANTED
4039            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4040                != PackageManager.PERMISSION_GRANTED) {
4041            throw new SecurityException(message + " requires "
4042                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4043                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4044        }
4045    }
4046
4047    @Override
4048    public boolean shouldShowRequestPermissionRationale(String permissionName,
4049            String packageName, int userId) {
4050        if (UserHandle.getCallingUserId() != userId) {
4051            mContext.enforceCallingPermission(
4052                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4053                    "canShowRequestPermissionRationale for user " + userId);
4054        }
4055
4056        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4057        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4058            return false;
4059        }
4060
4061        if (checkPermission(permissionName, packageName, userId)
4062                == PackageManager.PERMISSION_GRANTED) {
4063            return false;
4064        }
4065
4066        final int flags;
4067
4068        final long identity = Binder.clearCallingIdentity();
4069        try {
4070            flags = getPermissionFlags(permissionName,
4071                    packageName, userId);
4072        } finally {
4073            Binder.restoreCallingIdentity(identity);
4074        }
4075
4076        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4077                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4078                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4079
4080        if ((flags & fixedFlags) != 0) {
4081            return false;
4082        }
4083
4084        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4085    }
4086
4087    @Override
4088    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4089        mContext.enforceCallingOrSelfPermission(
4090                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4091                "addOnPermissionsChangeListener");
4092
4093        synchronized (mPackages) {
4094            mOnPermissionChangeListeners.addListenerLocked(listener);
4095        }
4096    }
4097
4098    @Override
4099    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4100        synchronized (mPackages) {
4101            mOnPermissionChangeListeners.removeListenerLocked(listener);
4102        }
4103    }
4104
4105    @Override
4106    public boolean isProtectedBroadcast(String actionName) {
4107        synchronized (mPackages) {
4108            if (mProtectedBroadcasts.contains(actionName)) {
4109                return true;
4110            } else if (actionName != null) {
4111                // TODO: remove these terrible hacks
4112                if (actionName.startsWith("android.net.netmon.lingerExpired")
4113                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4114                    return true;
4115                }
4116            }
4117        }
4118        return false;
4119    }
4120
4121    @Override
4122    public int checkSignatures(String pkg1, String pkg2) {
4123        synchronized (mPackages) {
4124            final PackageParser.Package p1 = mPackages.get(pkg1);
4125            final PackageParser.Package p2 = mPackages.get(pkg2);
4126            if (p1 == null || p1.mExtras == null
4127                    || p2 == null || p2.mExtras == null) {
4128                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4129            }
4130            return compareSignatures(p1.mSignatures, p2.mSignatures);
4131        }
4132    }
4133
4134    @Override
4135    public int checkUidSignatures(int uid1, int uid2) {
4136        // Map to base uids.
4137        uid1 = UserHandle.getAppId(uid1);
4138        uid2 = UserHandle.getAppId(uid2);
4139        // reader
4140        synchronized (mPackages) {
4141            Signature[] s1;
4142            Signature[] s2;
4143            Object obj = mSettings.getUserIdLPr(uid1);
4144            if (obj != null) {
4145                if (obj instanceof SharedUserSetting) {
4146                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4147                } else if (obj instanceof PackageSetting) {
4148                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4149                } else {
4150                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4151                }
4152            } else {
4153                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4154            }
4155            obj = mSettings.getUserIdLPr(uid2);
4156            if (obj != null) {
4157                if (obj instanceof SharedUserSetting) {
4158                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4159                } else if (obj instanceof PackageSetting) {
4160                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4161                } else {
4162                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4163                }
4164            } else {
4165                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4166            }
4167            return compareSignatures(s1, s2);
4168        }
4169    }
4170
4171    private void killUid(int appId, int userId, String reason) {
4172        final long identity = Binder.clearCallingIdentity();
4173        try {
4174            IActivityManager am = ActivityManagerNative.getDefault();
4175            if (am != null) {
4176                try {
4177                    am.killUid(appId, userId, reason);
4178                } catch (RemoteException e) {
4179                    /* ignore - same process */
4180                }
4181            }
4182        } finally {
4183            Binder.restoreCallingIdentity(identity);
4184        }
4185    }
4186
4187    /**
4188     * Compares two sets of signatures. Returns:
4189     * <br />
4190     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4191     * <br />
4192     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4193     * <br />
4194     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4195     * <br />
4196     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4197     * <br />
4198     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4199     */
4200    static int compareSignatures(Signature[] s1, Signature[] s2) {
4201        if (s1 == null) {
4202            return s2 == null
4203                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4204                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4205        }
4206
4207        if (s2 == null) {
4208            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4209        }
4210
4211        if (s1.length != s2.length) {
4212            return PackageManager.SIGNATURE_NO_MATCH;
4213        }
4214
4215        // Since both signature sets are of size 1, we can compare without HashSets.
4216        if (s1.length == 1) {
4217            return s1[0].equals(s2[0]) ?
4218                    PackageManager.SIGNATURE_MATCH :
4219                    PackageManager.SIGNATURE_NO_MATCH;
4220        }
4221
4222        ArraySet<Signature> set1 = new ArraySet<Signature>();
4223        for (Signature sig : s1) {
4224            set1.add(sig);
4225        }
4226        ArraySet<Signature> set2 = new ArraySet<Signature>();
4227        for (Signature sig : s2) {
4228            set2.add(sig);
4229        }
4230        // Make sure s2 contains all signatures in s1.
4231        if (set1.equals(set2)) {
4232            return PackageManager.SIGNATURE_MATCH;
4233        }
4234        return PackageManager.SIGNATURE_NO_MATCH;
4235    }
4236
4237    /**
4238     * If the database version for this type of package (internal storage or
4239     * external storage) is less than the version where package signatures
4240     * were updated, return true.
4241     */
4242    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4243        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4244        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4245    }
4246
4247    /**
4248     * Used for backward compatibility to make sure any packages with
4249     * certificate chains get upgraded to the new style. {@code existingSigs}
4250     * will be in the old format (since they were stored on disk from before the
4251     * system upgrade) and {@code scannedSigs} will be in the newer format.
4252     */
4253    private int compareSignaturesCompat(PackageSignatures existingSigs,
4254            PackageParser.Package scannedPkg) {
4255        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4256            return PackageManager.SIGNATURE_NO_MATCH;
4257        }
4258
4259        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4260        for (Signature sig : existingSigs.mSignatures) {
4261            existingSet.add(sig);
4262        }
4263        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4264        for (Signature sig : scannedPkg.mSignatures) {
4265            try {
4266                Signature[] chainSignatures = sig.getChainSignatures();
4267                for (Signature chainSig : chainSignatures) {
4268                    scannedCompatSet.add(chainSig);
4269                }
4270            } catch (CertificateEncodingException e) {
4271                scannedCompatSet.add(sig);
4272            }
4273        }
4274        /*
4275         * Make sure the expanded scanned set contains all signatures in the
4276         * existing one.
4277         */
4278        if (scannedCompatSet.equals(existingSet)) {
4279            // Migrate the old signatures to the new scheme.
4280            existingSigs.assignSignatures(scannedPkg.mSignatures);
4281            // The new KeySets will be re-added later in the scanning process.
4282            synchronized (mPackages) {
4283                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4284            }
4285            return PackageManager.SIGNATURE_MATCH;
4286        }
4287        return PackageManager.SIGNATURE_NO_MATCH;
4288    }
4289
4290    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4291        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4292        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4293    }
4294
4295    private int compareSignaturesRecover(PackageSignatures existingSigs,
4296            PackageParser.Package scannedPkg) {
4297        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4298            return PackageManager.SIGNATURE_NO_MATCH;
4299        }
4300
4301        String msg = null;
4302        try {
4303            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4304                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4305                        + scannedPkg.packageName);
4306                return PackageManager.SIGNATURE_MATCH;
4307            }
4308        } catch (CertificateException e) {
4309            msg = e.getMessage();
4310        }
4311
4312        logCriticalInfo(Log.INFO,
4313                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4314        return PackageManager.SIGNATURE_NO_MATCH;
4315    }
4316
4317    @Override
4318    public String[] getPackagesForUid(int uid) {
4319        uid = UserHandle.getAppId(uid);
4320        // reader
4321        synchronized (mPackages) {
4322            Object obj = mSettings.getUserIdLPr(uid);
4323            if (obj instanceof SharedUserSetting) {
4324                final SharedUserSetting sus = (SharedUserSetting) obj;
4325                final int N = sus.packages.size();
4326                final String[] res = new String[N];
4327                final Iterator<PackageSetting> it = sus.packages.iterator();
4328                int i = 0;
4329                while (it.hasNext()) {
4330                    res[i++] = it.next().name;
4331                }
4332                return res;
4333            } else if (obj instanceof PackageSetting) {
4334                final PackageSetting ps = (PackageSetting) obj;
4335                return new String[] { ps.name };
4336            }
4337        }
4338        return null;
4339    }
4340
4341    @Override
4342    public String getNameForUid(int uid) {
4343        // reader
4344        synchronized (mPackages) {
4345            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4346            if (obj instanceof SharedUserSetting) {
4347                final SharedUserSetting sus = (SharedUserSetting) obj;
4348                return sus.name + ":" + sus.userId;
4349            } else if (obj instanceof PackageSetting) {
4350                final PackageSetting ps = (PackageSetting) obj;
4351                return ps.name;
4352            }
4353        }
4354        return null;
4355    }
4356
4357    @Override
4358    public int getUidForSharedUser(String sharedUserName) {
4359        if(sharedUserName == null) {
4360            return -1;
4361        }
4362        // reader
4363        synchronized (mPackages) {
4364            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4365            if (suid == null) {
4366                return -1;
4367            }
4368            return suid.userId;
4369        }
4370    }
4371
4372    @Override
4373    public int getFlagsForUid(int uid) {
4374        synchronized (mPackages) {
4375            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4376            if (obj instanceof SharedUserSetting) {
4377                final SharedUserSetting sus = (SharedUserSetting) obj;
4378                return sus.pkgFlags;
4379            } else if (obj instanceof PackageSetting) {
4380                final PackageSetting ps = (PackageSetting) obj;
4381                return ps.pkgFlags;
4382            }
4383        }
4384        return 0;
4385    }
4386
4387    @Override
4388    public int getPrivateFlagsForUid(int uid) {
4389        synchronized (mPackages) {
4390            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4391            if (obj instanceof SharedUserSetting) {
4392                final SharedUserSetting sus = (SharedUserSetting) obj;
4393                return sus.pkgPrivateFlags;
4394            } else if (obj instanceof PackageSetting) {
4395                final PackageSetting ps = (PackageSetting) obj;
4396                return ps.pkgPrivateFlags;
4397            }
4398        }
4399        return 0;
4400    }
4401
4402    @Override
4403    public boolean isUidPrivileged(int uid) {
4404        uid = UserHandle.getAppId(uid);
4405        // reader
4406        synchronized (mPackages) {
4407            Object obj = mSettings.getUserIdLPr(uid);
4408            if (obj instanceof SharedUserSetting) {
4409                final SharedUserSetting sus = (SharedUserSetting) obj;
4410                final Iterator<PackageSetting> it = sus.packages.iterator();
4411                while (it.hasNext()) {
4412                    if (it.next().isPrivileged()) {
4413                        return true;
4414                    }
4415                }
4416            } else if (obj instanceof PackageSetting) {
4417                final PackageSetting ps = (PackageSetting) obj;
4418                return ps.isPrivileged();
4419            }
4420        }
4421        return false;
4422    }
4423
4424    @Override
4425    public String[] getAppOpPermissionPackages(String permissionName) {
4426        synchronized (mPackages) {
4427            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4428            if (pkgs == null) {
4429                return null;
4430            }
4431            return pkgs.toArray(new String[pkgs.size()]);
4432        }
4433    }
4434
4435    @Override
4436    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4437            int flags, int userId) {
4438        if (!sUserManager.exists(userId)) return null;
4439        flags = updateFlagsForResolve(flags, userId, intent);
4440        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4441        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4442        final ResolveInfo bestChoice =
4443                chooseBestActivity(intent, resolvedType, flags, query, userId);
4444
4445        if (isEphemeralAllowed(intent, query, userId)) {
4446            final EphemeralResolveInfo ai =
4447                    getEphemeralResolveInfo(intent, resolvedType, userId);
4448            if (ai != null) {
4449                if (DEBUG_EPHEMERAL) {
4450                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4451                }
4452                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4453                bestChoice.ephemeralResolveInfo = ai;
4454            }
4455        }
4456        return bestChoice;
4457    }
4458
4459    @Override
4460    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4461            IntentFilter filter, int match, ComponentName activity) {
4462        final int userId = UserHandle.getCallingUserId();
4463        if (DEBUG_PREFERRED) {
4464            Log.v(TAG, "setLastChosenActivity intent=" + intent
4465                + " resolvedType=" + resolvedType
4466                + " flags=" + flags
4467                + " filter=" + filter
4468                + " match=" + match
4469                + " activity=" + activity);
4470            filter.dump(new PrintStreamPrinter(System.out), "    ");
4471        }
4472        intent.setComponent(null);
4473        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4474        // Find any earlier preferred or last chosen entries and nuke them
4475        findPreferredActivity(intent, resolvedType,
4476                flags, query, 0, false, true, false, userId);
4477        // Add the new activity as the last chosen for this filter
4478        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4479                "Setting last chosen");
4480    }
4481
4482    @Override
4483    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4484        final int userId = UserHandle.getCallingUserId();
4485        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4486        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4487        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4488                false, false, false, userId);
4489    }
4490
4491
4492    private boolean isEphemeralAllowed(
4493            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4494        // Short circuit and return early if possible.
4495        if (DISABLE_EPHEMERAL_APPS) {
4496            return false;
4497        }
4498        final int callingUser = UserHandle.getCallingUserId();
4499        if (callingUser != UserHandle.USER_SYSTEM) {
4500            return false;
4501        }
4502        if (mEphemeralResolverConnection == null) {
4503            return false;
4504        }
4505        if (intent.getComponent() != null) {
4506            return false;
4507        }
4508        if (intent.getPackage() != null) {
4509            return false;
4510        }
4511        final boolean isWebUri = hasWebURI(intent);
4512        if (!isWebUri) {
4513            return false;
4514        }
4515        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4516        synchronized (mPackages) {
4517            final int count = resolvedActivites.size();
4518            for (int n = 0; n < count; n++) {
4519                ResolveInfo info = resolvedActivites.get(n);
4520                String packageName = info.activityInfo.packageName;
4521                PackageSetting ps = mSettings.mPackages.get(packageName);
4522                if (ps != null) {
4523                    // Try to get the status from User settings first
4524                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4525                    int status = (int) (packedStatus >> 32);
4526                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4527                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4528                        if (DEBUG_EPHEMERAL) {
4529                            Slog.v(TAG, "DENY ephemeral apps;"
4530                                + " pkg: " + packageName + ", status: " + status);
4531                        }
4532                        return false;
4533                    }
4534                }
4535            }
4536        }
4537        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4538        return true;
4539    }
4540
4541    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4542            int userId) {
4543        MessageDigest digest = null;
4544        try {
4545            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4546        } catch (NoSuchAlgorithmException e) {
4547            // If we can't create a digest, ignore ephemeral apps.
4548            return null;
4549        }
4550
4551        final byte[] hostBytes = intent.getData().getHost().getBytes();
4552        final byte[] digestBytes = digest.digest(hostBytes);
4553        int shaPrefix =
4554                digestBytes[0] << 24
4555                | digestBytes[1] << 16
4556                | digestBytes[2] << 8
4557                | digestBytes[3] << 0;
4558        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4559                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4560        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4561            // No hash prefix match; there are no ephemeral apps for this domain.
4562            return null;
4563        }
4564        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4565            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4566            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4567                continue;
4568            }
4569            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4570            // No filters; this should never happen.
4571            if (filters.isEmpty()) {
4572                continue;
4573            }
4574            // We have a domain match; resolve the filters to see if anything matches.
4575            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4576            for (int j = filters.size() - 1; j >= 0; --j) {
4577                final EphemeralResolveIntentInfo intentInfo =
4578                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4579                ephemeralResolver.addFilter(intentInfo);
4580            }
4581            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4582                    intent, resolvedType, false /*defaultOnly*/, userId);
4583            if (!matchedResolveInfoList.isEmpty()) {
4584                return matchedResolveInfoList.get(0);
4585            }
4586        }
4587        // Hash or filter mis-match; no ephemeral apps for this domain.
4588        return null;
4589    }
4590
4591    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4592            int flags, List<ResolveInfo> query, int userId) {
4593        if (query != null) {
4594            final int N = query.size();
4595            if (N == 1) {
4596                return query.get(0);
4597            } else if (N > 1) {
4598                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4599                // If there is more than one activity with the same priority,
4600                // then let the user decide between them.
4601                ResolveInfo r0 = query.get(0);
4602                ResolveInfo r1 = query.get(1);
4603                if (DEBUG_INTENT_MATCHING || debug) {
4604                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4605                            + r1.activityInfo.name + "=" + r1.priority);
4606                }
4607                // If the first activity has a higher priority, or a different
4608                // default, then it is always desirable to pick it.
4609                if (r0.priority != r1.priority
4610                        || r0.preferredOrder != r1.preferredOrder
4611                        || r0.isDefault != r1.isDefault) {
4612                    return query.get(0);
4613                }
4614                // If we have saved a preference for a preferred activity for
4615                // this Intent, use that.
4616                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4617                        flags, query, r0.priority, true, false, debug, userId);
4618                if (ri != null) {
4619                    return ri;
4620                }
4621                ri = new ResolveInfo(mResolveInfo);
4622                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4623                ri.activityInfo.applicationInfo = new ApplicationInfo(
4624                        ri.activityInfo.applicationInfo);
4625                if (userId != 0) {
4626                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4627                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4628                }
4629                // Make sure that the resolver is displayable in car mode
4630                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4631                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4632                return ri;
4633            }
4634        }
4635        return null;
4636    }
4637
4638    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4639            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4640        final int N = query.size();
4641        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4642                .get(userId);
4643        // Get the list of persistent preferred activities that handle the intent
4644        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4645        List<PersistentPreferredActivity> pprefs = ppir != null
4646                ? ppir.queryIntent(intent, resolvedType,
4647                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4648                : null;
4649        if (pprefs != null && pprefs.size() > 0) {
4650            final int M = pprefs.size();
4651            for (int i=0; i<M; i++) {
4652                final PersistentPreferredActivity ppa = pprefs.get(i);
4653                if (DEBUG_PREFERRED || debug) {
4654                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4655                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4656                            + "\n  component=" + ppa.mComponent);
4657                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4658                }
4659                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4660                        flags | MATCH_DISABLED_COMPONENTS, userId);
4661                if (DEBUG_PREFERRED || debug) {
4662                    Slog.v(TAG, "Found persistent preferred activity:");
4663                    if (ai != null) {
4664                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4665                    } else {
4666                        Slog.v(TAG, "  null");
4667                    }
4668                }
4669                if (ai == null) {
4670                    // This previously registered persistent preferred activity
4671                    // component is no longer known. Ignore it and do NOT remove it.
4672                    continue;
4673                }
4674                for (int j=0; j<N; j++) {
4675                    final ResolveInfo ri = query.get(j);
4676                    if (!ri.activityInfo.applicationInfo.packageName
4677                            .equals(ai.applicationInfo.packageName)) {
4678                        continue;
4679                    }
4680                    if (!ri.activityInfo.name.equals(ai.name)) {
4681                        continue;
4682                    }
4683                    //  Found a persistent preference that can handle the intent.
4684                    if (DEBUG_PREFERRED || debug) {
4685                        Slog.v(TAG, "Returning persistent preferred activity: " +
4686                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4687                    }
4688                    return ri;
4689                }
4690            }
4691        }
4692        return null;
4693    }
4694
4695    // TODO: handle preferred activities missing while user has amnesia
4696    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4697            List<ResolveInfo> query, int priority, boolean always,
4698            boolean removeMatches, boolean debug, int userId) {
4699        if (!sUserManager.exists(userId)) return null;
4700        flags = updateFlagsForResolve(flags, userId, intent);
4701        // writer
4702        synchronized (mPackages) {
4703            if (intent.getSelector() != null) {
4704                intent = intent.getSelector();
4705            }
4706            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4707
4708            // Try to find a matching persistent preferred activity.
4709            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4710                    debug, userId);
4711
4712            // If a persistent preferred activity matched, use it.
4713            if (pri != null) {
4714                return pri;
4715            }
4716
4717            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4718            // Get the list of preferred activities that handle the intent
4719            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4720            List<PreferredActivity> prefs = pir != null
4721                    ? pir.queryIntent(intent, resolvedType,
4722                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4723                    : null;
4724            if (prefs != null && prefs.size() > 0) {
4725                boolean changed = false;
4726                try {
4727                    // First figure out how good the original match set is.
4728                    // We will only allow preferred activities that came
4729                    // from the same match quality.
4730                    int match = 0;
4731
4732                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4733
4734                    final int N = query.size();
4735                    for (int j=0; j<N; j++) {
4736                        final ResolveInfo ri = query.get(j);
4737                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4738                                + ": 0x" + Integer.toHexString(match));
4739                        if (ri.match > match) {
4740                            match = ri.match;
4741                        }
4742                    }
4743
4744                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4745                            + Integer.toHexString(match));
4746
4747                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4748                    final int M = prefs.size();
4749                    for (int i=0; i<M; i++) {
4750                        final PreferredActivity pa = prefs.get(i);
4751                        if (DEBUG_PREFERRED || debug) {
4752                            Slog.v(TAG, "Checking PreferredActivity ds="
4753                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4754                                    + "\n  component=" + pa.mPref.mComponent);
4755                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4756                        }
4757                        if (pa.mPref.mMatch != match) {
4758                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4759                                    + Integer.toHexString(pa.mPref.mMatch));
4760                            continue;
4761                        }
4762                        // If it's not an "always" type preferred activity and that's what we're
4763                        // looking for, skip it.
4764                        if (always && !pa.mPref.mAlways) {
4765                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4766                            continue;
4767                        }
4768                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4769                                flags | MATCH_DISABLED_COMPONENTS, userId);
4770                        if (DEBUG_PREFERRED || debug) {
4771                            Slog.v(TAG, "Found preferred activity:");
4772                            if (ai != null) {
4773                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4774                            } else {
4775                                Slog.v(TAG, "  null");
4776                            }
4777                        }
4778                        if (ai == null) {
4779                            // This previously registered preferred activity
4780                            // component is no longer known.  Most likely an update
4781                            // to the app was installed and in the new version this
4782                            // component no longer exists.  Clean it up by removing
4783                            // it from the preferred activities list, and skip it.
4784                            Slog.w(TAG, "Removing dangling preferred activity: "
4785                                    + pa.mPref.mComponent);
4786                            pir.removeFilter(pa);
4787                            changed = true;
4788                            continue;
4789                        }
4790                        for (int j=0; j<N; j++) {
4791                            final ResolveInfo ri = query.get(j);
4792                            if (!ri.activityInfo.applicationInfo.packageName
4793                                    .equals(ai.applicationInfo.packageName)) {
4794                                continue;
4795                            }
4796                            if (!ri.activityInfo.name.equals(ai.name)) {
4797                                continue;
4798                            }
4799
4800                            if (removeMatches) {
4801                                pir.removeFilter(pa);
4802                                changed = true;
4803                                if (DEBUG_PREFERRED) {
4804                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4805                                }
4806                                break;
4807                            }
4808
4809                            // Okay we found a previously set preferred or last chosen app.
4810                            // If the result set is different from when this
4811                            // was created, we need to clear it and re-ask the
4812                            // user their preference, if we're looking for an "always" type entry.
4813                            if (always && !pa.mPref.sameSet(query)) {
4814                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4815                                        + intent + " type " + resolvedType);
4816                                if (DEBUG_PREFERRED) {
4817                                    Slog.v(TAG, "Removing preferred activity since set changed "
4818                                            + pa.mPref.mComponent);
4819                                }
4820                                pir.removeFilter(pa);
4821                                // Re-add the filter as a "last chosen" entry (!always)
4822                                PreferredActivity lastChosen = new PreferredActivity(
4823                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4824                                pir.addFilter(lastChosen);
4825                                changed = true;
4826                                return null;
4827                            }
4828
4829                            // Yay! Either the set matched or we're looking for the last chosen
4830                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4831                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4832                            return ri;
4833                        }
4834                    }
4835                } finally {
4836                    if (changed) {
4837                        if (DEBUG_PREFERRED) {
4838                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4839                        }
4840                        scheduleWritePackageRestrictionsLocked(userId);
4841                    }
4842                }
4843            }
4844        }
4845        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4846        return null;
4847    }
4848
4849    /*
4850     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4851     */
4852    @Override
4853    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4854            int targetUserId) {
4855        mContext.enforceCallingOrSelfPermission(
4856                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4857        List<CrossProfileIntentFilter> matches =
4858                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4859        if (matches != null) {
4860            int size = matches.size();
4861            for (int i = 0; i < size; i++) {
4862                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4863            }
4864        }
4865        if (hasWebURI(intent)) {
4866            // cross-profile app linking works only towards the parent.
4867            final UserInfo parent = getProfileParent(sourceUserId);
4868            synchronized(mPackages) {
4869                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4870                        intent, resolvedType, 0, sourceUserId, parent.id);
4871                return xpDomainInfo != null;
4872            }
4873        }
4874        return false;
4875    }
4876
4877    private UserInfo getProfileParent(int userId) {
4878        final long identity = Binder.clearCallingIdentity();
4879        try {
4880            return sUserManager.getProfileParent(userId);
4881        } finally {
4882            Binder.restoreCallingIdentity(identity);
4883        }
4884    }
4885
4886    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4887            String resolvedType, int userId) {
4888        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4889        if (resolver != null) {
4890            return resolver.queryIntent(intent, resolvedType, false, userId);
4891        }
4892        return null;
4893    }
4894
4895    @Override
4896    public List<ResolveInfo> queryIntentActivities(Intent intent,
4897            String resolvedType, int flags, int userId) {
4898        if (!sUserManager.exists(userId)) return Collections.emptyList();
4899        flags = updateFlagsForResolve(flags, userId, intent);
4900        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4901        ComponentName comp = intent.getComponent();
4902        if (comp == null) {
4903            if (intent.getSelector() != null) {
4904                intent = intent.getSelector();
4905                comp = intent.getComponent();
4906            }
4907        }
4908
4909        if (comp != null) {
4910            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4911            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4912            if (ai != null) {
4913                final ResolveInfo ri = new ResolveInfo();
4914                ri.activityInfo = ai;
4915                list.add(ri);
4916            }
4917            return list;
4918        }
4919
4920        // reader
4921        synchronized (mPackages) {
4922            final String pkgName = intent.getPackage();
4923            if (pkgName == null) {
4924                List<CrossProfileIntentFilter> matchingFilters =
4925                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4926                // Check for results that need to skip the current profile.
4927                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4928                        resolvedType, flags, userId);
4929                if (xpResolveInfo != null) {
4930                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4931                    result.add(xpResolveInfo);
4932                    return filterIfNotSystemUser(result, userId);
4933                }
4934
4935                // Check for results in the current profile.
4936                List<ResolveInfo> result = mActivities.queryIntent(
4937                        intent, resolvedType, flags, userId);
4938                result = filterIfNotSystemUser(result, userId);
4939
4940                // Check for cross profile results.
4941                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4942                xpResolveInfo = queryCrossProfileIntents(
4943                        matchingFilters, intent, resolvedType, flags, userId,
4944                        hasNonNegativePriorityResult);
4945                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4946                    boolean isVisibleToUser = filterIfNotSystemUser(
4947                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4948                    if (isVisibleToUser) {
4949                        result.add(xpResolveInfo);
4950                        Collections.sort(result, mResolvePrioritySorter);
4951                    }
4952                }
4953                if (hasWebURI(intent)) {
4954                    CrossProfileDomainInfo xpDomainInfo = null;
4955                    final UserInfo parent = getProfileParent(userId);
4956                    if (parent != null) {
4957                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4958                                flags, userId, parent.id);
4959                    }
4960                    if (xpDomainInfo != null) {
4961                        if (xpResolveInfo != null) {
4962                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4963                            // in the result.
4964                            result.remove(xpResolveInfo);
4965                        }
4966                        if (result.size() == 0) {
4967                            result.add(xpDomainInfo.resolveInfo);
4968                            return result;
4969                        }
4970                    } else if (result.size() <= 1) {
4971                        return result;
4972                    }
4973                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4974                            xpDomainInfo, userId);
4975                    Collections.sort(result, mResolvePrioritySorter);
4976                }
4977                return result;
4978            }
4979            final PackageParser.Package pkg = mPackages.get(pkgName);
4980            if (pkg != null) {
4981                return filterIfNotSystemUser(
4982                        mActivities.queryIntentForPackage(
4983                                intent, resolvedType, flags, pkg.activities, userId),
4984                        userId);
4985            }
4986            return new ArrayList<ResolveInfo>();
4987        }
4988    }
4989
4990    private static class CrossProfileDomainInfo {
4991        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4992        ResolveInfo resolveInfo;
4993        /* Best domain verification status of the activities found in the other profile */
4994        int bestDomainVerificationStatus;
4995    }
4996
4997    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4998            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4999        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5000                sourceUserId)) {
5001            return null;
5002        }
5003        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5004                resolvedType, flags, parentUserId);
5005
5006        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5007            return null;
5008        }
5009        CrossProfileDomainInfo result = null;
5010        int size = resultTargetUser.size();
5011        for (int i = 0; i < size; i++) {
5012            ResolveInfo riTargetUser = resultTargetUser.get(i);
5013            // Intent filter verification is only for filters that specify a host. So don't return
5014            // those that handle all web uris.
5015            if (riTargetUser.handleAllWebDataURI) {
5016                continue;
5017            }
5018            String packageName = riTargetUser.activityInfo.packageName;
5019            PackageSetting ps = mSettings.mPackages.get(packageName);
5020            if (ps == null) {
5021                continue;
5022            }
5023            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5024            int status = (int)(verificationState >> 32);
5025            if (result == null) {
5026                result = new CrossProfileDomainInfo();
5027                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5028                        sourceUserId, parentUserId);
5029                result.bestDomainVerificationStatus = status;
5030            } else {
5031                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5032                        result.bestDomainVerificationStatus);
5033            }
5034        }
5035        // Don't consider matches with status NEVER across profiles.
5036        if (result != null && result.bestDomainVerificationStatus
5037                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5038            return null;
5039        }
5040        return result;
5041    }
5042
5043    /**
5044     * Verification statuses are ordered from the worse to the best, except for
5045     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5046     */
5047    private int bestDomainVerificationStatus(int status1, int status2) {
5048        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5049            return status2;
5050        }
5051        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5052            return status1;
5053        }
5054        return (int) MathUtils.max(status1, status2);
5055    }
5056
5057    private boolean isUserEnabled(int userId) {
5058        long callingId = Binder.clearCallingIdentity();
5059        try {
5060            UserInfo userInfo = sUserManager.getUserInfo(userId);
5061            return userInfo != null && userInfo.isEnabled();
5062        } finally {
5063            Binder.restoreCallingIdentity(callingId);
5064        }
5065    }
5066
5067    /**
5068     * Filter out activities with systemUserOnly flag set, when current user is not System.
5069     *
5070     * @return filtered list
5071     */
5072    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5073        if (userId == UserHandle.USER_SYSTEM) {
5074            return resolveInfos;
5075        }
5076        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5077            ResolveInfo info = resolveInfos.get(i);
5078            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5079                resolveInfos.remove(i);
5080            }
5081        }
5082        return resolveInfos;
5083    }
5084
5085    /**
5086     * @param resolveInfos list of resolve infos in descending priority order
5087     * @return if the list contains a resolve info with non-negative priority
5088     */
5089    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5090        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5091    }
5092
5093    private static boolean hasWebURI(Intent intent) {
5094        if (intent.getData() == null) {
5095            return false;
5096        }
5097        final String scheme = intent.getScheme();
5098        if (TextUtils.isEmpty(scheme)) {
5099            return false;
5100        }
5101        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5102    }
5103
5104    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5105            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5106            int userId) {
5107        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5108
5109        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5110            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5111                    candidates.size());
5112        }
5113
5114        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5115        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5116        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5117        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5118        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5119        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5120
5121        synchronized (mPackages) {
5122            final int count = candidates.size();
5123            // First, try to use linked apps. Partition the candidates into four lists:
5124            // one for the final results, one for the "do not use ever", one for "undefined status"
5125            // and finally one for "browser app type".
5126            for (int n=0; n<count; n++) {
5127                ResolveInfo info = candidates.get(n);
5128                String packageName = info.activityInfo.packageName;
5129                PackageSetting ps = mSettings.mPackages.get(packageName);
5130                if (ps != null) {
5131                    // Add to the special match all list (Browser use case)
5132                    if (info.handleAllWebDataURI) {
5133                        matchAllList.add(info);
5134                        continue;
5135                    }
5136                    // Try to get the status from User settings first
5137                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5138                    int status = (int)(packedStatus >> 32);
5139                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5140                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5141                        if (DEBUG_DOMAIN_VERIFICATION) {
5142                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5143                                    + " : linkgen=" + linkGeneration);
5144                        }
5145                        // Use link-enabled generation as preferredOrder, i.e.
5146                        // prefer newly-enabled over earlier-enabled.
5147                        info.preferredOrder = linkGeneration;
5148                        alwaysList.add(info);
5149                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5150                        if (DEBUG_DOMAIN_VERIFICATION) {
5151                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5152                        }
5153                        neverList.add(info);
5154                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5155                        if (DEBUG_DOMAIN_VERIFICATION) {
5156                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5157                        }
5158                        alwaysAskList.add(info);
5159                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5160                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5161                        if (DEBUG_DOMAIN_VERIFICATION) {
5162                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5163                        }
5164                        undefinedList.add(info);
5165                    }
5166                }
5167            }
5168
5169            // We'll want to include browser possibilities in a few cases
5170            boolean includeBrowser = false;
5171
5172            // First try to add the "always" resolution(s) for the current user, if any
5173            if (alwaysList.size() > 0) {
5174                result.addAll(alwaysList);
5175            } else {
5176                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5177                result.addAll(undefinedList);
5178                // Maybe add one for the other profile.
5179                if (xpDomainInfo != null && (
5180                        xpDomainInfo.bestDomainVerificationStatus
5181                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5182                    result.add(xpDomainInfo.resolveInfo);
5183                }
5184                includeBrowser = true;
5185            }
5186
5187            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5188            // If there were 'always' entries their preferred order has been set, so we also
5189            // back that off to make the alternatives equivalent
5190            if (alwaysAskList.size() > 0) {
5191                for (ResolveInfo i : result) {
5192                    i.preferredOrder = 0;
5193                }
5194                result.addAll(alwaysAskList);
5195                includeBrowser = true;
5196            }
5197
5198            if (includeBrowser) {
5199                // Also add browsers (all of them or only the default one)
5200                if (DEBUG_DOMAIN_VERIFICATION) {
5201                    Slog.v(TAG, "   ...including browsers in candidate set");
5202                }
5203                if ((matchFlags & MATCH_ALL) != 0) {
5204                    result.addAll(matchAllList);
5205                } else {
5206                    // Browser/generic handling case.  If there's a default browser, go straight
5207                    // to that (but only if there is no other higher-priority match).
5208                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5209                    int maxMatchPrio = 0;
5210                    ResolveInfo defaultBrowserMatch = null;
5211                    final int numCandidates = matchAllList.size();
5212                    for (int n = 0; n < numCandidates; n++) {
5213                        ResolveInfo info = matchAllList.get(n);
5214                        // track the highest overall match priority...
5215                        if (info.priority > maxMatchPrio) {
5216                            maxMatchPrio = info.priority;
5217                        }
5218                        // ...and the highest-priority default browser match
5219                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5220                            if (defaultBrowserMatch == null
5221                                    || (defaultBrowserMatch.priority < info.priority)) {
5222                                if (debug) {
5223                                    Slog.v(TAG, "Considering default browser match " + info);
5224                                }
5225                                defaultBrowserMatch = info;
5226                            }
5227                        }
5228                    }
5229                    if (defaultBrowserMatch != null
5230                            && defaultBrowserMatch.priority >= maxMatchPrio
5231                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5232                    {
5233                        if (debug) {
5234                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5235                        }
5236                        result.add(defaultBrowserMatch);
5237                    } else {
5238                        result.addAll(matchAllList);
5239                    }
5240                }
5241
5242                // If there is nothing selected, add all candidates and remove the ones that the user
5243                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5244                if (result.size() == 0) {
5245                    result.addAll(candidates);
5246                    result.removeAll(neverList);
5247                }
5248            }
5249        }
5250        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5251            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5252                    result.size());
5253            for (ResolveInfo info : result) {
5254                Slog.v(TAG, "  + " + info.activityInfo);
5255            }
5256        }
5257        return result;
5258    }
5259
5260    // Returns a packed value as a long:
5261    //
5262    // high 'int'-sized word: link status: undefined/ask/never/always.
5263    // low 'int'-sized word: relative priority among 'always' results.
5264    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5265        long result = ps.getDomainVerificationStatusForUser(userId);
5266        // if none available, get the master status
5267        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5268            if (ps.getIntentFilterVerificationInfo() != null) {
5269                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5270            }
5271        }
5272        return result;
5273    }
5274
5275    private ResolveInfo querySkipCurrentProfileIntents(
5276            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5277            int flags, int sourceUserId) {
5278        if (matchingFilters != null) {
5279            int size = matchingFilters.size();
5280            for (int i = 0; i < size; i ++) {
5281                CrossProfileIntentFilter filter = matchingFilters.get(i);
5282                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5283                    // Checking if there are activities in the target user that can handle the
5284                    // intent.
5285                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5286                            resolvedType, flags, sourceUserId);
5287                    if (resolveInfo != null) {
5288                        return resolveInfo;
5289                    }
5290                }
5291            }
5292        }
5293        return null;
5294    }
5295
5296    // Return matching ResolveInfo in target user if any.
5297    private ResolveInfo queryCrossProfileIntents(
5298            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5299            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5300        if (matchingFilters != null) {
5301            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5302            // match the same intent. For performance reasons, it is better not to
5303            // run queryIntent twice for the same userId
5304            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5305            int size = matchingFilters.size();
5306            for (int i = 0; i < size; i++) {
5307                CrossProfileIntentFilter filter = matchingFilters.get(i);
5308                int targetUserId = filter.getTargetUserId();
5309                boolean skipCurrentProfile =
5310                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5311                boolean skipCurrentProfileIfNoMatchFound =
5312                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5313                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5314                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5315                    // Checking if there are activities in the target user that can handle the
5316                    // intent.
5317                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5318                            resolvedType, flags, sourceUserId);
5319                    if (resolveInfo != null) return resolveInfo;
5320                    alreadyTriedUserIds.put(targetUserId, true);
5321                }
5322            }
5323        }
5324        return null;
5325    }
5326
5327    /**
5328     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5329     * will forward the intent to the filter's target user.
5330     * Otherwise, returns null.
5331     */
5332    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5333            String resolvedType, int flags, int sourceUserId) {
5334        int targetUserId = filter.getTargetUserId();
5335        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5336                resolvedType, flags, targetUserId);
5337        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5338                && isUserEnabled(targetUserId)) {
5339            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5340        }
5341        return null;
5342    }
5343
5344    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5345            int sourceUserId, int targetUserId) {
5346        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5347        long ident = Binder.clearCallingIdentity();
5348        boolean targetIsProfile;
5349        try {
5350            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5351        } finally {
5352            Binder.restoreCallingIdentity(ident);
5353        }
5354        String className;
5355        if (targetIsProfile) {
5356            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5357        } else {
5358            className = FORWARD_INTENT_TO_PARENT;
5359        }
5360        ComponentName forwardingActivityComponentName = new ComponentName(
5361                mAndroidApplication.packageName, className);
5362        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5363                sourceUserId);
5364        if (!targetIsProfile) {
5365            forwardingActivityInfo.showUserIcon = targetUserId;
5366            forwardingResolveInfo.noResourceId = true;
5367        }
5368        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5369        forwardingResolveInfo.priority = 0;
5370        forwardingResolveInfo.preferredOrder = 0;
5371        forwardingResolveInfo.match = 0;
5372        forwardingResolveInfo.isDefault = true;
5373        forwardingResolveInfo.filter = filter;
5374        forwardingResolveInfo.targetUserId = targetUserId;
5375        return forwardingResolveInfo;
5376    }
5377
5378    @Override
5379    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5380            Intent[] specifics, String[] specificTypes, Intent intent,
5381            String resolvedType, int flags, int userId) {
5382        if (!sUserManager.exists(userId)) return Collections.emptyList();
5383        flags = updateFlagsForResolve(flags, userId, intent);
5384        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5385                false, "query intent activity options");
5386        final String resultsAction = intent.getAction();
5387
5388        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5389                | PackageManager.GET_RESOLVED_FILTER, userId);
5390
5391        if (DEBUG_INTENT_MATCHING) {
5392            Log.v(TAG, "Query " + intent + ": " + results);
5393        }
5394
5395        int specificsPos = 0;
5396        int N;
5397
5398        // todo: note that the algorithm used here is O(N^2).  This
5399        // isn't a problem in our current environment, but if we start running
5400        // into situations where we have more than 5 or 10 matches then this
5401        // should probably be changed to something smarter...
5402
5403        // First we go through and resolve each of the specific items
5404        // that were supplied, taking care of removing any corresponding
5405        // duplicate items in the generic resolve list.
5406        if (specifics != null) {
5407            for (int i=0; i<specifics.length; i++) {
5408                final Intent sintent = specifics[i];
5409                if (sintent == null) {
5410                    continue;
5411                }
5412
5413                if (DEBUG_INTENT_MATCHING) {
5414                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5415                }
5416
5417                String action = sintent.getAction();
5418                if (resultsAction != null && resultsAction.equals(action)) {
5419                    // If this action was explicitly requested, then don't
5420                    // remove things that have it.
5421                    action = null;
5422                }
5423
5424                ResolveInfo ri = null;
5425                ActivityInfo ai = null;
5426
5427                ComponentName comp = sintent.getComponent();
5428                if (comp == null) {
5429                    ri = resolveIntent(
5430                        sintent,
5431                        specificTypes != null ? specificTypes[i] : null,
5432                            flags, userId);
5433                    if (ri == null) {
5434                        continue;
5435                    }
5436                    if (ri == mResolveInfo) {
5437                        // ACK!  Must do something better with this.
5438                    }
5439                    ai = ri.activityInfo;
5440                    comp = new ComponentName(ai.applicationInfo.packageName,
5441                            ai.name);
5442                } else {
5443                    ai = getActivityInfo(comp, flags, userId);
5444                    if (ai == null) {
5445                        continue;
5446                    }
5447                }
5448
5449                // Look for any generic query activities that are duplicates
5450                // of this specific one, and remove them from the results.
5451                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5452                N = results.size();
5453                int j;
5454                for (j=specificsPos; j<N; j++) {
5455                    ResolveInfo sri = results.get(j);
5456                    if ((sri.activityInfo.name.equals(comp.getClassName())
5457                            && sri.activityInfo.applicationInfo.packageName.equals(
5458                                    comp.getPackageName()))
5459                        || (action != null && sri.filter.matchAction(action))) {
5460                        results.remove(j);
5461                        if (DEBUG_INTENT_MATCHING) Log.v(
5462                            TAG, "Removing duplicate item from " + j
5463                            + " due to specific " + specificsPos);
5464                        if (ri == null) {
5465                            ri = sri;
5466                        }
5467                        j--;
5468                        N--;
5469                    }
5470                }
5471
5472                // Add this specific item to its proper place.
5473                if (ri == null) {
5474                    ri = new ResolveInfo();
5475                    ri.activityInfo = ai;
5476                }
5477                results.add(specificsPos, ri);
5478                ri.specificIndex = i;
5479                specificsPos++;
5480            }
5481        }
5482
5483        // Now we go through the remaining generic results and remove any
5484        // duplicate actions that are found here.
5485        N = results.size();
5486        for (int i=specificsPos; i<N-1; i++) {
5487            final ResolveInfo rii = results.get(i);
5488            if (rii.filter == null) {
5489                continue;
5490            }
5491
5492            // Iterate over all of the actions of this result's intent
5493            // filter...  typically this should be just one.
5494            final Iterator<String> it = rii.filter.actionsIterator();
5495            if (it == null) {
5496                continue;
5497            }
5498            while (it.hasNext()) {
5499                final String action = it.next();
5500                if (resultsAction != null && resultsAction.equals(action)) {
5501                    // If this action was explicitly requested, then don't
5502                    // remove things that have it.
5503                    continue;
5504                }
5505                for (int j=i+1; j<N; j++) {
5506                    final ResolveInfo rij = results.get(j);
5507                    if (rij.filter != null && rij.filter.hasAction(action)) {
5508                        results.remove(j);
5509                        if (DEBUG_INTENT_MATCHING) Log.v(
5510                            TAG, "Removing duplicate item from " + j
5511                            + " due to action " + action + " at " + i);
5512                        j--;
5513                        N--;
5514                    }
5515                }
5516            }
5517
5518            // If the caller didn't request filter information, drop it now
5519            // so we don't have to marshall/unmarshall it.
5520            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5521                rii.filter = null;
5522            }
5523        }
5524
5525        // Filter out the caller activity if so requested.
5526        if (caller != null) {
5527            N = results.size();
5528            for (int i=0; i<N; i++) {
5529                ActivityInfo ainfo = results.get(i).activityInfo;
5530                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5531                        && caller.getClassName().equals(ainfo.name)) {
5532                    results.remove(i);
5533                    break;
5534                }
5535            }
5536        }
5537
5538        // If the caller didn't request filter information,
5539        // drop them now so we don't have to
5540        // marshall/unmarshall it.
5541        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5542            N = results.size();
5543            for (int i=0; i<N; i++) {
5544                results.get(i).filter = null;
5545            }
5546        }
5547
5548        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5549        return results;
5550    }
5551
5552    @Override
5553    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5554            int userId) {
5555        if (!sUserManager.exists(userId)) return Collections.emptyList();
5556        flags = updateFlagsForResolve(flags, userId, intent);
5557        ComponentName comp = intent.getComponent();
5558        if (comp == null) {
5559            if (intent.getSelector() != null) {
5560                intent = intent.getSelector();
5561                comp = intent.getComponent();
5562            }
5563        }
5564        if (comp != null) {
5565            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5566            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5567            if (ai != null) {
5568                ResolveInfo ri = new ResolveInfo();
5569                ri.activityInfo = ai;
5570                list.add(ri);
5571            }
5572            return list;
5573        }
5574
5575        // reader
5576        synchronized (mPackages) {
5577            String pkgName = intent.getPackage();
5578            if (pkgName == null) {
5579                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5580            }
5581            final PackageParser.Package pkg = mPackages.get(pkgName);
5582            if (pkg != null) {
5583                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5584                        userId);
5585            }
5586            return null;
5587        }
5588    }
5589
5590    @Override
5591    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5592        if (!sUserManager.exists(userId)) return null;
5593        flags = updateFlagsForResolve(flags, userId, intent);
5594        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5595        if (query != null) {
5596            if (query.size() >= 1) {
5597                // If there is more than one service with the same priority,
5598                // just arbitrarily pick the first one.
5599                return query.get(0);
5600            }
5601        }
5602        return null;
5603    }
5604
5605    @Override
5606    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5607            int userId) {
5608        if (!sUserManager.exists(userId)) return Collections.emptyList();
5609        flags = updateFlagsForResolve(flags, userId, intent);
5610        ComponentName comp = intent.getComponent();
5611        if (comp == null) {
5612            if (intent.getSelector() != null) {
5613                intent = intent.getSelector();
5614                comp = intent.getComponent();
5615            }
5616        }
5617        if (comp != null) {
5618            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5619            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5620            if (si != null) {
5621                final ResolveInfo ri = new ResolveInfo();
5622                ri.serviceInfo = si;
5623                list.add(ri);
5624            }
5625            return list;
5626        }
5627
5628        // reader
5629        synchronized (mPackages) {
5630            String pkgName = intent.getPackage();
5631            if (pkgName == null) {
5632                return mServices.queryIntent(intent, resolvedType, flags, userId);
5633            }
5634            final PackageParser.Package pkg = mPackages.get(pkgName);
5635            if (pkg != null) {
5636                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5637                        userId);
5638            }
5639            return null;
5640        }
5641    }
5642
5643    @Override
5644    public List<ResolveInfo> queryIntentContentProviders(
5645            Intent intent, String resolvedType, int flags, int userId) {
5646        if (!sUserManager.exists(userId)) return Collections.emptyList();
5647        flags = updateFlagsForResolve(flags, userId, intent);
5648        ComponentName comp = intent.getComponent();
5649        if (comp == null) {
5650            if (intent.getSelector() != null) {
5651                intent = intent.getSelector();
5652                comp = intent.getComponent();
5653            }
5654        }
5655        if (comp != null) {
5656            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5657            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5658            if (pi != null) {
5659                final ResolveInfo ri = new ResolveInfo();
5660                ri.providerInfo = pi;
5661                list.add(ri);
5662            }
5663            return list;
5664        }
5665
5666        // reader
5667        synchronized (mPackages) {
5668            String pkgName = intent.getPackage();
5669            if (pkgName == null) {
5670                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5671            }
5672            final PackageParser.Package pkg = mPackages.get(pkgName);
5673            if (pkg != null) {
5674                return mProviders.queryIntentForPackage(
5675                        intent, resolvedType, flags, pkg.providers, userId);
5676            }
5677            return null;
5678        }
5679    }
5680
5681    @Override
5682    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5683        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5684        flags = updateFlagsForPackage(flags, userId, null);
5685        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5686        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5687
5688        // writer
5689        synchronized (mPackages) {
5690            ArrayList<PackageInfo> list;
5691            if (listUninstalled) {
5692                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5693                for (PackageSetting ps : mSettings.mPackages.values()) {
5694                    PackageInfo pi;
5695                    if (ps.pkg != null) {
5696                        pi = generatePackageInfo(ps.pkg, flags, userId);
5697                    } else {
5698                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5699                    }
5700                    if (pi != null) {
5701                        list.add(pi);
5702                    }
5703                }
5704            } else {
5705                list = new ArrayList<PackageInfo>(mPackages.size());
5706                for (PackageParser.Package p : mPackages.values()) {
5707                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5708                    if (pi != null) {
5709                        list.add(pi);
5710                    }
5711                }
5712            }
5713
5714            return new ParceledListSlice<PackageInfo>(list);
5715        }
5716    }
5717
5718    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5719            String[] permissions, boolean[] tmp, int flags, int userId) {
5720        int numMatch = 0;
5721        final PermissionsState permissionsState = ps.getPermissionsState();
5722        for (int i=0; i<permissions.length; i++) {
5723            final String permission = permissions[i];
5724            if (permissionsState.hasPermission(permission, userId)) {
5725                tmp[i] = true;
5726                numMatch++;
5727            } else {
5728                tmp[i] = false;
5729            }
5730        }
5731        if (numMatch == 0) {
5732            return;
5733        }
5734        PackageInfo pi;
5735        if (ps.pkg != null) {
5736            pi = generatePackageInfo(ps.pkg, flags, userId);
5737        } else {
5738            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5739        }
5740        // The above might return null in cases of uninstalled apps or install-state
5741        // skew across users/profiles.
5742        if (pi != null) {
5743            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5744                if (numMatch == permissions.length) {
5745                    pi.requestedPermissions = permissions;
5746                } else {
5747                    pi.requestedPermissions = new String[numMatch];
5748                    numMatch = 0;
5749                    for (int i=0; i<permissions.length; i++) {
5750                        if (tmp[i]) {
5751                            pi.requestedPermissions[numMatch] = permissions[i];
5752                            numMatch++;
5753                        }
5754                    }
5755                }
5756            }
5757            list.add(pi);
5758        }
5759    }
5760
5761    @Override
5762    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5763            String[] permissions, int flags, int userId) {
5764        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5765        flags = updateFlagsForPackage(flags, userId, permissions);
5766        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5767
5768        // writer
5769        synchronized (mPackages) {
5770            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5771            boolean[] tmpBools = new boolean[permissions.length];
5772            if (listUninstalled) {
5773                for (PackageSetting ps : mSettings.mPackages.values()) {
5774                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5775                }
5776            } else {
5777                for (PackageParser.Package pkg : mPackages.values()) {
5778                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5779                    if (ps != null) {
5780                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5781                                userId);
5782                    }
5783                }
5784            }
5785
5786            return new ParceledListSlice<PackageInfo>(list);
5787        }
5788    }
5789
5790    @Override
5791    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5792        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5793        flags = updateFlagsForApplication(flags, userId, null);
5794        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5795
5796        // writer
5797        synchronized (mPackages) {
5798            ArrayList<ApplicationInfo> list;
5799            if (listUninstalled) {
5800                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5801                for (PackageSetting ps : mSettings.mPackages.values()) {
5802                    ApplicationInfo ai;
5803                    if (ps.pkg != null) {
5804                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5805                                ps.readUserState(userId), userId);
5806                    } else {
5807                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5808                    }
5809                    if (ai != null) {
5810                        list.add(ai);
5811                    }
5812                }
5813            } else {
5814                list = new ArrayList<ApplicationInfo>(mPackages.size());
5815                for (PackageParser.Package p : mPackages.values()) {
5816                    if (p.mExtras != null) {
5817                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5818                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5819                        if (ai != null) {
5820                            list.add(ai);
5821                        }
5822                    }
5823                }
5824            }
5825
5826            return new ParceledListSlice<ApplicationInfo>(list);
5827        }
5828    }
5829
5830    @Override
5831    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5832        if (DISABLE_EPHEMERAL_APPS) {
5833            return null;
5834        }
5835
5836        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5837                "getEphemeralApplications");
5838        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5839                "getEphemeralApplications");
5840        synchronized (mPackages) {
5841            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5842                    .getEphemeralApplicationsLPw(userId);
5843            if (ephemeralApps != null) {
5844                return new ParceledListSlice<>(ephemeralApps);
5845            }
5846        }
5847        return null;
5848    }
5849
5850    @Override
5851    public boolean isEphemeralApplication(String packageName, int userId) {
5852        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5853                "isEphemeral");
5854        if (DISABLE_EPHEMERAL_APPS) {
5855            return false;
5856        }
5857
5858        if (!isCallerSameApp(packageName)) {
5859            return false;
5860        }
5861        synchronized (mPackages) {
5862            PackageParser.Package pkg = mPackages.get(packageName);
5863            if (pkg != null) {
5864                return pkg.applicationInfo.isEphemeralApp();
5865            }
5866        }
5867        return false;
5868    }
5869
5870    @Override
5871    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5872        if (DISABLE_EPHEMERAL_APPS) {
5873            return null;
5874        }
5875
5876        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5877                "getCookie");
5878        if (!isCallerSameApp(packageName)) {
5879            return null;
5880        }
5881        synchronized (mPackages) {
5882            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5883                    packageName, userId);
5884        }
5885    }
5886
5887    @Override
5888    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5889        if (DISABLE_EPHEMERAL_APPS) {
5890            return true;
5891        }
5892
5893        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5894                "setCookie");
5895        if (!isCallerSameApp(packageName)) {
5896            return false;
5897        }
5898        synchronized (mPackages) {
5899            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5900                    packageName, cookie, userId);
5901        }
5902    }
5903
5904    @Override
5905    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5906        if (DISABLE_EPHEMERAL_APPS) {
5907            return null;
5908        }
5909
5910        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5911                "getEphemeralApplicationIcon");
5912        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5913                "getEphemeralApplicationIcon");
5914        synchronized (mPackages) {
5915            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5916                    packageName, userId);
5917        }
5918    }
5919
5920    private boolean isCallerSameApp(String packageName) {
5921        PackageParser.Package pkg = mPackages.get(packageName);
5922        return pkg != null
5923                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5924    }
5925
5926    public List<ApplicationInfo> getPersistentApplications(int flags) {
5927        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5928
5929        // reader
5930        synchronized (mPackages) {
5931            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5932            final int userId = UserHandle.getCallingUserId();
5933            while (i.hasNext()) {
5934                final PackageParser.Package p = i.next();
5935                if (p.applicationInfo != null
5936                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5937                        && (!mSafeMode || isSystemApp(p))) {
5938                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5939                    if (ps != null) {
5940                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5941                                ps.readUserState(userId), userId);
5942                        if (ai != null) {
5943                            finalList.add(ai);
5944                        }
5945                    }
5946                }
5947            }
5948        }
5949
5950        return finalList;
5951    }
5952
5953    @Override
5954    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5955        if (!sUserManager.exists(userId)) return null;
5956        flags = updateFlagsForComponent(flags, userId, name);
5957        // reader
5958        synchronized (mPackages) {
5959            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5960            PackageSetting ps = provider != null
5961                    ? mSettings.mPackages.get(provider.owner.packageName)
5962                    : null;
5963            return ps != null
5964                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5965                    ? PackageParser.generateProviderInfo(provider, flags,
5966                            ps.readUserState(userId), userId)
5967                    : null;
5968        }
5969    }
5970
5971    /**
5972     * @deprecated
5973     */
5974    @Deprecated
5975    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5976        // reader
5977        synchronized (mPackages) {
5978            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5979                    .entrySet().iterator();
5980            final int userId = UserHandle.getCallingUserId();
5981            while (i.hasNext()) {
5982                Map.Entry<String, PackageParser.Provider> entry = i.next();
5983                PackageParser.Provider p = entry.getValue();
5984                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5985
5986                if (ps != null && p.syncable
5987                        && (!mSafeMode || (p.info.applicationInfo.flags
5988                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5989                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5990                            ps.readUserState(userId), userId);
5991                    if (info != null) {
5992                        outNames.add(entry.getKey());
5993                        outInfo.add(info);
5994                    }
5995                }
5996            }
5997        }
5998    }
5999
6000    @Override
6001    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6002            int uid, int flags) {
6003        final int userId = processName != null ? UserHandle.getUserId(uid)
6004                : UserHandle.getCallingUserId();
6005        if (!sUserManager.exists(userId)) return null;
6006        flags = updateFlagsForComponent(flags, userId, processName);
6007
6008        ArrayList<ProviderInfo> finalList = null;
6009        // reader
6010        synchronized (mPackages) {
6011            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6012            while (i.hasNext()) {
6013                final PackageParser.Provider p = i.next();
6014                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6015                if (ps != null && p.info.authority != null
6016                        && (processName == null
6017                                || (p.info.processName.equals(processName)
6018                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6019                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6020                    if (finalList == null) {
6021                        finalList = new ArrayList<ProviderInfo>(3);
6022                    }
6023                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6024                            ps.readUserState(userId), userId);
6025                    if (info != null) {
6026                        finalList.add(info);
6027                    }
6028                }
6029            }
6030        }
6031
6032        if (finalList != null) {
6033            Collections.sort(finalList, mProviderInitOrderSorter);
6034            return new ParceledListSlice<ProviderInfo>(finalList);
6035        }
6036
6037        return null;
6038    }
6039
6040    @Override
6041    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6042        // reader
6043        synchronized (mPackages) {
6044            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6045            return PackageParser.generateInstrumentationInfo(i, flags);
6046        }
6047    }
6048
6049    @Override
6050    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6051            int flags) {
6052        ArrayList<InstrumentationInfo> finalList =
6053            new ArrayList<InstrumentationInfo>();
6054
6055        // reader
6056        synchronized (mPackages) {
6057            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6058            while (i.hasNext()) {
6059                final PackageParser.Instrumentation p = i.next();
6060                if (targetPackage == null
6061                        || targetPackage.equals(p.info.targetPackage)) {
6062                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6063                            flags);
6064                    if (ii != null) {
6065                        finalList.add(ii);
6066                    }
6067                }
6068            }
6069        }
6070
6071        return finalList;
6072    }
6073
6074    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6075        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6076        if (overlays == null) {
6077            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6078            return;
6079        }
6080        for (PackageParser.Package opkg : overlays.values()) {
6081            // Not much to do if idmap fails: we already logged the error
6082            // and we certainly don't want to abort installation of pkg simply
6083            // because an overlay didn't fit properly. For these reasons,
6084            // ignore the return value of createIdmapForPackagePairLI.
6085            createIdmapForPackagePairLI(pkg, opkg);
6086        }
6087    }
6088
6089    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6090            PackageParser.Package opkg) {
6091        if (!opkg.mTrustedOverlay) {
6092            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6093                    opkg.baseCodePath + ": overlay not trusted");
6094            return false;
6095        }
6096        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6097        if (overlaySet == null) {
6098            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6099                    opkg.baseCodePath + " but target package has no known overlays");
6100            return false;
6101        }
6102        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6103        // TODO: generate idmap for split APKs
6104        try {
6105            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6106        } catch (InstallerException e) {
6107            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6108                    + opkg.baseCodePath);
6109            return false;
6110        }
6111        PackageParser.Package[] overlayArray =
6112            overlaySet.values().toArray(new PackageParser.Package[0]);
6113        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6114            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6115                return p1.mOverlayPriority - p2.mOverlayPriority;
6116            }
6117        };
6118        Arrays.sort(overlayArray, cmp);
6119
6120        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6121        int i = 0;
6122        for (PackageParser.Package p : overlayArray) {
6123            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6124        }
6125        return true;
6126    }
6127
6128    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6129        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6130        try {
6131            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6132        } finally {
6133            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6134        }
6135    }
6136
6137    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6138        final File[] files = dir.listFiles();
6139        if (ArrayUtils.isEmpty(files)) {
6140            Log.d(TAG, "No files in app dir " + dir);
6141            return;
6142        }
6143
6144        if (DEBUG_PACKAGE_SCANNING) {
6145            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6146                    + " flags=0x" + Integer.toHexString(parseFlags));
6147        }
6148
6149        for (File file : files) {
6150            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6151                    && !PackageInstallerService.isStageName(file.getName());
6152            if (!isPackage) {
6153                // Ignore entries which are not packages
6154                continue;
6155            }
6156            try {
6157                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6158                        scanFlags, currentTime, null);
6159            } catch (PackageManagerException e) {
6160                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6161
6162                // Delete invalid userdata apps
6163                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6164                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6165                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6166                    removeCodePathLI(file);
6167                }
6168            }
6169        }
6170    }
6171
6172    private static File getSettingsProblemFile() {
6173        File dataDir = Environment.getDataDirectory();
6174        File systemDir = new File(dataDir, "system");
6175        File fname = new File(systemDir, "uiderrors.txt");
6176        return fname;
6177    }
6178
6179    static void reportSettingsProblem(int priority, String msg) {
6180        logCriticalInfo(priority, msg);
6181    }
6182
6183    static void logCriticalInfo(int priority, String msg) {
6184        Slog.println(priority, TAG, msg);
6185        EventLogTags.writePmCriticalInfo(msg);
6186        try {
6187            File fname = getSettingsProblemFile();
6188            FileOutputStream out = new FileOutputStream(fname, true);
6189            PrintWriter pw = new FastPrintWriter(out);
6190            SimpleDateFormat formatter = new SimpleDateFormat();
6191            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6192            pw.println(dateString + ": " + msg);
6193            pw.close();
6194            FileUtils.setPermissions(
6195                    fname.toString(),
6196                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6197                    -1, -1);
6198        } catch (java.io.IOException e) {
6199        }
6200    }
6201
6202    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6203            PackageParser.Package pkg, File srcFile, int parseFlags)
6204            throws PackageManagerException {
6205        if (ps != null
6206                && ps.codePath.equals(srcFile)
6207                && ps.timeStamp == srcFile.lastModified()
6208                && !isCompatSignatureUpdateNeeded(pkg)
6209                && !isRecoverSignatureUpdateNeeded(pkg)) {
6210            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6211            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6212            ArraySet<PublicKey> signingKs;
6213            synchronized (mPackages) {
6214                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6215            }
6216            if (ps.signatures.mSignatures != null
6217                    && ps.signatures.mSignatures.length != 0
6218                    && signingKs != null) {
6219                // Optimization: reuse the existing cached certificates
6220                // if the package appears to be unchanged.
6221                pkg.mSignatures = ps.signatures.mSignatures;
6222                pkg.mSigningKeys = signingKs;
6223                return;
6224            }
6225
6226            Slog.w(TAG, "PackageSetting for " + ps.name
6227                    + " is missing signatures.  Collecting certs again to recover them.");
6228        } else {
6229            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6230        }
6231
6232        try {
6233            pp.collectCertificates(pkg, parseFlags);
6234        } catch (PackageParserException e) {
6235            throw PackageManagerException.from(e);
6236        }
6237    }
6238
6239    /**
6240     *  Traces a package scan.
6241     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6242     */
6243    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6244            long currentTime, UserHandle user) throws PackageManagerException {
6245        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6246        try {
6247            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6248        } finally {
6249            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6250        }
6251    }
6252
6253    /**
6254     *  Scans a package and returns the newly parsed package.
6255     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6256     */
6257    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6258            long currentTime, UserHandle user) throws PackageManagerException {
6259        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6260        parseFlags |= mDefParseFlags;
6261        PackageParser pp = new PackageParser();
6262        pp.setSeparateProcesses(mSeparateProcesses);
6263        pp.setOnlyCoreApps(mOnlyCore);
6264        pp.setDisplayMetrics(mMetrics);
6265
6266        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6267            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6268        }
6269
6270        final PackageParser.Package pkg;
6271        try {
6272            pkg = pp.parsePackage(scanFile, parseFlags);
6273        } catch (PackageParserException e) {
6274            throw PackageManagerException.from(e);
6275        }
6276
6277        PackageSetting ps = null;
6278        PackageSetting updatedPkg;
6279        // reader
6280        synchronized (mPackages) {
6281            // Look to see if we already know about this package.
6282            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6283            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6284                // This package has been renamed to its original name.  Let's
6285                // use that.
6286                ps = mSettings.peekPackageLPr(oldName);
6287            }
6288            // If there was no original package, see one for the real package name.
6289            if (ps == null) {
6290                ps = mSettings.peekPackageLPr(pkg.packageName);
6291            }
6292            // Check to see if this package could be hiding/updating a system
6293            // package.  Must look for it either under the original or real
6294            // package name depending on our state.
6295            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6296            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6297        }
6298        boolean updatedPkgBetter = false;
6299        // First check if this is a system package that may involve an update
6300        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6301            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6302            // it needs to drop FLAG_PRIVILEGED.
6303            if (locationIsPrivileged(scanFile)) {
6304                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6305            } else {
6306                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6307            }
6308
6309            if (ps != null && !ps.codePath.equals(scanFile)) {
6310                // The path has changed from what was last scanned...  check the
6311                // version of the new path against what we have stored to determine
6312                // what to do.
6313                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6314                if (pkg.mVersionCode <= ps.versionCode) {
6315                    // The system package has been updated and the code path does not match
6316                    // Ignore entry. Skip it.
6317                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6318                            + " ignored: updated version " + ps.versionCode
6319                            + " better than this " + pkg.mVersionCode);
6320                    if (!updatedPkg.codePath.equals(scanFile)) {
6321                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6322                                + ps.name + " changing from " + updatedPkg.codePathString
6323                                + " to " + scanFile);
6324                        updatedPkg.codePath = scanFile;
6325                        updatedPkg.codePathString = scanFile.toString();
6326                        updatedPkg.resourcePath = scanFile;
6327                        updatedPkg.resourcePathString = scanFile.toString();
6328                    }
6329                    updatedPkg.pkg = pkg;
6330                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6331                            "Package " + ps.name + " at " + scanFile
6332                                    + " ignored: updated version " + ps.versionCode
6333                                    + " better than this " + pkg.mVersionCode);
6334                } else {
6335                    // The current app on the system partition is better than
6336                    // what we have updated to on the data partition; switch
6337                    // back to the system partition version.
6338                    // At this point, its safely assumed that package installation for
6339                    // apps in system partition will go through. If not there won't be a working
6340                    // version of the app
6341                    // writer
6342                    synchronized (mPackages) {
6343                        // Just remove the loaded entries from package lists.
6344                        mPackages.remove(ps.name);
6345                    }
6346
6347                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6348                            + " reverting from " + ps.codePathString
6349                            + ": new version " + pkg.mVersionCode
6350                            + " better than installed " + ps.versionCode);
6351
6352                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6353                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6354                    synchronized (mInstallLock) {
6355                        args.cleanUpResourcesLI();
6356                    }
6357                    synchronized (mPackages) {
6358                        mSettings.enableSystemPackageLPw(ps.name);
6359                    }
6360                    updatedPkgBetter = true;
6361                }
6362            }
6363        }
6364
6365        if (updatedPkg != null) {
6366            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6367            // initially
6368            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6369
6370            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6371            // flag set initially
6372            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6373                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6374            }
6375        }
6376
6377        // Verify certificates against what was last scanned
6378        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6379
6380        /*
6381         * A new system app appeared, but we already had a non-system one of the
6382         * same name installed earlier.
6383         */
6384        boolean shouldHideSystemApp = false;
6385        if (updatedPkg == null && ps != null
6386                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6387            /*
6388             * Check to make sure the signatures match first. If they don't,
6389             * wipe the installed application and its data.
6390             */
6391            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6392                    != PackageManager.SIGNATURE_MATCH) {
6393                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6394                        + " signatures don't match existing userdata copy; removing");
6395                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6396                ps = null;
6397            } else {
6398                /*
6399                 * If the newly-added system app is an older version than the
6400                 * already installed version, hide it. It will be scanned later
6401                 * and re-added like an update.
6402                 */
6403                if (pkg.mVersionCode <= ps.versionCode) {
6404                    shouldHideSystemApp = true;
6405                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6406                            + " but new version " + pkg.mVersionCode + " better than installed "
6407                            + ps.versionCode + "; hiding system");
6408                } else {
6409                    /*
6410                     * The newly found system app is a newer version that the
6411                     * one previously installed. Simply remove the
6412                     * already-installed application and replace it with our own
6413                     * while keeping the application data.
6414                     */
6415                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6416                            + " reverting from " + ps.codePathString + ": new version "
6417                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6418                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6419                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6420                    synchronized (mInstallLock) {
6421                        args.cleanUpResourcesLI();
6422                    }
6423                }
6424            }
6425        }
6426
6427        // The apk is forward locked (not public) if its code and resources
6428        // are kept in different files. (except for app in either system or
6429        // vendor path).
6430        // TODO grab this value from PackageSettings
6431        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6432            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6433                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6434            }
6435        }
6436
6437        // TODO: extend to support forward-locked splits
6438        String resourcePath = null;
6439        String baseResourcePath = null;
6440        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6441            if (ps != null && ps.resourcePathString != null) {
6442                resourcePath = ps.resourcePathString;
6443                baseResourcePath = ps.resourcePathString;
6444            } else {
6445                // Should not happen at all. Just log an error.
6446                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6447            }
6448        } else {
6449            resourcePath = pkg.codePath;
6450            baseResourcePath = pkg.baseCodePath;
6451        }
6452
6453        // Set application objects path explicitly.
6454        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6455        pkg.applicationInfo.setCodePath(pkg.codePath);
6456        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6457        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6458        pkg.applicationInfo.setResourcePath(resourcePath);
6459        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6460        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6461
6462        // Note that we invoke the following method only if we are about to unpack an application
6463        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6464                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6465
6466        /*
6467         * If the system app should be overridden by a previously installed
6468         * data, hide the system app now and let the /data/app scan pick it up
6469         * again.
6470         */
6471        if (shouldHideSystemApp) {
6472            synchronized (mPackages) {
6473                mSettings.disableSystemPackageLPw(pkg.packageName);
6474            }
6475        }
6476
6477        return scannedPkg;
6478    }
6479
6480    private static String fixProcessName(String defProcessName,
6481            String processName, int uid) {
6482        if (processName == null) {
6483            return defProcessName;
6484        }
6485        return processName;
6486    }
6487
6488    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6489            throws PackageManagerException {
6490        if (pkgSetting.signatures.mSignatures != null) {
6491            // Already existing package. Make sure signatures match
6492            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6493                    == PackageManager.SIGNATURE_MATCH;
6494            if (!match) {
6495                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6496                        == PackageManager.SIGNATURE_MATCH;
6497            }
6498            if (!match) {
6499                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6500                        == PackageManager.SIGNATURE_MATCH;
6501            }
6502            if (!match) {
6503                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6504                        + pkg.packageName + " signatures do not match the "
6505                        + "previously installed version; ignoring!");
6506            }
6507        }
6508
6509        // Check for shared user signatures
6510        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6511            // Already existing package. Make sure signatures match
6512            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6513                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6514            if (!match) {
6515                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6516                        == PackageManager.SIGNATURE_MATCH;
6517            }
6518            if (!match) {
6519                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6520                        == PackageManager.SIGNATURE_MATCH;
6521            }
6522            if (!match) {
6523                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6524                        "Package " + pkg.packageName
6525                        + " has no signatures that match those in shared user "
6526                        + pkgSetting.sharedUser.name + "; ignoring!");
6527            }
6528        }
6529    }
6530
6531    /**
6532     * Enforces that only the system UID or root's UID can call a method exposed
6533     * via Binder.
6534     *
6535     * @param message used as message if SecurityException is thrown
6536     * @throws SecurityException if the caller is not system or root
6537     */
6538    private static final void enforceSystemOrRoot(String message) {
6539        final int uid = Binder.getCallingUid();
6540        if (uid != Process.SYSTEM_UID && uid != 0) {
6541            throw new SecurityException(message);
6542        }
6543    }
6544
6545    @Override
6546    public void performFstrimIfNeeded() {
6547        enforceSystemOrRoot("Only the system can request fstrim");
6548
6549        // Before everything else, see whether we need to fstrim.
6550        try {
6551            IMountService ms = PackageHelper.getMountService();
6552            if (ms != null) {
6553                final boolean isUpgrade = isUpgrade();
6554                boolean doTrim = isUpgrade;
6555                if (doTrim) {
6556                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6557                } else {
6558                    final long interval = android.provider.Settings.Global.getLong(
6559                            mContext.getContentResolver(),
6560                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6561                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6562                    if (interval > 0) {
6563                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6564                        if (timeSinceLast > interval) {
6565                            doTrim = true;
6566                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6567                                    + "; running immediately");
6568                        }
6569                    }
6570                }
6571                if (doTrim) {
6572                    if (!isFirstBoot()) {
6573                        try {
6574                            ActivityManagerNative.getDefault().showBootMessage(
6575                                    mContext.getResources().getString(
6576                                            R.string.android_upgrading_fstrim), true);
6577                        } catch (RemoteException e) {
6578                        }
6579                    }
6580                    ms.runMaintenance();
6581                }
6582            } else {
6583                Slog.e(TAG, "Mount service unavailable!");
6584            }
6585        } catch (RemoteException e) {
6586            // Can't happen; MountService is local
6587        }
6588    }
6589
6590    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6591        List<ResolveInfo> ris = null;
6592        try {
6593            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6594                    intent, null, 0, userId);
6595        } catch (RemoteException e) {
6596        }
6597        ArraySet<String> pkgNames = new ArraySet<String>();
6598        if (ris != null) {
6599            for (ResolveInfo ri : ris) {
6600                pkgNames.add(ri.activityInfo.packageName);
6601            }
6602        }
6603        return pkgNames;
6604    }
6605
6606    @Override
6607    public void notifyPackageUse(String packageName) {
6608        synchronized (mPackages) {
6609            PackageParser.Package p = mPackages.get(packageName);
6610            if (p == null) {
6611                return;
6612            }
6613            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6614        }
6615    }
6616
6617    @Override
6618    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6619        return performDexOptTraced(packageName, instructionSet);
6620    }
6621
6622    public boolean performDexOpt(String packageName, String instructionSet) {
6623        return performDexOptTraced(packageName, instructionSet);
6624    }
6625
6626    private boolean performDexOptTraced(String packageName, String instructionSet) {
6627        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6628        try {
6629            return performDexOptInternal(packageName, instructionSet);
6630        } finally {
6631            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6632        }
6633    }
6634
6635    private boolean performDexOptInternal(String packageName, String instructionSet) {
6636        PackageParser.Package p;
6637        final String targetInstructionSet;
6638        synchronized (mPackages) {
6639            p = mPackages.get(packageName);
6640            if (p == null) {
6641                return false;
6642            }
6643            mPackageUsage.write(false);
6644
6645            targetInstructionSet = instructionSet != null ? instructionSet :
6646                    getPrimaryInstructionSet(p.applicationInfo);
6647            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6648                return false;
6649            }
6650        }
6651        long callingId = Binder.clearCallingIdentity();
6652        try {
6653            synchronized (mInstallLock) {
6654                final String[] instructionSets = new String[] { targetInstructionSet };
6655                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6656                        true /* inclDependencies */);
6657                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6658            }
6659        } finally {
6660            Binder.restoreCallingIdentity(callingId);
6661        }
6662    }
6663
6664    public ArraySet<String> getPackagesThatNeedDexOpt() {
6665        ArraySet<String> pkgs = null;
6666        synchronized (mPackages) {
6667            for (PackageParser.Package p : mPackages.values()) {
6668                if (DEBUG_DEXOPT) {
6669                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6670                }
6671                if (!p.mDexOptPerformed.isEmpty()) {
6672                    continue;
6673                }
6674                if (pkgs == null) {
6675                    pkgs = new ArraySet<String>();
6676                }
6677                pkgs.add(p.packageName);
6678            }
6679        }
6680        return pkgs;
6681    }
6682
6683    public void shutdown() {
6684        mPackageUsage.write(true);
6685    }
6686
6687    @Override
6688    public void forceDexOpt(String packageName) {
6689        enforceSystemOrRoot("forceDexOpt");
6690
6691        PackageParser.Package pkg;
6692        synchronized (mPackages) {
6693            pkg = mPackages.get(packageName);
6694            if (pkg == null) {
6695                throw new IllegalArgumentException("Unknown package: " + packageName);
6696            }
6697        }
6698
6699        synchronized (mInstallLock) {
6700            final String[] instructionSets = new String[] {
6701                    getPrimaryInstructionSet(pkg.applicationInfo) };
6702
6703            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6704
6705            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6706                    true /* inclDependencies */);
6707
6708            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6709            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6710                throw new IllegalStateException("Failed to dexopt: " + res);
6711            }
6712        }
6713    }
6714
6715    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6716        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6717            Slog.w(TAG, "Unable to update from " + oldPkg.name
6718                    + " to " + newPkg.packageName
6719                    + ": old package not in system partition");
6720            return false;
6721        } else if (mPackages.get(oldPkg.name) != null) {
6722            Slog.w(TAG, "Unable to update from " + oldPkg.name
6723                    + " to " + newPkg.packageName
6724                    + ": old package still exists");
6725            return false;
6726        }
6727        return true;
6728    }
6729
6730    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
6731        // TODO: triage flags as part of 26466827
6732        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6733
6734        boolean res = true;
6735        final int[] users = sUserManager.getUserIds();
6736        for (int user : users) {
6737            try {
6738                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
6739            } catch (InstallerException e) {
6740                Slog.w(TAG, "Failed to delete data directory", e);
6741                res = false;
6742            }
6743        }
6744        return res;
6745    }
6746
6747    void removeCodePathLI(File codePath) {
6748        if (codePath.isDirectory()) {
6749            try {
6750                mInstaller.rmPackageDir(codePath.getAbsolutePath());
6751            } catch (InstallerException e) {
6752                Slog.w(TAG, "Failed to remove code path", e);
6753            }
6754        } else {
6755            codePath.delete();
6756        }
6757    }
6758
6759    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
6760        try {
6761            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
6762        } catch (InstallerException e) {
6763            Slog.w(TAG, "Failed to destroy app data", e);
6764        }
6765    }
6766
6767    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
6768            int appId, String seinfo) {
6769        try {
6770            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
6771        } catch (InstallerException e) {
6772            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
6773        }
6774    }
6775
6776    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6777        // TODO: triage flags as part of 26466827
6778        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
6779
6780        final int[] users = sUserManager.getUserIds();
6781        for (int user : users) {
6782            try {
6783                mInstaller.clearAppData(volumeUuid, packageName, user,
6784                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
6785            } catch (InstallerException e) {
6786                Slog.w(TAG, "Failed to delete code cache directory", e);
6787            }
6788        }
6789    }
6790
6791    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6792            PackageParser.Package changingLib) {
6793        if (file.path != null) {
6794            usesLibraryFiles.add(file.path);
6795            return;
6796        }
6797        PackageParser.Package p = mPackages.get(file.apk);
6798        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6799            // If we are doing this while in the middle of updating a library apk,
6800            // then we need to make sure to use that new apk for determining the
6801            // dependencies here.  (We haven't yet finished committing the new apk
6802            // to the package manager state.)
6803            if (p == null || p.packageName.equals(changingLib.packageName)) {
6804                p = changingLib;
6805            }
6806        }
6807        if (p != null) {
6808            usesLibraryFiles.addAll(p.getAllCodePaths());
6809        }
6810    }
6811
6812    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6813            PackageParser.Package changingLib) throws PackageManagerException {
6814        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6815            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6816            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6817            for (int i=0; i<N; i++) {
6818                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6819                if (file == null) {
6820                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6821                            "Package " + pkg.packageName + " requires unavailable shared library "
6822                            + pkg.usesLibraries.get(i) + "; failing!");
6823                }
6824                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6825            }
6826            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6827            for (int i=0; i<N; i++) {
6828                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6829                if (file == null) {
6830                    Slog.w(TAG, "Package " + pkg.packageName
6831                            + " desires unavailable shared library "
6832                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6833                } else {
6834                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6835                }
6836            }
6837            N = usesLibraryFiles.size();
6838            if (N > 0) {
6839                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6840            } else {
6841                pkg.usesLibraryFiles = null;
6842            }
6843        }
6844    }
6845
6846    private static boolean hasString(List<String> list, List<String> which) {
6847        if (list == null) {
6848            return false;
6849        }
6850        for (int i=list.size()-1; i>=0; i--) {
6851            for (int j=which.size()-1; j>=0; j--) {
6852                if (which.get(j).equals(list.get(i))) {
6853                    return true;
6854                }
6855            }
6856        }
6857        return false;
6858    }
6859
6860    private void updateAllSharedLibrariesLPw() {
6861        for (PackageParser.Package pkg : mPackages.values()) {
6862            try {
6863                updateSharedLibrariesLPw(pkg, null);
6864            } catch (PackageManagerException e) {
6865                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6866            }
6867        }
6868    }
6869
6870    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6871            PackageParser.Package changingPkg) {
6872        ArrayList<PackageParser.Package> res = null;
6873        for (PackageParser.Package pkg : mPackages.values()) {
6874            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6875                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6876                if (res == null) {
6877                    res = new ArrayList<PackageParser.Package>();
6878                }
6879                res.add(pkg);
6880                try {
6881                    updateSharedLibrariesLPw(pkg, changingPkg);
6882                } catch (PackageManagerException e) {
6883                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6884                }
6885            }
6886        }
6887        return res;
6888    }
6889
6890    /**
6891     * Derive the value of the {@code cpuAbiOverride} based on the provided
6892     * value and an optional stored value from the package settings.
6893     */
6894    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6895        String cpuAbiOverride = null;
6896
6897        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6898            cpuAbiOverride = null;
6899        } else if (abiOverride != null) {
6900            cpuAbiOverride = abiOverride;
6901        } else if (settings != null) {
6902            cpuAbiOverride = settings.cpuAbiOverrideString;
6903        }
6904
6905        return cpuAbiOverride;
6906    }
6907
6908    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6909            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6910        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6911        try {
6912            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6913        } finally {
6914            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6915        }
6916    }
6917
6918    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6919            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6920        boolean success = false;
6921        try {
6922            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6923                    currentTime, user);
6924            success = true;
6925            return res;
6926        } finally {
6927            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6928                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6929            }
6930        }
6931    }
6932
6933    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6934            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6935        final File scanFile = new File(pkg.codePath);
6936        if (pkg.applicationInfo.getCodePath() == null ||
6937                pkg.applicationInfo.getResourcePath() == null) {
6938            // Bail out. The resource and code paths haven't been set.
6939            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6940                    "Code and resource paths haven't been set correctly");
6941        }
6942
6943        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6944            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6945        } else {
6946            // Only allow system apps to be flagged as core apps.
6947            pkg.coreApp = false;
6948        }
6949
6950        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6951            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6952        }
6953
6954        if (mCustomResolverComponentName != null &&
6955                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6956            setUpCustomResolverActivity(pkg);
6957        }
6958
6959        if (pkg.packageName.equals("android")) {
6960            synchronized (mPackages) {
6961                if (mAndroidApplication != null) {
6962                    Slog.w(TAG, "*************************************************");
6963                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6964                    Slog.w(TAG, " file=" + scanFile);
6965                    Slog.w(TAG, "*************************************************");
6966                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6967                            "Core android package being redefined.  Skipping.");
6968                }
6969
6970                // Set up information for our fall-back user intent resolution activity.
6971                mPlatformPackage = pkg;
6972                pkg.mVersionCode = mSdkVersion;
6973                mAndroidApplication = pkg.applicationInfo;
6974
6975                if (!mResolverReplaced) {
6976                    mResolveActivity.applicationInfo = mAndroidApplication;
6977                    mResolveActivity.name = ResolverActivity.class.getName();
6978                    mResolveActivity.packageName = mAndroidApplication.packageName;
6979                    mResolveActivity.processName = "system:ui";
6980                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6981                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6982                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6983                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6984                    mResolveActivity.exported = true;
6985                    mResolveActivity.enabled = true;
6986                    mResolveInfo.activityInfo = mResolveActivity;
6987                    mResolveInfo.priority = 0;
6988                    mResolveInfo.preferredOrder = 0;
6989                    mResolveInfo.match = 0;
6990                    mResolveComponentName = new ComponentName(
6991                            mAndroidApplication.packageName, mResolveActivity.name);
6992                }
6993            }
6994        }
6995
6996        if (DEBUG_PACKAGE_SCANNING) {
6997            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6998                Log.d(TAG, "Scanning package " + pkg.packageName);
6999        }
7000
7001        if (mPackages.containsKey(pkg.packageName)
7002                || mSharedLibraries.containsKey(pkg.packageName)) {
7003            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7004                    "Application package " + pkg.packageName
7005                    + " already installed.  Skipping duplicate.");
7006        }
7007
7008        // If we're only installing presumed-existing packages, require that the
7009        // scanned APK is both already known and at the path previously established
7010        // for it.  Previously unknown packages we pick up normally, but if we have an
7011        // a priori expectation about this package's install presence, enforce it.
7012        // With a singular exception for new system packages. When an OTA contains
7013        // a new system package, we allow the codepath to change from a system location
7014        // to the user-installed location. If we don't allow this change, any newer,
7015        // user-installed version of the application will be ignored.
7016        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7017            if (mExpectingBetter.containsKey(pkg.packageName)) {
7018                logCriticalInfo(Log.WARN,
7019                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7020            } else {
7021                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7022                if (known != null) {
7023                    if (DEBUG_PACKAGE_SCANNING) {
7024                        Log.d(TAG, "Examining " + pkg.codePath
7025                                + " and requiring known paths " + known.codePathString
7026                                + " & " + known.resourcePathString);
7027                    }
7028                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7029                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7030                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7031                                "Application package " + pkg.packageName
7032                                + " found at " + pkg.applicationInfo.getCodePath()
7033                                + " but expected at " + known.codePathString + "; ignoring.");
7034                    }
7035                }
7036            }
7037        }
7038
7039        // Initialize package source and resource directories
7040        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7041        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7042
7043        SharedUserSetting suid = null;
7044        PackageSetting pkgSetting = null;
7045
7046        if (!isSystemApp(pkg)) {
7047            // Only system apps can use these features.
7048            pkg.mOriginalPackages = null;
7049            pkg.mRealPackage = null;
7050            pkg.mAdoptPermissions = null;
7051        }
7052
7053        // writer
7054        synchronized (mPackages) {
7055            if (pkg.mSharedUserId != null) {
7056                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7057                if (suid == null) {
7058                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7059                            "Creating application package " + pkg.packageName
7060                            + " for shared user failed");
7061                }
7062                if (DEBUG_PACKAGE_SCANNING) {
7063                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7064                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7065                                + "): packages=" + suid.packages);
7066                }
7067            }
7068
7069            // Check if we are renaming from an original package name.
7070            PackageSetting origPackage = null;
7071            String realName = null;
7072            if (pkg.mOriginalPackages != null) {
7073                // This package may need to be renamed to a previously
7074                // installed name.  Let's check on that...
7075                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7076                if (pkg.mOriginalPackages.contains(renamed)) {
7077                    // This package had originally been installed as the
7078                    // original name, and we have already taken care of
7079                    // transitioning to the new one.  Just update the new
7080                    // one to continue using the old name.
7081                    realName = pkg.mRealPackage;
7082                    if (!pkg.packageName.equals(renamed)) {
7083                        // Callers into this function may have already taken
7084                        // care of renaming the package; only do it here if
7085                        // it is not already done.
7086                        pkg.setPackageName(renamed);
7087                    }
7088
7089                } else {
7090                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7091                        if ((origPackage = mSettings.peekPackageLPr(
7092                                pkg.mOriginalPackages.get(i))) != null) {
7093                            // We do have the package already installed under its
7094                            // original name...  should we use it?
7095                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7096                                // New package is not compatible with original.
7097                                origPackage = null;
7098                                continue;
7099                            } else if (origPackage.sharedUser != null) {
7100                                // Make sure uid is compatible between packages.
7101                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7102                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7103                                            + " to " + pkg.packageName + ": old uid "
7104                                            + origPackage.sharedUser.name
7105                                            + " differs from " + pkg.mSharedUserId);
7106                                    origPackage = null;
7107                                    continue;
7108                                }
7109                            } else {
7110                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7111                                        + pkg.packageName + " to old name " + origPackage.name);
7112                            }
7113                            break;
7114                        }
7115                    }
7116                }
7117            }
7118
7119            if (mTransferedPackages.contains(pkg.packageName)) {
7120                Slog.w(TAG, "Package " + pkg.packageName
7121                        + " was transferred to another, but its .apk remains");
7122            }
7123
7124            // Just create the setting, don't add it yet. For already existing packages
7125            // the PkgSetting exists already and doesn't have to be created.
7126            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7127                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7128                    pkg.applicationInfo.primaryCpuAbi,
7129                    pkg.applicationInfo.secondaryCpuAbi,
7130                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7131                    user, false);
7132            if (pkgSetting == null) {
7133                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7134                        "Creating application package " + pkg.packageName + " failed");
7135            }
7136
7137            if (pkgSetting.origPackage != null) {
7138                // If we are first transitioning from an original package,
7139                // fix up the new package's name now.  We need to do this after
7140                // looking up the package under its new name, so getPackageLP
7141                // can take care of fiddling things correctly.
7142                pkg.setPackageName(origPackage.name);
7143
7144                // File a report about this.
7145                String msg = "New package " + pkgSetting.realName
7146                        + " renamed to replace old package " + pkgSetting.name;
7147                reportSettingsProblem(Log.WARN, msg);
7148
7149                // Make a note of it.
7150                mTransferedPackages.add(origPackage.name);
7151
7152                // No longer need to retain this.
7153                pkgSetting.origPackage = null;
7154            }
7155
7156            if (realName != null) {
7157                // Make a note of it.
7158                mTransferedPackages.add(pkg.packageName);
7159            }
7160
7161            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7162                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7163            }
7164
7165            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7166                // Check all shared libraries and map to their actual file path.
7167                // We only do this here for apps not on a system dir, because those
7168                // are the only ones that can fail an install due to this.  We
7169                // will take care of the system apps by updating all of their
7170                // library paths after the scan is done.
7171                updateSharedLibrariesLPw(pkg, null);
7172            }
7173
7174            if (mFoundPolicyFile) {
7175                SELinuxMMAC.assignSeinfoValue(pkg);
7176            }
7177
7178            pkg.applicationInfo.uid = pkgSetting.appId;
7179            pkg.mExtras = pkgSetting;
7180            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7181                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7182                    // We just determined the app is signed correctly, so bring
7183                    // over the latest parsed certs.
7184                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7185                } else {
7186                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7187                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7188                                "Package " + pkg.packageName + " upgrade keys do not match the "
7189                                + "previously installed version");
7190                    } else {
7191                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7192                        String msg = "System package " + pkg.packageName
7193                            + " signature changed; retaining data.";
7194                        reportSettingsProblem(Log.WARN, msg);
7195                    }
7196                }
7197            } else {
7198                try {
7199                    verifySignaturesLP(pkgSetting, pkg);
7200                    // We just determined the app is signed correctly, so bring
7201                    // over the latest parsed certs.
7202                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7203                } catch (PackageManagerException e) {
7204                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7205                        throw e;
7206                    }
7207                    // The signature has changed, but this package is in the system
7208                    // image...  let's recover!
7209                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7210                    // However...  if this package is part of a shared user, but it
7211                    // doesn't match the signature of the shared user, let's fail.
7212                    // What this means is that you can't change the signatures
7213                    // associated with an overall shared user, which doesn't seem all
7214                    // that unreasonable.
7215                    if (pkgSetting.sharedUser != null) {
7216                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7217                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7218                            throw new PackageManagerException(
7219                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7220                                            "Signature mismatch for shared user: "
7221                                            + pkgSetting.sharedUser);
7222                        }
7223                    }
7224                    // File a report about this.
7225                    String msg = "System package " + pkg.packageName
7226                        + " signature changed; retaining data.";
7227                    reportSettingsProblem(Log.WARN, msg);
7228                }
7229            }
7230            // Verify that this new package doesn't have any content providers
7231            // that conflict with existing packages.  Only do this if the
7232            // package isn't already installed, since we don't want to break
7233            // things that are installed.
7234            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7235                final int N = pkg.providers.size();
7236                int i;
7237                for (i=0; i<N; i++) {
7238                    PackageParser.Provider p = pkg.providers.get(i);
7239                    if (p.info.authority != null) {
7240                        String names[] = p.info.authority.split(";");
7241                        for (int j = 0; j < names.length; j++) {
7242                            if (mProvidersByAuthority.containsKey(names[j])) {
7243                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7244                                final String otherPackageName =
7245                                        ((other != null && other.getComponentName() != null) ?
7246                                                other.getComponentName().getPackageName() : "?");
7247                                throw new PackageManagerException(
7248                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7249                                                "Can't install because provider name " + names[j]
7250                                                + " (in package " + pkg.applicationInfo.packageName
7251                                                + ") is already used by " + otherPackageName);
7252                            }
7253                        }
7254                    }
7255                }
7256            }
7257
7258            if (pkg.mAdoptPermissions != null) {
7259                // This package wants to adopt ownership of permissions from
7260                // another package.
7261                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7262                    final String origName = pkg.mAdoptPermissions.get(i);
7263                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7264                    if (orig != null) {
7265                        if (verifyPackageUpdateLPr(orig, pkg)) {
7266                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7267                                    + pkg.packageName);
7268                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7269                        }
7270                    }
7271                }
7272            }
7273        }
7274
7275        final String pkgName = pkg.packageName;
7276
7277        final long scanFileTime = scanFile.lastModified();
7278        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7279        pkg.applicationInfo.processName = fixProcessName(
7280                pkg.applicationInfo.packageName,
7281                pkg.applicationInfo.processName,
7282                pkg.applicationInfo.uid);
7283
7284        if (pkg != mPlatformPackage) {
7285            // Get all of our default paths setup
7286            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7287        }
7288
7289        final String path = scanFile.getPath();
7290        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7291
7292        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7293            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7294
7295            // Some system apps still use directory structure for native libraries
7296            // in which case we might end up not detecting abi solely based on apk
7297            // structure. Try to detect abi based on directory structure.
7298            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7299                    pkg.applicationInfo.primaryCpuAbi == null) {
7300                setBundledAppAbisAndRoots(pkg, pkgSetting);
7301                setNativeLibraryPaths(pkg);
7302            }
7303
7304        } else {
7305            if ((scanFlags & SCAN_MOVE) != 0) {
7306                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7307                // but we already have this packages package info in the PackageSetting. We just
7308                // use that and derive the native library path based on the new codepath.
7309                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7310                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7311            }
7312
7313            // Set native library paths again. For moves, the path will be updated based on the
7314            // ABIs we've determined above. For non-moves, the path will be updated based on the
7315            // ABIs we determined during compilation, but the path will depend on the final
7316            // package path (after the rename away from the stage path).
7317            setNativeLibraryPaths(pkg);
7318        }
7319
7320        // This is a special case for the "system" package, where the ABI is
7321        // dictated by the zygote configuration (and init.rc). We should keep track
7322        // of this ABI so that we can deal with "normal" applications that run under
7323        // the same UID correctly.
7324        if (mPlatformPackage == pkg) {
7325            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7326                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7327        }
7328
7329        // If there's a mismatch between the abi-override in the package setting
7330        // and the abiOverride specified for the install. Warn about this because we
7331        // would've already compiled the app without taking the package setting into
7332        // account.
7333        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7334            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7335                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7336                        " for package " + pkg.packageName);
7337            }
7338        }
7339
7340        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7341        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7342        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7343
7344        // Copy the derived override back to the parsed package, so that we can
7345        // update the package settings accordingly.
7346        pkg.cpuAbiOverride = cpuAbiOverride;
7347
7348        if (DEBUG_ABI_SELECTION) {
7349            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7350                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7351                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7352        }
7353
7354        // Push the derived path down into PackageSettings so we know what to
7355        // clean up at uninstall time.
7356        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7357
7358        if (DEBUG_ABI_SELECTION) {
7359            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7360                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7361                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7362        }
7363
7364        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7365            // We don't do this here during boot because we can do it all
7366            // at once after scanning all existing packages.
7367            //
7368            // We also do this *before* we perform dexopt on this package, so that
7369            // we can avoid redundant dexopts, and also to make sure we've got the
7370            // code and package path correct.
7371            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7372                    pkg, true /* boot complete */);
7373        }
7374
7375        if (mFactoryTest && pkg.requestedPermissions.contains(
7376                android.Manifest.permission.FACTORY_TEST)) {
7377            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7378        }
7379
7380        ArrayList<PackageParser.Package> clientLibPkgs = null;
7381
7382        // writer
7383        synchronized (mPackages) {
7384            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7385                // Only system apps can add new shared libraries.
7386                if (pkg.libraryNames != null) {
7387                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7388                        String name = pkg.libraryNames.get(i);
7389                        boolean allowed = false;
7390                        if (pkg.isUpdatedSystemApp()) {
7391                            // New library entries can only be added through the
7392                            // system image.  This is important to get rid of a lot
7393                            // of nasty edge cases: for example if we allowed a non-
7394                            // system update of the app to add a library, then uninstalling
7395                            // the update would make the library go away, and assumptions
7396                            // we made such as through app install filtering would now
7397                            // have allowed apps on the device which aren't compatible
7398                            // with it.  Better to just have the restriction here, be
7399                            // conservative, and create many fewer cases that can negatively
7400                            // impact the user experience.
7401                            final PackageSetting sysPs = mSettings
7402                                    .getDisabledSystemPkgLPr(pkg.packageName);
7403                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7404                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7405                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7406                                        allowed = true;
7407                                        break;
7408                                    }
7409                                }
7410                            }
7411                        } else {
7412                            allowed = true;
7413                        }
7414                        if (allowed) {
7415                            if (!mSharedLibraries.containsKey(name)) {
7416                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7417                            } else if (!name.equals(pkg.packageName)) {
7418                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7419                                        + name + " already exists; skipping");
7420                            }
7421                        } else {
7422                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7423                                    + name + " that is not declared on system image; skipping");
7424                        }
7425                    }
7426                    if ((scanFlags & SCAN_BOOTING) == 0) {
7427                        // If we are not booting, we need to update any applications
7428                        // that are clients of our shared library.  If we are booting,
7429                        // this will all be done once the scan is complete.
7430                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7431                    }
7432                }
7433            }
7434        }
7435
7436        // Request the ActivityManager to kill the process(only for existing packages)
7437        // so that we do not end up in a confused state while the user is still using the older
7438        // version of the application while the new one gets installed.
7439        if ((scanFlags & SCAN_REPLACING) != 0) {
7440            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7441
7442            killApplication(pkg.applicationInfo.packageName,
7443                        pkg.applicationInfo.uid, "replace pkg");
7444
7445            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7446        }
7447
7448        // Also need to kill any apps that are dependent on the library.
7449        if (clientLibPkgs != null) {
7450            for (int i=0; i<clientLibPkgs.size(); i++) {
7451                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7452                killApplication(clientPkg.applicationInfo.packageName,
7453                        clientPkg.applicationInfo.uid, "update lib");
7454            }
7455        }
7456
7457        // Make sure we're not adding any bogus keyset info
7458        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7459        ksms.assertScannedPackageValid(pkg);
7460
7461        // writer
7462        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7463
7464        boolean createIdmapFailed = false;
7465        synchronized (mPackages) {
7466            // We don't expect installation to fail beyond this point
7467
7468            // Add the new setting to mSettings
7469            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7470            // Add the new setting to mPackages
7471            mPackages.put(pkg.applicationInfo.packageName, pkg);
7472            // Make sure we don't accidentally delete its data.
7473            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7474            while (iter.hasNext()) {
7475                PackageCleanItem item = iter.next();
7476                if (pkgName.equals(item.packageName)) {
7477                    iter.remove();
7478                }
7479            }
7480
7481            // Take care of first install / last update times.
7482            if (currentTime != 0) {
7483                if (pkgSetting.firstInstallTime == 0) {
7484                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7485                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7486                    pkgSetting.lastUpdateTime = currentTime;
7487                }
7488            } else if (pkgSetting.firstInstallTime == 0) {
7489                // We need *something*.  Take time time stamp of the file.
7490                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7491            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7492                if (scanFileTime != pkgSetting.timeStamp) {
7493                    // A package on the system image has changed; consider this
7494                    // to be an update.
7495                    pkgSetting.lastUpdateTime = scanFileTime;
7496                }
7497            }
7498
7499            // Add the package's KeySets to the global KeySetManagerService
7500            ksms.addScannedPackageLPw(pkg);
7501
7502            int N = pkg.providers.size();
7503            StringBuilder r = null;
7504            int i;
7505            for (i=0; i<N; i++) {
7506                PackageParser.Provider p = pkg.providers.get(i);
7507                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7508                        p.info.processName, pkg.applicationInfo.uid);
7509                mProviders.addProvider(p);
7510                p.syncable = p.info.isSyncable;
7511                if (p.info.authority != null) {
7512                    String names[] = p.info.authority.split(";");
7513                    p.info.authority = null;
7514                    for (int j = 0; j < names.length; j++) {
7515                        if (j == 1 && p.syncable) {
7516                            // We only want the first authority for a provider to possibly be
7517                            // syncable, so if we already added this provider using a different
7518                            // authority clear the syncable flag. We copy the provider before
7519                            // changing it because the mProviders object contains a reference
7520                            // to a provider that we don't want to change.
7521                            // Only do this for the second authority since the resulting provider
7522                            // object can be the same for all future authorities for this provider.
7523                            p = new PackageParser.Provider(p);
7524                            p.syncable = false;
7525                        }
7526                        if (!mProvidersByAuthority.containsKey(names[j])) {
7527                            mProvidersByAuthority.put(names[j], p);
7528                            if (p.info.authority == null) {
7529                                p.info.authority = names[j];
7530                            } else {
7531                                p.info.authority = p.info.authority + ";" + names[j];
7532                            }
7533                            if (DEBUG_PACKAGE_SCANNING) {
7534                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7535                                    Log.d(TAG, "Registered content provider: " + names[j]
7536                                            + ", className = " + p.info.name + ", isSyncable = "
7537                                            + p.info.isSyncable);
7538                            }
7539                        } else {
7540                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7541                            Slog.w(TAG, "Skipping provider name " + names[j] +
7542                                    " (in package " + pkg.applicationInfo.packageName +
7543                                    "): name already used by "
7544                                    + ((other != null && other.getComponentName() != null)
7545                                            ? other.getComponentName().getPackageName() : "?"));
7546                        }
7547                    }
7548                }
7549                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7550                    if (r == null) {
7551                        r = new StringBuilder(256);
7552                    } else {
7553                        r.append(' ');
7554                    }
7555                    r.append(p.info.name);
7556                }
7557            }
7558            if (r != null) {
7559                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7560            }
7561
7562            N = pkg.services.size();
7563            r = null;
7564            for (i=0; i<N; i++) {
7565                PackageParser.Service s = pkg.services.get(i);
7566                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7567                        s.info.processName, pkg.applicationInfo.uid);
7568                mServices.addService(s);
7569                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7570                    if (r == null) {
7571                        r = new StringBuilder(256);
7572                    } else {
7573                        r.append(' ');
7574                    }
7575                    r.append(s.info.name);
7576                }
7577            }
7578            if (r != null) {
7579                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7580            }
7581
7582            N = pkg.receivers.size();
7583            r = null;
7584            for (i=0; i<N; i++) {
7585                PackageParser.Activity a = pkg.receivers.get(i);
7586                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7587                        a.info.processName, pkg.applicationInfo.uid);
7588                mReceivers.addActivity(a, "receiver");
7589                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7590                    if (r == null) {
7591                        r = new StringBuilder(256);
7592                    } else {
7593                        r.append(' ');
7594                    }
7595                    r.append(a.info.name);
7596                }
7597            }
7598            if (r != null) {
7599                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7600            }
7601
7602            N = pkg.activities.size();
7603            r = null;
7604            for (i=0; i<N; i++) {
7605                PackageParser.Activity a = pkg.activities.get(i);
7606                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7607                        a.info.processName, pkg.applicationInfo.uid);
7608                mActivities.addActivity(a, "activity");
7609                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7610                    if (r == null) {
7611                        r = new StringBuilder(256);
7612                    } else {
7613                        r.append(' ');
7614                    }
7615                    r.append(a.info.name);
7616                }
7617            }
7618            if (r != null) {
7619                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7620            }
7621
7622            N = pkg.permissionGroups.size();
7623            r = null;
7624            for (i=0; i<N; i++) {
7625                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7626                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7627                if (cur == null) {
7628                    mPermissionGroups.put(pg.info.name, pg);
7629                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7630                        if (r == null) {
7631                            r = new StringBuilder(256);
7632                        } else {
7633                            r.append(' ');
7634                        }
7635                        r.append(pg.info.name);
7636                    }
7637                } else {
7638                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7639                            + pg.info.packageName + " ignored: original from "
7640                            + cur.info.packageName);
7641                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7642                        if (r == null) {
7643                            r = new StringBuilder(256);
7644                        } else {
7645                            r.append(' ');
7646                        }
7647                        r.append("DUP:");
7648                        r.append(pg.info.name);
7649                    }
7650                }
7651            }
7652            if (r != null) {
7653                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7654            }
7655
7656            N = pkg.permissions.size();
7657            r = null;
7658            for (i=0; i<N; i++) {
7659                PackageParser.Permission p = pkg.permissions.get(i);
7660
7661                // Assume by default that we did not install this permission into the system.
7662                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7663
7664                // Now that permission groups have a special meaning, we ignore permission
7665                // groups for legacy apps to prevent unexpected behavior. In particular,
7666                // permissions for one app being granted to someone just becuase they happen
7667                // to be in a group defined by another app (before this had no implications).
7668                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7669                    p.group = mPermissionGroups.get(p.info.group);
7670                    // Warn for a permission in an unknown group.
7671                    if (p.info.group != null && p.group == null) {
7672                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7673                                + p.info.packageName + " in an unknown group " + p.info.group);
7674                    }
7675                }
7676
7677                ArrayMap<String, BasePermission> permissionMap =
7678                        p.tree ? mSettings.mPermissionTrees
7679                                : mSettings.mPermissions;
7680                BasePermission bp = permissionMap.get(p.info.name);
7681
7682                // Allow system apps to redefine non-system permissions
7683                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7684                    final boolean currentOwnerIsSystem = (bp.perm != null
7685                            && isSystemApp(bp.perm.owner));
7686                    if (isSystemApp(p.owner)) {
7687                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7688                            // It's a built-in permission and no owner, take ownership now
7689                            bp.packageSetting = pkgSetting;
7690                            bp.perm = p;
7691                            bp.uid = pkg.applicationInfo.uid;
7692                            bp.sourcePackage = p.info.packageName;
7693                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7694                        } else if (!currentOwnerIsSystem) {
7695                            String msg = "New decl " + p.owner + " of permission  "
7696                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7697                            reportSettingsProblem(Log.WARN, msg);
7698                            bp = null;
7699                        }
7700                    }
7701                }
7702
7703                if (bp == null) {
7704                    bp = new BasePermission(p.info.name, p.info.packageName,
7705                            BasePermission.TYPE_NORMAL);
7706                    permissionMap.put(p.info.name, bp);
7707                }
7708
7709                if (bp.perm == null) {
7710                    if (bp.sourcePackage == null
7711                            || bp.sourcePackage.equals(p.info.packageName)) {
7712                        BasePermission tree = findPermissionTreeLP(p.info.name);
7713                        if (tree == null
7714                                || tree.sourcePackage.equals(p.info.packageName)) {
7715                            bp.packageSetting = pkgSetting;
7716                            bp.perm = p;
7717                            bp.uid = pkg.applicationInfo.uid;
7718                            bp.sourcePackage = p.info.packageName;
7719                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
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(p.info.name);
7727                            }
7728                        } else {
7729                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7730                                    + p.info.packageName + " ignored: base tree "
7731                                    + tree.name + " is from package "
7732                                    + tree.sourcePackage);
7733                        }
7734                    } else {
7735                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7736                                + p.info.packageName + " ignored: original from "
7737                                + bp.sourcePackage);
7738                    }
7739                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7740                    if (r == null) {
7741                        r = new StringBuilder(256);
7742                    } else {
7743                        r.append(' ');
7744                    }
7745                    r.append("DUP:");
7746                    r.append(p.info.name);
7747                }
7748                if (bp.perm == p) {
7749                    bp.protectionLevel = p.info.protectionLevel;
7750                }
7751            }
7752
7753            if (r != null) {
7754                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7755            }
7756
7757            N = pkg.instrumentation.size();
7758            r = null;
7759            for (i=0; i<N; i++) {
7760                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7761                a.info.packageName = pkg.applicationInfo.packageName;
7762                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7763                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7764                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7765                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7766                a.info.dataDir = pkg.applicationInfo.dataDir;
7767                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7768                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7769
7770                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7771                // need other information about the application, like the ABI and what not ?
7772                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7773                mInstrumentation.put(a.getComponentName(), a);
7774                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7775                    if (r == null) {
7776                        r = new StringBuilder(256);
7777                    } else {
7778                        r.append(' ');
7779                    }
7780                    r.append(a.info.name);
7781                }
7782            }
7783            if (r != null) {
7784                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7785            }
7786
7787            if (pkg.protectedBroadcasts != null) {
7788                N = pkg.protectedBroadcasts.size();
7789                for (i=0; i<N; i++) {
7790                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7791                }
7792            }
7793
7794            pkgSetting.setTimeStamp(scanFileTime);
7795
7796            // Create idmap files for pairs of (packages, overlay packages).
7797            // Note: "android", ie framework-res.apk, is handled by native layers.
7798            if (pkg.mOverlayTarget != null) {
7799                // This is an overlay package.
7800                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7801                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7802                        mOverlays.put(pkg.mOverlayTarget,
7803                                new ArrayMap<String, PackageParser.Package>());
7804                    }
7805                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7806                    map.put(pkg.packageName, pkg);
7807                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7808                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7809                        createIdmapFailed = true;
7810                    }
7811                }
7812            } else if (mOverlays.containsKey(pkg.packageName) &&
7813                    !pkg.packageName.equals("android")) {
7814                // This is a regular package, with one or more known overlay packages.
7815                createIdmapsForPackageLI(pkg);
7816            }
7817        }
7818
7819        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7820
7821        if (createIdmapFailed) {
7822            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7823                    "scanPackageLI failed to createIdmap");
7824        }
7825        return pkg;
7826    }
7827
7828    /**
7829     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7830     * is derived purely on the basis of the contents of {@code scanFile} and
7831     * {@code cpuAbiOverride}.
7832     *
7833     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7834     */
7835    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7836                                 String cpuAbiOverride, boolean extractLibs)
7837            throws PackageManagerException {
7838        // TODO: We can probably be smarter about this stuff. For installed apps,
7839        // we can calculate this information at install time once and for all. For
7840        // system apps, we can probably assume that this information doesn't change
7841        // after the first boot scan. As things stand, we do lots of unnecessary work.
7842
7843        // Give ourselves some initial paths; we'll come back for another
7844        // pass once we've determined ABI below.
7845        setNativeLibraryPaths(pkg);
7846
7847        // We would never need to extract libs for forward-locked and external packages,
7848        // since the container service will do it for us. We shouldn't attempt to
7849        // extract libs from system app when it was not updated.
7850        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7851                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7852            extractLibs = false;
7853        }
7854
7855        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7856        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7857
7858        NativeLibraryHelper.Handle handle = null;
7859        try {
7860            handle = NativeLibraryHelper.Handle.create(pkg);
7861            // TODO(multiArch): This can be null for apps that didn't go through the
7862            // usual installation process. We can calculate it again, like we
7863            // do during install time.
7864            //
7865            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7866            // unnecessary.
7867            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7868
7869            // Null out the abis so that they can be recalculated.
7870            pkg.applicationInfo.primaryCpuAbi = null;
7871            pkg.applicationInfo.secondaryCpuAbi = null;
7872            if (isMultiArch(pkg.applicationInfo)) {
7873                // Warn if we've set an abiOverride for multi-lib packages..
7874                // By definition, we need to copy both 32 and 64 bit libraries for
7875                // such packages.
7876                if (pkg.cpuAbiOverride != null
7877                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7878                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7879                }
7880
7881                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7882                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7883                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7884                    if (extractLibs) {
7885                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7886                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7887                                useIsaSpecificSubdirs);
7888                    } else {
7889                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7890                    }
7891                }
7892
7893                maybeThrowExceptionForMultiArchCopy(
7894                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7895
7896                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7897                    if (extractLibs) {
7898                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7899                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7900                                useIsaSpecificSubdirs);
7901                    } else {
7902                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7903                    }
7904                }
7905
7906                maybeThrowExceptionForMultiArchCopy(
7907                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7908
7909                if (abi64 >= 0) {
7910                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7911                }
7912
7913                if (abi32 >= 0) {
7914                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7915                    if (abi64 >= 0) {
7916                        pkg.applicationInfo.secondaryCpuAbi = abi;
7917                    } else {
7918                        pkg.applicationInfo.primaryCpuAbi = abi;
7919                    }
7920                }
7921            } else {
7922                String[] abiList = (cpuAbiOverride != null) ?
7923                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7924
7925                // Enable gross and lame hacks for apps that are built with old
7926                // SDK tools. We must scan their APKs for renderscript bitcode and
7927                // not launch them if it's present. Don't bother checking on devices
7928                // that don't have 64 bit support.
7929                boolean needsRenderScriptOverride = false;
7930                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7931                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7932                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7933                    needsRenderScriptOverride = true;
7934                }
7935
7936                final int copyRet;
7937                if (extractLibs) {
7938                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7939                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7940                } else {
7941                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7942                }
7943
7944                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7945                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7946                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7947                }
7948
7949                if (copyRet >= 0) {
7950                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7951                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7952                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7953                } else if (needsRenderScriptOverride) {
7954                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7955                }
7956            }
7957        } catch (IOException ioe) {
7958            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7959        } finally {
7960            IoUtils.closeQuietly(handle);
7961        }
7962
7963        // Now that we've calculated the ABIs and determined if it's an internal app,
7964        // we will go ahead and populate the nativeLibraryPath.
7965        setNativeLibraryPaths(pkg);
7966    }
7967
7968    /**
7969     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7970     * i.e, so that all packages can be run inside a single process if required.
7971     *
7972     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7973     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7974     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7975     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7976     * updating a package that belongs to a shared user.
7977     *
7978     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7979     * adds unnecessary complexity.
7980     */
7981    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7982            PackageParser.Package scannedPackage, boolean bootComplete) {
7983        String requiredInstructionSet = null;
7984        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7985            requiredInstructionSet = VMRuntime.getInstructionSet(
7986                     scannedPackage.applicationInfo.primaryCpuAbi);
7987        }
7988
7989        PackageSetting requirer = null;
7990        for (PackageSetting ps : packagesForUser) {
7991            // If packagesForUser contains scannedPackage, we skip it. This will happen
7992            // when scannedPackage is an update of an existing package. Without this check,
7993            // we will never be able to change the ABI of any package belonging to a shared
7994            // user, even if it's compatible with other packages.
7995            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7996                if (ps.primaryCpuAbiString == null) {
7997                    continue;
7998                }
7999
8000                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8001                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8002                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8003                    // this but there's not much we can do.
8004                    String errorMessage = "Instruction set mismatch, "
8005                            + ((requirer == null) ? "[caller]" : requirer)
8006                            + " requires " + requiredInstructionSet + " whereas " + ps
8007                            + " requires " + instructionSet;
8008                    Slog.w(TAG, errorMessage);
8009                }
8010
8011                if (requiredInstructionSet == null) {
8012                    requiredInstructionSet = instructionSet;
8013                    requirer = ps;
8014                }
8015            }
8016        }
8017
8018        if (requiredInstructionSet != null) {
8019            String adjustedAbi;
8020            if (requirer != null) {
8021                // requirer != null implies that either scannedPackage was null or that scannedPackage
8022                // did not require an ABI, in which case we have to adjust scannedPackage to match
8023                // the ABI of the set (which is the same as requirer's ABI)
8024                adjustedAbi = requirer.primaryCpuAbiString;
8025                if (scannedPackage != null) {
8026                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8027                }
8028            } else {
8029                // requirer == null implies that we're updating all ABIs in the set to
8030                // match scannedPackage.
8031                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8032            }
8033
8034            for (PackageSetting ps : packagesForUser) {
8035                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8036                    if (ps.primaryCpuAbiString != null) {
8037                        continue;
8038                    }
8039
8040                    ps.primaryCpuAbiString = adjustedAbi;
8041                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8042                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8043                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi);
8044                        try {
8045                            mInstaller.rmdex(ps.codePathString,
8046                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8047                        } catch (InstallerException ignored) {
8048                        }
8049                    }
8050                }
8051            }
8052        }
8053    }
8054
8055    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8056        synchronized (mPackages) {
8057            mResolverReplaced = true;
8058            // Set up information for custom user intent resolution activity.
8059            mResolveActivity.applicationInfo = pkg.applicationInfo;
8060            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8061            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8062            mResolveActivity.processName = pkg.applicationInfo.packageName;
8063            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8064            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8065                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8066            mResolveActivity.theme = 0;
8067            mResolveActivity.exported = true;
8068            mResolveActivity.enabled = true;
8069            mResolveInfo.activityInfo = mResolveActivity;
8070            mResolveInfo.priority = 0;
8071            mResolveInfo.preferredOrder = 0;
8072            mResolveInfo.match = 0;
8073            mResolveComponentName = mCustomResolverComponentName;
8074            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8075                    mResolveComponentName);
8076        }
8077    }
8078
8079    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8080        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8081
8082        // Set up information for ephemeral installer activity
8083        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8084        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8085        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8086        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8087        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8088        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8089                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8090        mEphemeralInstallerActivity.theme = 0;
8091        mEphemeralInstallerActivity.exported = true;
8092        mEphemeralInstallerActivity.enabled = true;
8093        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8094        mEphemeralInstallerInfo.priority = 0;
8095        mEphemeralInstallerInfo.preferredOrder = 0;
8096        mEphemeralInstallerInfo.match = 0;
8097
8098        if (DEBUG_EPHEMERAL) {
8099            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8100        }
8101    }
8102
8103    private static String calculateBundledApkRoot(final String codePathString) {
8104        final File codePath = new File(codePathString);
8105        final File codeRoot;
8106        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8107            codeRoot = Environment.getRootDirectory();
8108        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8109            codeRoot = Environment.getOemDirectory();
8110        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8111            codeRoot = Environment.getVendorDirectory();
8112        } else {
8113            // Unrecognized code path; take its top real segment as the apk root:
8114            // e.g. /something/app/blah.apk => /something
8115            try {
8116                File f = codePath.getCanonicalFile();
8117                File parent = f.getParentFile();    // non-null because codePath is a file
8118                File tmp;
8119                while ((tmp = parent.getParentFile()) != null) {
8120                    f = parent;
8121                    parent = tmp;
8122                }
8123                codeRoot = f;
8124                Slog.w(TAG, "Unrecognized code path "
8125                        + codePath + " - using " + codeRoot);
8126            } catch (IOException e) {
8127                // Can't canonicalize the code path -- shenanigans?
8128                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8129                return Environment.getRootDirectory().getPath();
8130            }
8131        }
8132        return codeRoot.getPath();
8133    }
8134
8135    /**
8136     * Derive and set the location of native libraries for the given package,
8137     * which varies depending on where and how the package was installed.
8138     */
8139    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8140        final ApplicationInfo info = pkg.applicationInfo;
8141        final String codePath = pkg.codePath;
8142        final File codeFile = new File(codePath);
8143        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8144        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8145
8146        info.nativeLibraryRootDir = null;
8147        info.nativeLibraryRootRequiresIsa = false;
8148        info.nativeLibraryDir = null;
8149        info.secondaryNativeLibraryDir = null;
8150
8151        if (isApkFile(codeFile)) {
8152            // Monolithic install
8153            if (bundledApp) {
8154                // If "/system/lib64/apkname" exists, assume that is the per-package
8155                // native library directory to use; otherwise use "/system/lib/apkname".
8156                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8157                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8158                        getPrimaryInstructionSet(info));
8159
8160                // This is a bundled system app so choose the path based on the ABI.
8161                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8162                // is just the default path.
8163                final String apkName = deriveCodePathName(codePath);
8164                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8165                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8166                        apkName).getAbsolutePath();
8167
8168                if (info.secondaryCpuAbi != null) {
8169                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8170                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8171                            secondaryLibDir, apkName).getAbsolutePath();
8172                }
8173            } else if (asecApp) {
8174                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8175                        .getAbsolutePath();
8176            } else {
8177                final String apkName = deriveCodePathName(codePath);
8178                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8179                        .getAbsolutePath();
8180            }
8181
8182            info.nativeLibraryRootRequiresIsa = false;
8183            info.nativeLibraryDir = info.nativeLibraryRootDir;
8184        } else {
8185            // Cluster install
8186            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8187            info.nativeLibraryRootRequiresIsa = true;
8188
8189            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8190                    getPrimaryInstructionSet(info)).getAbsolutePath();
8191
8192            if (info.secondaryCpuAbi != null) {
8193                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8194                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8195            }
8196        }
8197    }
8198
8199    /**
8200     * Calculate the abis and roots for a bundled app. These can uniquely
8201     * be determined from the contents of the system partition, i.e whether
8202     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8203     * of this information, and instead assume that the system was built
8204     * sensibly.
8205     */
8206    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8207                                           PackageSetting pkgSetting) {
8208        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8209
8210        // If "/system/lib64/apkname" exists, assume that is the per-package
8211        // native library directory to use; otherwise use "/system/lib/apkname".
8212        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8213        setBundledAppAbi(pkg, apkRoot, apkName);
8214        // pkgSetting might be null during rescan following uninstall of updates
8215        // to a bundled app, so accommodate that possibility.  The settings in
8216        // that case will be established later from the parsed package.
8217        //
8218        // If the settings aren't null, sync them up with what we've just derived.
8219        // note that apkRoot isn't stored in the package settings.
8220        if (pkgSetting != null) {
8221            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8222            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8223        }
8224    }
8225
8226    /**
8227     * Deduces the ABI of a bundled app and sets the relevant fields on the
8228     * parsed pkg object.
8229     *
8230     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8231     *        under which system libraries are installed.
8232     * @param apkName the name of the installed package.
8233     */
8234    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8235        final File codeFile = new File(pkg.codePath);
8236
8237        final boolean has64BitLibs;
8238        final boolean has32BitLibs;
8239        if (isApkFile(codeFile)) {
8240            // Monolithic install
8241            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8242            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8243        } else {
8244            // Cluster install
8245            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8246            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8247                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8248                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8249                has64BitLibs = (new File(rootDir, isa)).exists();
8250            } else {
8251                has64BitLibs = false;
8252            }
8253            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8254                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8255                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8256                has32BitLibs = (new File(rootDir, isa)).exists();
8257            } else {
8258                has32BitLibs = false;
8259            }
8260        }
8261
8262        if (has64BitLibs && !has32BitLibs) {
8263            // The package has 64 bit libs, but not 32 bit libs. Its primary
8264            // ABI should be 64 bit. We can safely assume here that the bundled
8265            // native libraries correspond to the most preferred ABI in the list.
8266
8267            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8268            pkg.applicationInfo.secondaryCpuAbi = null;
8269        } else if (has32BitLibs && !has64BitLibs) {
8270            // The package has 32 bit libs but not 64 bit libs. Its primary
8271            // ABI should be 32 bit.
8272
8273            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8274            pkg.applicationInfo.secondaryCpuAbi = null;
8275        } else if (has32BitLibs && has64BitLibs) {
8276            // The application has both 64 and 32 bit bundled libraries. We check
8277            // here that the app declares multiArch support, and warn if it doesn't.
8278            //
8279            // We will be lenient here and record both ABIs. The primary will be the
8280            // ABI that's higher on the list, i.e, a device that's configured to prefer
8281            // 64 bit apps will see a 64 bit primary ABI,
8282
8283            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8284                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8285            }
8286
8287            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8288                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8289                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8290            } else {
8291                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8292                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8293            }
8294        } else {
8295            pkg.applicationInfo.primaryCpuAbi = null;
8296            pkg.applicationInfo.secondaryCpuAbi = null;
8297        }
8298    }
8299
8300    private void killApplication(String pkgName, int appId, String reason) {
8301        // Request the ActivityManager to kill the process(only for existing packages)
8302        // so that we do not end up in a confused state while the user is still using the older
8303        // version of the application while the new one gets installed.
8304        IActivityManager am = ActivityManagerNative.getDefault();
8305        if (am != null) {
8306            try {
8307                am.killApplicationWithAppId(pkgName, appId, reason);
8308            } catch (RemoteException e) {
8309            }
8310        }
8311    }
8312
8313    void removePackageLI(PackageSetting ps, boolean chatty) {
8314        if (DEBUG_INSTALL) {
8315            if (chatty)
8316                Log.d(TAG, "Removing package " + ps.name);
8317        }
8318
8319        // writer
8320        synchronized (mPackages) {
8321            mPackages.remove(ps.name);
8322            final PackageParser.Package pkg = ps.pkg;
8323            if (pkg != null) {
8324                cleanPackageDataStructuresLILPw(pkg, chatty);
8325            }
8326        }
8327    }
8328
8329    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8330        if (DEBUG_INSTALL) {
8331            if (chatty)
8332                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8333        }
8334
8335        // writer
8336        synchronized (mPackages) {
8337            mPackages.remove(pkg.applicationInfo.packageName);
8338            cleanPackageDataStructuresLILPw(pkg, chatty);
8339        }
8340    }
8341
8342    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8343        int N = pkg.providers.size();
8344        StringBuilder r = null;
8345        int i;
8346        for (i=0; i<N; i++) {
8347            PackageParser.Provider p = pkg.providers.get(i);
8348            mProviders.removeProvider(p);
8349            if (p.info.authority == null) {
8350
8351                /* There was another ContentProvider with this authority when
8352                 * this app was installed so this authority is null,
8353                 * Ignore it as we don't have to unregister the provider.
8354                 */
8355                continue;
8356            }
8357            String names[] = p.info.authority.split(";");
8358            for (int j = 0; j < names.length; j++) {
8359                if (mProvidersByAuthority.get(names[j]) == p) {
8360                    mProvidersByAuthority.remove(names[j]);
8361                    if (DEBUG_REMOVE) {
8362                        if (chatty)
8363                            Log.d(TAG, "Unregistered content provider: " + names[j]
8364                                    + ", className = " + p.info.name + ", isSyncable = "
8365                                    + p.info.isSyncable);
8366                    }
8367                }
8368            }
8369            if (DEBUG_REMOVE && chatty) {
8370                if (r == null) {
8371                    r = new StringBuilder(256);
8372                } else {
8373                    r.append(' ');
8374                }
8375                r.append(p.info.name);
8376            }
8377        }
8378        if (r != null) {
8379            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8380        }
8381
8382        N = pkg.services.size();
8383        r = null;
8384        for (i=0; i<N; i++) {
8385            PackageParser.Service s = pkg.services.get(i);
8386            mServices.removeService(s);
8387            if (chatty) {
8388                if (r == null) {
8389                    r = new StringBuilder(256);
8390                } else {
8391                    r.append(' ');
8392                }
8393                r.append(s.info.name);
8394            }
8395        }
8396        if (r != null) {
8397            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8398        }
8399
8400        N = pkg.receivers.size();
8401        r = null;
8402        for (i=0; i<N; i++) {
8403            PackageParser.Activity a = pkg.receivers.get(i);
8404            mReceivers.removeActivity(a, "receiver");
8405            if (DEBUG_REMOVE && chatty) {
8406                if (r == null) {
8407                    r = new StringBuilder(256);
8408                } else {
8409                    r.append(' ');
8410                }
8411                r.append(a.info.name);
8412            }
8413        }
8414        if (r != null) {
8415            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8416        }
8417
8418        N = pkg.activities.size();
8419        r = null;
8420        for (i=0; i<N; i++) {
8421            PackageParser.Activity a = pkg.activities.get(i);
8422            mActivities.removeActivity(a, "activity");
8423            if (DEBUG_REMOVE && chatty) {
8424                if (r == null) {
8425                    r = new StringBuilder(256);
8426                } else {
8427                    r.append(' ');
8428                }
8429                r.append(a.info.name);
8430            }
8431        }
8432        if (r != null) {
8433            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8434        }
8435
8436        N = pkg.permissions.size();
8437        r = null;
8438        for (i=0; i<N; i++) {
8439            PackageParser.Permission p = pkg.permissions.get(i);
8440            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8441            if (bp == null) {
8442                bp = mSettings.mPermissionTrees.get(p.info.name);
8443            }
8444            if (bp != null && bp.perm == p) {
8445                bp.perm = null;
8446                if (DEBUG_REMOVE && chatty) {
8447                    if (r == null) {
8448                        r = new StringBuilder(256);
8449                    } else {
8450                        r.append(' ');
8451                    }
8452                    r.append(p.info.name);
8453                }
8454            }
8455            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8456                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8457                if (appOpPkgs != null) {
8458                    appOpPkgs.remove(pkg.packageName);
8459                }
8460            }
8461        }
8462        if (r != null) {
8463            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8464        }
8465
8466        N = pkg.requestedPermissions.size();
8467        r = null;
8468        for (i=0; i<N; i++) {
8469            String perm = pkg.requestedPermissions.get(i);
8470            BasePermission bp = mSettings.mPermissions.get(perm);
8471            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8472                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8473                if (appOpPkgs != null) {
8474                    appOpPkgs.remove(pkg.packageName);
8475                    if (appOpPkgs.isEmpty()) {
8476                        mAppOpPermissionPackages.remove(perm);
8477                    }
8478                }
8479            }
8480        }
8481        if (r != null) {
8482            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8483        }
8484
8485        N = pkg.instrumentation.size();
8486        r = null;
8487        for (i=0; i<N; i++) {
8488            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8489            mInstrumentation.remove(a.getComponentName());
8490            if (DEBUG_REMOVE && chatty) {
8491                if (r == null) {
8492                    r = new StringBuilder(256);
8493                } else {
8494                    r.append(' ');
8495                }
8496                r.append(a.info.name);
8497            }
8498        }
8499        if (r != null) {
8500            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8501        }
8502
8503        r = null;
8504        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8505            // Only system apps can hold shared libraries.
8506            if (pkg.libraryNames != null) {
8507                for (i=0; i<pkg.libraryNames.size(); i++) {
8508                    String name = pkg.libraryNames.get(i);
8509                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8510                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8511                        mSharedLibraries.remove(name);
8512                        if (DEBUG_REMOVE && chatty) {
8513                            if (r == null) {
8514                                r = new StringBuilder(256);
8515                            } else {
8516                                r.append(' ');
8517                            }
8518                            r.append(name);
8519                        }
8520                    }
8521                }
8522            }
8523        }
8524        if (r != null) {
8525            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8526        }
8527    }
8528
8529    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8530        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8531            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8532                return true;
8533            }
8534        }
8535        return false;
8536    }
8537
8538    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8539    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8540    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8541
8542    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8543            int flags) {
8544        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8545        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8546    }
8547
8548    private void updatePermissionsLPw(String changingPkg,
8549            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8550        // Make sure there are no dangling permission trees.
8551        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8552        while (it.hasNext()) {
8553            final BasePermission bp = it.next();
8554            if (bp.packageSetting == null) {
8555                // We may not yet have parsed the package, so just see if
8556                // we still know about its settings.
8557                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8558            }
8559            if (bp.packageSetting == null) {
8560                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8561                        + " from package " + bp.sourcePackage);
8562                it.remove();
8563            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8564                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8565                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8566                            + " from package " + bp.sourcePackage);
8567                    flags |= UPDATE_PERMISSIONS_ALL;
8568                    it.remove();
8569                }
8570            }
8571        }
8572
8573        // Make sure all dynamic permissions have been assigned to a package,
8574        // and make sure there are no dangling permissions.
8575        it = mSettings.mPermissions.values().iterator();
8576        while (it.hasNext()) {
8577            final BasePermission bp = it.next();
8578            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8579                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8580                        + bp.name + " pkg=" + bp.sourcePackage
8581                        + " info=" + bp.pendingInfo);
8582                if (bp.packageSetting == null && bp.pendingInfo != null) {
8583                    final BasePermission tree = findPermissionTreeLP(bp.name);
8584                    if (tree != null && tree.perm != null) {
8585                        bp.packageSetting = tree.packageSetting;
8586                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8587                                new PermissionInfo(bp.pendingInfo));
8588                        bp.perm.info.packageName = tree.perm.info.packageName;
8589                        bp.perm.info.name = bp.name;
8590                        bp.uid = tree.uid;
8591                    }
8592                }
8593            }
8594            if (bp.packageSetting == null) {
8595                // We may not yet have parsed the package, so just see if
8596                // we still know about its settings.
8597                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8598            }
8599            if (bp.packageSetting == null) {
8600                Slog.w(TAG, "Removing dangling permission: " + bp.name
8601                        + " from package " + bp.sourcePackage);
8602                it.remove();
8603            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8604                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8605                    Slog.i(TAG, "Removing old permission: " + bp.name
8606                            + " from package " + bp.sourcePackage);
8607                    flags |= UPDATE_PERMISSIONS_ALL;
8608                    it.remove();
8609                }
8610            }
8611        }
8612
8613        // Now update the permissions for all packages, in particular
8614        // replace the granted permissions of the system packages.
8615        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8616            for (PackageParser.Package pkg : mPackages.values()) {
8617                if (pkg != pkgInfo) {
8618                    // Only replace for packages on requested volume
8619                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8620                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8621                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8622                    grantPermissionsLPw(pkg, replace, changingPkg);
8623                }
8624            }
8625        }
8626
8627        if (pkgInfo != null) {
8628            // Only replace for packages on requested volume
8629            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8630            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8631                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8632            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8633        }
8634    }
8635
8636    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8637            String packageOfInterest) {
8638        // IMPORTANT: There are two types of permissions: install and runtime.
8639        // Install time permissions are granted when the app is installed to
8640        // all device users and users added in the future. Runtime permissions
8641        // are granted at runtime explicitly to specific users. Normal and signature
8642        // protected permissions are install time permissions. Dangerous permissions
8643        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8644        // otherwise they are runtime permissions. This function does not manage
8645        // runtime permissions except for the case an app targeting Lollipop MR1
8646        // being upgraded to target a newer SDK, in which case dangerous permissions
8647        // are transformed from install time to runtime ones.
8648
8649        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8650        if (ps == null) {
8651            return;
8652        }
8653
8654        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8655
8656        PermissionsState permissionsState = ps.getPermissionsState();
8657        PermissionsState origPermissions = permissionsState;
8658
8659        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8660
8661        boolean runtimePermissionsRevoked = false;
8662        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8663
8664        boolean changedInstallPermission = false;
8665
8666        if (replace) {
8667            ps.installPermissionsFixed = false;
8668            if (!ps.isSharedUser()) {
8669                origPermissions = new PermissionsState(permissionsState);
8670                permissionsState.reset();
8671            } else {
8672                // We need to know only about runtime permission changes since the
8673                // calling code always writes the install permissions state but
8674                // the runtime ones are written only if changed. The only cases of
8675                // changed runtime permissions here are promotion of an install to
8676                // runtime and revocation of a runtime from a shared user.
8677                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8678                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8679                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8680                    runtimePermissionsRevoked = true;
8681                }
8682            }
8683        }
8684
8685        permissionsState.setGlobalGids(mGlobalGids);
8686
8687        final int N = pkg.requestedPermissions.size();
8688        for (int i=0; i<N; i++) {
8689            final String name = pkg.requestedPermissions.get(i);
8690            final BasePermission bp = mSettings.mPermissions.get(name);
8691
8692            if (DEBUG_INSTALL) {
8693                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8694            }
8695
8696            if (bp == null || bp.packageSetting == null) {
8697                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8698                    Slog.w(TAG, "Unknown permission " + name
8699                            + " in package " + pkg.packageName);
8700                }
8701                continue;
8702            }
8703
8704            final String perm = bp.name;
8705            boolean allowedSig = false;
8706            int grant = GRANT_DENIED;
8707
8708            // Keep track of app op permissions.
8709            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8710                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8711                if (pkgs == null) {
8712                    pkgs = new ArraySet<>();
8713                    mAppOpPermissionPackages.put(bp.name, pkgs);
8714                }
8715                pkgs.add(pkg.packageName);
8716            }
8717
8718            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8719            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8720                    >= Build.VERSION_CODES.M;
8721            switch (level) {
8722                case PermissionInfo.PROTECTION_NORMAL: {
8723                    // For all apps normal permissions are install time ones.
8724                    grant = GRANT_INSTALL;
8725                } break;
8726
8727                case PermissionInfo.PROTECTION_DANGEROUS: {
8728                    // If a permission review is required for legacy apps we represent
8729                    // their permissions as always granted runtime ones since we need
8730                    // to keep the review required permission flag per user while an
8731                    // install permission's state is shared across all users.
8732                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8733                        // For legacy apps dangerous permissions are install time ones.
8734                        grant = GRANT_INSTALL;
8735                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8736                        // For legacy apps that became modern, install becomes runtime.
8737                        grant = GRANT_UPGRADE;
8738                    } else if (mPromoteSystemApps
8739                            && isSystemApp(ps)
8740                            && mExistingSystemPackages.contains(ps.name)) {
8741                        // For legacy system apps, install becomes runtime.
8742                        // We cannot check hasInstallPermission() for system apps since those
8743                        // permissions were granted implicitly and not persisted pre-M.
8744                        grant = GRANT_UPGRADE;
8745                    } else {
8746                        // For modern apps keep runtime permissions unchanged.
8747                        grant = GRANT_RUNTIME;
8748                    }
8749                } break;
8750
8751                case PermissionInfo.PROTECTION_SIGNATURE: {
8752                    // For all apps signature permissions are install time ones.
8753                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8754                    if (allowedSig) {
8755                        grant = GRANT_INSTALL;
8756                    }
8757                } break;
8758            }
8759
8760            if (DEBUG_INSTALL) {
8761                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8762            }
8763
8764            if (grant != GRANT_DENIED) {
8765                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8766                    // If this is an existing, non-system package, then
8767                    // we can't add any new permissions to it.
8768                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8769                        // Except...  if this is a permission that was added
8770                        // to the platform (note: need to only do this when
8771                        // updating the platform).
8772                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8773                            grant = GRANT_DENIED;
8774                        }
8775                    }
8776                }
8777
8778                switch (grant) {
8779                    case GRANT_INSTALL: {
8780                        // Revoke this as runtime permission to handle the case of
8781                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8782                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8783                            if (origPermissions.getRuntimePermissionState(
8784                                    bp.name, userId) != null) {
8785                                // Revoke the runtime permission and clear the flags.
8786                                origPermissions.revokeRuntimePermission(bp, userId);
8787                                origPermissions.updatePermissionFlags(bp, userId,
8788                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8789                                // If we revoked a permission permission, we have to write.
8790                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8791                                        changedRuntimePermissionUserIds, userId);
8792                            }
8793                        }
8794                        // Grant an install permission.
8795                        if (permissionsState.grantInstallPermission(bp) !=
8796                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8797                            changedInstallPermission = true;
8798                        }
8799                    } break;
8800
8801                    case GRANT_RUNTIME: {
8802                        // Grant previously granted runtime permissions.
8803                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8804                            PermissionState permissionState = origPermissions
8805                                    .getRuntimePermissionState(bp.name, userId);
8806                            int flags = permissionState != null
8807                                    ? permissionState.getFlags() : 0;
8808                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8809                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8810                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8811                                    // If we cannot put the permission as it was, we have to write.
8812                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8813                                            changedRuntimePermissionUserIds, userId);
8814                                }
8815                                // If the app supports runtime permissions no need for a review.
8816                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8817                                        && appSupportsRuntimePermissions
8818                                        && (flags & PackageManager
8819                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8820                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8821                                    // Since we changed the flags, we have to write.
8822                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8823                                            changedRuntimePermissionUserIds, userId);
8824                                }
8825                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8826                                    && !appSupportsRuntimePermissions) {
8827                                // For legacy apps that need a permission review, every new
8828                                // runtime permission is granted but it is pending a review.
8829                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8830                                    permissionsState.grantRuntimePermission(bp, userId);
8831                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8832                                    // We changed the permission and flags, hence have to write.
8833                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8834                                            changedRuntimePermissionUserIds, userId);
8835                                }
8836                            }
8837                            // Propagate the permission flags.
8838                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8839                        }
8840                    } break;
8841
8842                    case GRANT_UPGRADE: {
8843                        // Grant runtime permissions for a previously held install permission.
8844                        PermissionState permissionState = origPermissions
8845                                .getInstallPermissionState(bp.name);
8846                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8847
8848                        if (origPermissions.revokeInstallPermission(bp)
8849                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8850                            // We will be transferring the permission flags, so clear them.
8851                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8852                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8853                            changedInstallPermission = true;
8854                        }
8855
8856                        // If the permission is not to be promoted to runtime we ignore it and
8857                        // also its other flags as they are not applicable to install permissions.
8858                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8859                            for (int userId : currentUserIds) {
8860                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8861                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8862                                    // Transfer the permission flags.
8863                                    permissionsState.updatePermissionFlags(bp, userId,
8864                                            flags, flags);
8865                                    // If we granted the permission, we have to write.
8866                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8867                                            changedRuntimePermissionUserIds, userId);
8868                                }
8869                            }
8870                        }
8871                    } break;
8872
8873                    default: {
8874                        if (packageOfInterest == null
8875                                || packageOfInterest.equals(pkg.packageName)) {
8876                            Slog.w(TAG, "Not granting permission " + perm
8877                                    + " to package " + pkg.packageName
8878                                    + " because it was previously installed without");
8879                        }
8880                    } break;
8881                }
8882            } else {
8883                if (permissionsState.revokeInstallPermission(bp) !=
8884                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8885                    // Also drop the permission flags.
8886                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8887                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8888                    changedInstallPermission = true;
8889                    Slog.i(TAG, "Un-granting permission " + perm
8890                            + " from package " + pkg.packageName
8891                            + " (protectionLevel=" + bp.protectionLevel
8892                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8893                            + ")");
8894                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8895                    // Don't print warning for app op permissions, since it is fine for them
8896                    // not to be granted, there is a UI for the user to decide.
8897                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8898                        Slog.w(TAG, "Not granting permission " + perm
8899                                + " to package " + pkg.packageName
8900                                + " (protectionLevel=" + bp.protectionLevel
8901                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8902                                + ")");
8903                    }
8904                }
8905            }
8906        }
8907
8908        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8909                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8910            // This is the first that we have heard about this package, so the
8911            // permissions we have now selected are fixed until explicitly
8912            // changed.
8913            ps.installPermissionsFixed = true;
8914        }
8915
8916        // Persist the runtime permissions state for users with changes. If permissions
8917        // were revoked because no app in the shared user declares them we have to
8918        // write synchronously to avoid losing runtime permissions state.
8919        for (int userId : changedRuntimePermissionUserIds) {
8920            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8921        }
8922
8923        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8924    }
8925
8926    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8927        boolean allowed = false;
8928        final int NP = PackageParser.NEW_PERMISSIONS.length;
8929        for (int ip=0; ip<NP; ip++) {
8930            final PackageParser.NewPermissionInfo npi
8931                    = PackageParser.NEW_PERMISSIONS[ip];
8932            if (npi.name.equals(perm)
8933                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8934                allowed = true;
8935                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8936                        + pkg.packageName);
8937                break;
8938            }
8939        }
8940        return allowed;
8941    }
8942
8943    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8944            BasePermission bp, PermissionsState origPermissions) {
8945        boolean allowed;
8946        allowed = (compareSignatures(
8947                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8948                        == PackageManager.SIGNATURE_MATCH)
8949                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8950                        == PackageManager.SIGNATURE_MATCH);
8951        if (!allowed && (bp.protectionLevel
8952                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8953            if (isSystemApp(pkg)) {
8954                // For updated system applications, a system permission
8955                // is granted only if it had been defined by the original application.
8956                if (pkg.isUpdatedSystemApp()) {
8957                    final PackageSetting sysPs = mSettings
8958                            .getDisabledSystemPkgLPr(pkg.packageName);
8959                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8960                        // If the original was granted this permission, we take
8961                        // that grant decision as read and propagate it to the
8962                        // update.
8963                        if (sysPs.isPrivileged()) {
8964                            allowed = true;
8965                        }
8966                    } else {
8967                        // The system apk may have been updated with an older
8968                        // version of the one on the data partition, but which
8969                        // granted a new system permission that it didn't have
8970                        // before.  In this case we do want to allow the app to
8971                        // now get the new permission if the ancestral apk is
8972                        // privileged to get it.
8973                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8974                            for (int j=0;
8975                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8976                                if (perm.equals(
8977                                        sysPs.pkg.requestedPermissions.get(j))) {
8978                                    allowed = true;
8979                                    break;
8980                                }
8981                            }
8982                        }
8983                    }
8984                } else {
8985                    allowed = isPrivilegedApp(pkg);
8986                }
8987            }
8988        }
8989        if (!allowed) {
8990            if (!allowed && (bp.protectionLevel
8991                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8992                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8993                // If this was a previously normal/dangerous permission that got moved
8994                // to a system permission as part of the runtime permission redesign, then
8995                // we still want to blindly grant it to old apps.
8996                allowed = true;
8997            }
8998            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8999                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9000                // If this permission is to be granted to the system installer and
9001                // this app is an installer, then it gets the permission.
9002                allowed = true;
9003            }
9004            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9005                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9006                // If this permission is to be granted to the system verifier and
9007                // this app is a verifier, then it gets the permission.
9008                allowed = true;
9009            }
9010            if (!allowed && (bp.protectionLevel
9011                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9012                    && isSystemApp(pkg)) {
9013                // Any pre-installed system app is allowed to get this permission.
9014                allowed = true;
9015            }
9016            if (!allowed && (bp.protectionLevel
9017                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9018                // For development permissions, a development permission
9019                // is granted only if it was already granted.
9020                allowed = origPermissions.hasInstallPermission(perm);
9021            }
9022        }
9023        return allowed;
9024    }
9025
9026    final class ActivityIntentResolver
9027            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9028        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9029                boolean defaultOnly, int userId) {
9030            if (!sUserManager.exists(userId)) return null;
9031            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9032            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9033        }
9034
9035        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9036                int userId) {
9037            if (!sUserManager.exists(userId)) return null;
9038            mFlags = flags;
9039            return super.queryIntent(intent, resolvedType,
9040                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9041        }
9042
9043        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9044                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9045            if (!sUserManager.exists(userId)) return null;
9046            if (packageActivities == null) {
9047                return null;
9048            }
9049            mFlags = flags;
9050            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9051            final int N = packageActivities.size();
9052            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9053                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9054
9055            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9056            for (int i = 0; i < N; ++i) {
9057                intentFilters = packageActivities.get(i).intents;
9058                if (intentFilters != null && intentFilters.size() > 0) {
9059                    PackageParser.ActivityIntentInfo[] array =
9060                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9061                    intentFilters.toArray(array);
9062                    listCut.add(array);
9063                }
9064            }
9065            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9066        }
9067
9068        public final void addActivity(PackageParser.Activity a, String type) {
9069            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9070            mActivities.put(a.getComponentName(), a);
9071            if (DEBUG_SHOW_INFO)
9072                Log.v(
9073                TAG, "  " + type + " " +
9074                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9075            if (DEBUG_SHOW_INFO)
9076                Log.v(TAG, "    Class=" + a.info.name);
9077            final int NI = a.intents.size();
9078            for (int j=0; j<NI; j++) {
9079                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9080                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9081                    intent.setPriority(0);
9082                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9083                            + a.className + " with priority > 0, forcing to 0");
9084                }
9085                if (DEBUG_SHOW_INFO) {
9086                    Log.v(TAG, "    IntentFilter:");
9087                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9088                }
9089                if (!intent.debugCheck()) {
9090                    Log.w(TAG, "==> For Activity " + a.info.name);
9091                }
9092                addFilter(intent);
9093            }
9094        }
9095
9096        public final void removeActivity(PackageParser.Activity a, String type) {
9097            mActivities.remove(a.getComponentName());
9098            if (DEBUG_SHOW_INFO) {
9099                Log.v(TAG, "  " + type + " "
9100                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9101                                : a.info.name) + ":");
9102                Log.v(TAG, "    Class=" + a.info.name);
9103            }
9104            final int NI = a.intents.size();
9105            for (int j=0; j<NI; j++) {
9106                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9107                if (DEBUG_SHOW_INFO) {
9108                    Log.v(TAG, "    IntentFilter:");
9109                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9110                }
9111                removeFilter(intent);
9112            }
9113        }
9114
9115        @Override
9116        protected boolean allowFilterResult(
9117                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9118            ActivityInfo filterAi = filter.activity.info;
9119            for (int i=dest.size()-1; i>=0; i--) {
9120                ActivityInfo destAi = dest.get(i).activityInfo;
9121                if (destAi.name == filterAi.name
9122                        && destAi.packageName == filterAi.packageName) {
9123                    return false;
9124                }
9125            }
9126            return true;
9127        }
9128
9129        @Override
9130        protected ActivityIntentInfo[] newArray(int size) {
9131            return new ActivityIntentInfo[size];
9132        }
9133
9134        @Override
9135        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9136            if (!sUserManager.exists(userId)) return true;
9137            PackageParser.Package p = filter.activity.owner;
9138            if (p != null) {
9139                PackageSetting ps = (PackageSetting)p.mExtras;
9140                if (ps != null) {
9141                    // System apps are never considered stopped for purposes of
9142                    // filtering, because there may be no way for the user to
9143                    // actually re-launch them.
9144                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9145                            && ps.getStopped(userId);
9146                }
9147            }
9148            return false;
9149        }
9150
9151        @Override
9152        protected boolean isPackageForFilter(String packageName,
9153                PackageParser.ActivityIntentInfo info) {
9154            return packageName.equals(info.activity.owner.packageName);
9155        }
9156
9157        @Override
9158        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9159                int match, int userId) {
9160            if (!sUserManager.exists(userId)) return null;
9161            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9162                return null;
9163            }
9164            final PackageParser.Activity activity = info.activity;
9165            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9166            if (ps == null) {
9167                return null;
9168            }
9169            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9170                    ps.readUserState(userId), userId);
9171            if (ai == null) {
9172                return null;
9173            }
9174            final ResolveInfo res = new ResolveInfo();
9175            res.activityInfo = ai;
9176            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9177                res.filter = info;
9178            }
9179            if (info != null) {
9180                res.handleAllWebDataURI = info.handleAllWebDataURI();
9181            }
9182            res.priority = info.getPriority();
9183            res.preferredOrder = activity.owner.mPreferredOrder;
9184            //System.out.println("Result: " + res.activityInfo.className +
9185            //                   " = " + res.priority);
9186            res.match = match;
9187            res.isDefault = info.hasDefault;
9188            res.labelRes = info.labelRes;
9189            res.nonLocalizedLabel = info.nonLocalizedLabel;
9190            if (userNeedsBadging(userId)) {
9191                res.noResourceId = true;
9192            } else {
9193                res.icon = info.icon;
9194            }
9195            res.iconResourceId = info.icon;
9196            res.system = res.activityInfo.applicationInfo.isSystemApp();
9197            return res;
9198        }
9199
9200        @Override
9201        protected void sortResults(List<ResolveInfo> results) {
9202            Collections.sort(results, mResolvePrioritySorter);
9203        }
9204
9205        @Override
9206        protected void dumpFilter(PrintWriter out, String prefix,
9207                PackageParser.ActivityIntentInfo filter) {
9208            out.print(prefix); out.print(
9209                    Integer.toHexString(System.identityHashCode(filter.activity)));
9210                    out.print(' ');
9211                    filter.activity.printComponentShortName(out);
9212                    out.print(" filter ");
9213                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9214        }
9215
9216        @Override
9217        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9218            return filter.activity;
9219        }
9220
9221        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9222            PackageParser.Activity activity = (PackageParser.Activity)label;
9223            out.print(prefix); out.print(
9224                    Integer.toHexString(System.identityHashCode(activity)));
9225                    out.print(' ');
9226                    activity.printComponentShortName(out);
9227            if (count > 1) {
9228                out.print(" ("); out.print(count); out.print(" filters)");
9229            }
9230            out.println();
9231        }
9232
9233//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9234//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9235//            final List<ResolveInfo> retList = Lists.newArrayList();
9236//            while (i.hasNext()) {
9237//                final ResolveInfo resolveInfo = i.next();
9238//                if (isEnabledLP(resolveInfo.activityInfo)) {
9239//                    retList.add(resolveInfo);
9240//                }
9241//            }
9242//            return retList;
9243//        }
9244
9245        // Keys are String (activity class name), values are Activity.
9246        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9247                = new ArrayMap<ComponentName, PackageParser.Activity>();
9248        private int mFlags;
9249    }
9250
9251    private final class ServiceIntentResolver
9252            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9253        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9254                boolean defaultOnly, int userId) {
9255            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9256            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9257        }
9258
9259        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9260                int userId) {
9261            if (!sUserManager.exists(userId)) return null;
9262            mFlags = flags;
9263            return super.queryIntent(intent, resolvedType,
9264                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9265        }
9266
9267        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9268                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9269            if (!sUserManager.exists(userId)) return null;
9270            if (packageServices == null) {
9271                return null;
9272            }
9273            mFlags = flags;
9274            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9275            final int N = packageServices.size();
9276            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9277                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9278
9279            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9280            for (int i = 0; i < N; ++i) {
9281                intentFilters = packageServices.get(i).intents;
9282                if (intentFilters != null && intentFilters.size() > 0) {
9283                    PackageParser.ServiceIntentInfo[] array =
9284                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9285                    intentFilters.toArray(array);
9286                    listCut.add(array);
9287                }
9288            }
9289            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9290        }
9291
9292        public final void addService(PackageParser.Service s) {
9293            mServices.put(s.getComponentName(), s);
9294            if (DEBUG_SHOW_INFO) {
9295                Log.v(TAG, "  "
9296                        + (s.info.nonLocalizedLabel != null
9297                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9298                Log.v(TAG, "    Class=" + s.info.name);
9299            }
9300            final int NI = s.intents.size();
9301            int j;
9302            for (j=0; j<NI; j++) {
9303                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9304                if (DEBUG_SHOW_INFO) {
9305                    Log.v(TAG, "    IntentFilter:");
9306                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9307                }
9308                if (!intent.debugCheck()) {
9309                    Log.w(TAG, "==> For Service " + s.info.name);
9310                }
9311                addFilter(intent);
9312            }
9313        }
9314
9315        public final void removeService(PackageParser.Service s) {
9316            mServices.remove(s.getComponentName());
9317            if (DEBUG_SHOW_INFO) {
9318                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9319                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9320                Log.v(TAG, "    Class=" + s.info.name);
9321            }
9322            final int NI = s.intents.size();
9323            int j;
9324            for (j=0; j<NI; j++) {
9325                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9326                if (DEBUG_SHOW_INFO) {
9327                    Log.v(TAG, "    IntentFilter:");
9328                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9329                }
9330                removeFilter(intent);
9331            }
9332        }
9333
9334        @Override
9335        protected boolean allowFilterResult(
9336                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9337            ServiceInfo filterSi = filter.service.info;
9338            for (int i=dest.size()-1; i>=0; i--) {
9339                ServiceInfo destAi = dest.get(i).serviceInfo;
9340                if (destAi.name == filterSi.name
9341                        && destAi.packageName == filterSi.packageName) {
9342                    return false;
9343                }
9344            }
9345            return true;
9346        }
9347
9348        @Override
9349        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9350            return new PackageParser.ServiceIntentInfo[size];
9351        }
9352
9353        @Override
9354        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9355            if (!sUserManager.exists(userId)) return true;
9356            PackageParser.Package p = filter.service.owner;
9357            if (p != null) {
9358                PackageSetting ps = (PackageSetting)p.mExtras;
9359                if (ps != null) {
9360                    // System apps are never considered stopped for purposes of
9361                    // filtering, because there may be no way for the user to
9362                    // actually re-launch them.
9363                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9364                            && ps.getStopped(userId);
9365                }
9366            }
9367            return false;
9368        }
9369
9370        @Override
9371        protected boolean isPackageForFilter(String packageName,
9372                PackageParser.ServiceIntentInfo info) {
9373            return packageName.equals(info.service.owner.packageName);
9374        }
9375
9376        @Override
9377        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9378                int match, int userId) {
9379            if (!sUserManager.exists(userId)) return null;
9380            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9381            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9382                return null;
9383            }
9384            final PackageParser.Service service = info.service;
9385            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9386            if (ps == null) {
9387                return null;
9388            }
9389            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9390                    ps.readUserState(userId), userId);
9391            if (si == null) {
9392                return null;
9393            }
9394            final ResolveInfo res = new ResolveInfo();
9395            res.serviceInfo = si;
9396            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9397                res.filter = filter;
9398            }
9399            res.priority = info.getPriority();
9400            res.preferredOrder = service.owner.mPreferredOrder;
9401            res.match = match;
9402            res.isDefault = info.hasDefault;
9403            res.labelRes = info.labelRes;
9404            res.nonLocalizedLabel = info.nonLocalizedLabel;
9405            res.icon = info.icon;
9406            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9407            return res;
9408        }
9409
9410        @Override
9411        protected void sortResults(List<ResolveInfo> results) {
9412            Collections.sort(results, mResolvePrioritySorter);
9413        }
9414
9415        @Override
9416        protected void dumpFilter(PrintWriter out, String prefix,
9417                PackageParser.ServiceIntentInfo filter) {
9418            out.print(prefix); out.print(
9419                    Integer.toHexString(System.identityHashCode(filter.service)));
9420                    out.print(' ');
9421                    filter.service.printComponentShortName(out);
9422                    out.print(" filter ");
9423                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9424        }
9425
9426        @Override
9427        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9428            return filter.service;
9429        }
9430
9431        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9432            PackageParser.Service service = (PackageParser.Service)label;
9433            out.print(prefix); out.print(
9434                    Integer.toHexString(System.identityHashCode(service)));
9435                    out.print(' ');
9436                    service.printComponentShortName(out);
9437            if (count > 1) {
9438                out.print(" ("); out.print(count); out.print(" filters)");
9439            }
9440            out.println();
9441        }
9442
9443//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9444//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9445//            final List<ResolveInfo> retList = Lists.newArrayList();
9446//            while (i.hasNext()) {
9447//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9448//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9449//                    retList.add(resolveInfo);
9450//                }
9451//            }
9452//            return retList;
9453//        }
9454
9455        // Keys are String (activity class name), values are Activity.
9456        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9457                = new ArrayMap<ComponentName, PackageParser.Service>();
9458        private int mFlags;
9459    };
9460
9461    private final class ProviderIntentResolver
9462            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9463        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9464                boolean defaultOnly, int userId) {
9465            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9466            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9467        }
9468
9469        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9470                int userId) {
9471            if (!sUserManager.exists(userId))
9472                return null;
9473            mFlags = flags;
9474            return super.queryIntent(intent, resolvedType,
9475                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9476        }
9477
9478        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9479                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9480            if (!sUserManager.exists(userId))
9481                return null;
9482            if (packageProviders == null) {
9483                return null;
9484            }
9485            mFlags = flags;
9486            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9487            final int N = packageProviders.size();
9488            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9489                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9490
9491            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9492            for (int i = 0; i < N; ++i) {
9493                intentFilters = packageProviders.get(i).intents;
9494                if (intentFilters != null && intentFilters.size() > 0) {
9495                    PackageParser.ProviderIntentInfo[] array =
9496                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9497                    intentFilters.toArray(array);
9498                    listCut.add(array);
9499                }
9500            }
9501            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9502        }
9503
9504        public final void addProvider(PackageParser.Provider p) {
9505            if (mProviders.containsKey(p.getComponentName())) {
9506                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9507                return;
9508            }
9509
9510            mProviders.put(p.getComponentName(), p);
9511            if (DEBUG_SHOW_INFO) {
9512                Log.v(TAG, "  "
9513                        + (p.info.nonLocalizedLabel != null
9514                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9515                Log.v(TAG, "    Class=" + p.info.name);
9516            }
9517            final int NI = p.intents.size();
9518            int j;
9519            for (j = 0; j < NI; j++) {
9520                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9521                if (DEBUG_SHOW_INFO) {
9522                    Log.v(TAG, "    IntentFilter:");
9523                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9524                }
9525                if (!intent.debugCheck()) {
9526                    Log.w(TAG, "==> For Provider " + p.info.name);
9527                }
9528                addFilter(intent);
9529            }
9530        }
9531
9532        public final void removeProvider(PackageParser.Provider p) {
9533            mProviders.remove(p.getComponentName());
9534            if (DEBUG_SHOW_INFO) {
9535                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9536                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9537                Log.v(TAG, "    Class=" + p.info.name);
9538            }
9539            final int NI = p.intents.size();
9540            int j;
9541            for (j = 0; j < NI; j++) {
9542                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9543                if (DEBUG_SHOW_INFO) {
9544                    Log.v(TAG, "    IntentFilter:");
9545                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9546                }
9547                removeFilter(intent);
9548            }
9549        }
9550
9551        @Override
9552        protected boolean allowFilterResult(
9553                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9554            ProviderInfo filterPi = filter.provider.info;
9555            for (int i = dest.size() - 1; i >= 0; i--) {
9556                ProviderInfo destPi = dest.get(i).providerInfo;
9557                if (destPi.name == filterPi.name
9558                        && destPi.packageName == filterPi.packageName) {
9559                    return false;
9560                }
9561            }
9562            return true;
9563        }
9564
9565        @Override
9566        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9567            return new PackageParser.ProviderIntentInfo[size];
9568        }
9569
9570        @Override
9571        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9572            if (!sUserManager.exists(userId))
9573                return true;
9574            PackageParser.Package p = filter.provider.owner;
9575            if (p != null) {
9576                PackageSetting ps = (PackageSetting) p.mExtras;
9577                if (ps != null) {
9578                    // System apps are never considered stopped for purposes of
9579                    // filtering, because there may be no way for the user to
9580                    // actually re-launch them.
9581                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9582                            && ps.getStopped(userId);
9583                }
9584            }
9585            return false;
9586        }
9587
9588        @Override
9589        protected boolean isPackageForFilter(String packageName,
9590                PackageParser.ProviderIntentInfo info) {
9591            return packageName.equals(info.provider.owner.packageName);
9592        }
9593
9594        @Override
9595        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9596                int match, int userId) {
9597            if (!sUserManager.exists(userId))
9598                return null;
9599            final PackageParser.ProviderIntentInfo info = filter;
9600            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9601                return null;
9602            }
9603            final PackageParser.Provider provider = info.provider;
9604            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9605            if (ps == null) {
9606                return null;
9607            }
9608            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9609                    ps.readUserState(userId), userId);
9610            if (pi == null) {
9611                return null;
9612            }
9613            final ResolveInfo res = new ResolveInfo();
9614            res.providerInfo = pi;
9615            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9616                res.filter = filter;
9617            }
9618            res.priority = info.getPriority();
9619            res.preferredOrder = provider.owner.mPreferredOrder;
9620            res.match = match;
9621            res.isDefault = info.hasDefault;
9622            res.labelRes = info.labelRes;
9623            res.nonLocalizedLabel = info.nonLocalizedLabel;
9624            res.icon = info.icon;
9625            res.system = res.providerInfo.applicationInfo.isSystemApp();
9626            return res;
9627        }
9628
9629        @Override
9630        protected void sortResults(List<ResolveInfo> results) {
9631            Collections.sort(results, mResolvePrioritySorter);
9632        }
9633
9634        @Override
9635        protected void dumpFilter(PrintWriter out, String prefix,
9636                PackageParser.ProviderIntentInfo filter) {
9637            out.print(prefix);
9638            out.print(
9639                    Integer.toHexString(System.identityHashCode(filter.provider)));
9640            out.print(' ');
9641            filter.provider.printComponentShortName(out);
9642            out.print(" filter ");
9643            out.println(Integer.toHexString(System.identityHashCode(filter)));
9644        }
9645
9646        @Override
9647        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9648            return filter.provider;
9649        }
9650
9651        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9652            PackageParser.Provider provider = (PackageParser.Provider)label;
9653            out.print(prefix); out.print(
9654                    Integer.toHexString(System.identityHashCode(provider)));
9655                    out.print(' ');
9656                    provider.printComponentShortName(out);
9657            if (count > 1) {
9658                out.print(" ("); out.print(count); out.print(" filters)");
9659            }
9660            out.println();
9661        }
9662
9663        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9664                = new ArrayMap<ComponentName, PackageParser.Provider>();
9665        private int mFlags;
9666    }
9667
9668    private static final class EphemeralIntentResolver
9669            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9670        @Override
9671        protected EphemeralResolveIntentInfo[] newArray(int size) {
9672            return new EphemeralResolveIntentInfo[size];
9673        }
9674
9675        @Override
9676        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9677            return true;
9678        }
9679
9680        @Override
9681        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9682                int userId) {
9683            if (!sUserManager.exists(userId)) {
9684                return null;
9685            }
9686            return info.getEphemeralResolveInfo();
9687        }
9688    }
9689
9690    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9691            new Comparator<ResolveInfo>() {
9692        public int compare(ResolveInfo r1, ResolveInfo r2) {
9693            int v1 = r1.priority;
9694            int v2 = r2.priority;
9695            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9696            if (v1 != v2) {
9697                return (v1 > v2) ? -1 : 1;
9698            }
9699            v1 = r1.preferredOrder;
9700            v2 = r2.preferredOrder;
9701            if (v1 != v2) {
9702                return (v1 > v2) ? -1 : 1;
9703            }
9704            if (r1.isDefault != r2.isDefault) {
9705                return r1.isDefault ? -1 : 1;
9706            }
9707            v1 = r1.match;
9708            v2 = r2.match;
9709            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9710            if (v1 != v2) {
9711                return (v1 > v2) ? -1 : 1;
9712            }
9713            if (r1.system != r2.system) {
9714                return r1.system ? -1 : 1;
9715            }
9716            if (r1.activityInfo != null) {
9717                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9718            }
9719            if (r1.serviceInfo != null) {
9720                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9721            }
9722            if (r1.providerInfo != null) {
9723                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9724            }
9725            return 0;
9726        }
9727    };
9728
9729    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9730            new Comparator<ProviderInfo>() {
9731        public int compare(ProviderInfo p1, ProviderInfo p2) {
9732            final int v1 = p1.initOrder;
9733            final int v2 = p2.initOrder;
9734            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9735        }
9736    };
9737
9738    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9739            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9740            final int[] userIds) {
9741        mHandler.post(new Runnable() {
9742            @Override
9743            public void run() {
9744                try {
9745                    final IActivityManager am = ActivityManagerNative.getDefault();
9746                    if (am == null) return;
9747                    final int[] resolvedUserIds;
9748                    if (userIds == null) {
9749                        resolvedUserIds = am.getRunningUserIds();
9750                    } else {
9751                        resolvedUserIds = userIds;
9752                    }
9753                    for (int id : resolvedUserIds) {
9754                        final Intent intent = new Intent(action,
9755                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9756                        if (extras != null) {
9757                            intent.putExtras(extras);
9758                        }
9759                        if (targetPkg != null) {
9760                            intent.setPackage(targetPkg);
9761                        }
9762                        // Modify the UID when posting to other users
9763                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9764                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9765                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9766                            intent.putExtra(Intent.EXTRA_UID, uid);
9767                        }
9768                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9769                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9770                        if (DEBUG_BROADCASTS) {
9771                            RuntimeException here = new RuntimeException("here");
9772                            here.fillInStackTrace();
9773                            Slog.d(TAG, "Sending to user " + id + ": "
9774                                    + intent.toShortString(false, true, false, false)
9775                                    + " " + intent.getExtras(), here);
9776                        }
9777                        am.broadcastIntent(null, intent, null, finishedReceiver,
9778                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9779                                null, finishedReceiver != null, false, id);
9780                    }
9781                } catch (RemoteException ex) {
9782                }
9783            }
9784        });
9785    }
9786
9787    /**
9788     * Check if the external storage media is available. This is true if there
9789     * is a mounted external storage medium or if the external storage is
9790     * emulated.
9791     */
9792    private boolean isExternalMediaAvailable() {
9793        return mMediaMounted || Environment.isExternalStorageEmulated();
9794    }
9795
9796    @Override
9797    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9798        // writer
9799        synchronized (mPackages) {
9800            if (!isExternalMediaAvailable()) {
9801                // If the external storage is no longer mounted at this point,
9802                // the caller may not have been able to delete all of this
9803                // packages files and can not delete any more.  Bail.
9804                return null;
9805            }
9806            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9807            if (lastPackage != null) {
9808                pkgs.remove(lastPackage);
9809            }
9810            if (pkgs.size() > 0) {
9811                return pkgs.get(0);
9812            }
9813        }
9814        return null;
9815    }
9816
9817    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9818        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9819                userId, andCode ? 1 : 0, packageName);
9820        if (mSystemReady) {
9821            msg.sendToTarget();
9822        } else {
9823            if (mPostSystemReadyMessages == null) {
9824                mPostSystemReadyMessages = new ArrayList<>();
9825            }
9826            mPostSystemReadyMessages.add(msg);
9827        }
9828    }
9829
9830    void startCleaningPackages() {
9831        // reader
9832        synchronized (mPackages) {
9833            if (!isExternalMediaAvailable()) {
9834                return;
9835            }
9836            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9837                return;
9838            }
9839        }
9840        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9841        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9842        IActivityManager am = ActivityManagerNative.getDefault();
9843        if (am != null) {
9844            try {
9845                am.startService(null, intent, null, mContext.getOpPackageName(),
9846                        UserHandle.USER_SYSTEM);
9847            } catch (RemoteException e) {
9848            }
9849        }
9850    }
9851
9852    @Override
9853    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9854            int installFlags, String installerPackageName, VerificationParams verificationParams,
9855            String packageAbiOverride) {
9856        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9857                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9858    }
9859
9860    @Override
9861    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9862            int installFlags, String installerPackageName, VerificationParams verificationParams,
9863            String packageAbiOverride, int userId) {
9864        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9865
9866        final int callingUid = Binder.getCallingUid();
9867        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9868
9869        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9870            try {
9871                if (observer != null) {
9872                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9873                }
9874            } catch (RemoteException re) {
9875            }
9876            return;
9877        }
9878
9879        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9880            installFlags |= PackageManager.INSTALL_FROM_ADB;
9881
9882        } else {
9883            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9884            // about installerPackageName.
9885
9886            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9887            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9888        }
9889
9890        UserHandle user;
9891        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9892            user = UserHandle.ALL;
9893        } else {
9894            user = new UserHandle(userId);
9895        }
9896
9897        // Only system components can circumvent runtime permissions when installing.
9898        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9899                && mContext.checkCallingOrSelfPermission(Manifest.permission
9900                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9901            throw new SecurityException("You need the "
9902                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9903                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9904        }
9905
9906        verificationParams.setInstallerUid(callingUid);
9907
9908        final File originFile = new File(originPath);
9909        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9910
9911        final Message msg = mHandler.obtainMessage(INIT_COPY);
9912        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9913                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9914        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9915        msg.obj = params;
9916
9917        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9918                System.identityHashCode(msg.obj));
9919        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9920                System.identityHashCode(msg.obj));
9921
9922        mHandler.sendMessage(msg);
9923    }
9924
9925    void installStage(String packageName, File stagedDir, String stagedCid,
9926            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9927            String installerPackageName, int installerUid, UserHandle user) {
9928        if (DEBUG_EPHEMERAL) {
9929            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
9930                Slog.d(TAG, "Ephemeral install of " + packageName);
9931            }
9932        }
9933        final VerificationParams verifParams = new VerificationParams(
9934                null, sessionParams.originatingUri, sessionParams.referrerUri,
9935                sessionParams.originatingUid);
9936        verifParams.setInstallerUid(installerUid);
9937
9938        final OriginInfo origin;
9939        if (stagedDir != null) {
9940            origin = OriginInfo.fromStagedFile(stagedDir);
9941        } else {
9942            origin = OriginInfo.fromStagedContainer(stagedCid);
9943        }
9944
9945        final Message msg = mHandler.obtainMessage(INIT_COPY);
9946        final InstallParams params = new InstallParams(origin, null, observer,
9947                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9948                verifParams, user, sessionParams.abiOverride,
9949                sessionParams.grantedRuntimePermissions);
9950        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9951        msg.obj = params;
9952
9953        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9954                System.identityHashCode(msg.obj));
9955        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9956                System.identityHashCode(msg.obj));
9957
9958        mHandler.sendMessage(msg);
9959    }
9960
9961    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9962        Bundle extras = new Bundle(1);
9963        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9964
9965        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9966                packageName, extras, 0, null, null, new int[] {userId});
9967        try {
9968            IActivityManager am = ActivityManagerNative.getDefault();
9969            final boolean isSystem =
9970                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9971            if (isSystem && am.isUserRunning(userId, 0)) {
9972                // The just-installed/enabled app is bundled on the system, so presumed
9973                // to be able to run automatically without needing an explicit launch.
9974                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9975                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9976                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9977                        .setPackage(packageName);
9978                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9979                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9980            }
9981        } catch (RemoteException e) {
9982            // shouldn't happen
9983            Slog.w(TAG, "Unable to bootstrap installed package", e);
9984        }
9985    }
9986
9987    @Override
9988    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9989            int userId) {
9990        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9991        PackageSetting pkgSetting;
9992        final int uid = Binder.getCallingUid();
9993        enforceCrossUserPermission(uid, userId, true, true,
9994                "setApplicationHiddenSetting for user " + userId);
9995
9996        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9997            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9998            return false;
9999        }
10000
10001        long callingId = Binder.clearCallingIdentity();
10002        try {
10003            boolean sendAdded = false;
10004            boolean sendRemoved = false;
10005            // writer
10006            synchronized (mPackages) {
10007                pkgSetting = mSettings.mPackages.get(packageName);
10008                if (pkgSetting == null) {
10009                    return false;
10010                }
10011                if (pkgSetting.getHidden(userId) != hidden) {
10012                    pkgSetting.setHidden(hidden, userId);
10013                    mSettings.writePackageRestrictionsLPr(userId);
10014                    if (hidden) {
10015                        sendRemoved = true;
10016                    } else {
10017                        sendAdded = true;
10018                    }
10019                }
10020            }
10021            if (sendAdded) {
10022                sendPackageAddedForUser(packageName, pkgSetting, userId);
10023                return true;
10024            }
10025            if (sendRemoved) {
10026                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10027                        "hiding pkg");
10028                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10029                return true;
10030            }
10031        } finally {
10032            Binder.restoreCallingIdentity(callingId);
10033        }
10034        return false;
10035    }
10036
10037    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10038            int userId) {
10039        final PackageRemovedInfo info = new PackageRemovedInfo();
10040        info.removedPackage = packageName;
10041        info.removedUsers = new int[] {userId};
10042        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10043        info.sendBroadcast(false, false, false);
10044    }
10045
10046    /**
10047     * Returns true if application is not found or there was an error. Otherwise it returns
10048     * the hidden state of the package for the given user.
10049     */
10050    @Override
10051    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10052        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10053        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10054                false, "getApplicationHidden for user " + userId);
10055        PackageSetting pkgSetting;
10056        long callingId = Binder.clearCallingIdentity();
10057        try {
10058            // writer
10059            synchronized (mPackages) {
10060                pkgSetting = mSettings.mPackages.get(packageName);
10061                if (pkgSetting == null) {
10062                    return true;
10063                }
10064                return pkgSetting.getHidden(userId);
10065            }
10066        } finally {
10067            Binder.restoreCallingIdentity(callingId);
10068        }
10069    }
10070
10071    /**
10072     * @hide
10073     */
10074    @Override
10075    public int installExistingPackageAsUser(String packageName, int userId) {
10076        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10077                null);
10078        PackageSetting pkgSetting;
10079        final int uid = Binder.getCallingUid();
10080        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10081                + userId);
10082        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10083            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10084        }
10085
10086        long callingId = Binder.clearCallingIdentity();
10087        try {
10088            boolean installed = false;
10089
10090            // writer
10091            synchronized (mPackages) {
10092                pkgSetting = mSettings.mPackages.get(packageName);
10093                if (pkgSetting == null) {
10094                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10095                }
10096                if (!pkgSetting.getInstalled(userId)) {
10097                    pkgSetting.setInstalled(true, userId);
10098                    pkgSetting.setHidden(false, userId);
10099                    mSettings.writePackageRestrictionsLPr(userId);
10100                    if (pkgSetting.pkg != null) {
10101                        prepareAppDataAfterInstall(pkgSetting.pkg);
10102                    }
10103                    installed = true;
10104                }
10105            }
10106
10107            if (installed) {
10108                sendPackageAddedForUser(packageName, pkgSetting, userId);
10109            }
10110        } finally {
10111            Binder.restoreCallingIdentity(callingId);
10112        }
10113
10114        return PackageManager.INSTALL_SUCCEEDED;
10115    }
10116
10117    boolean isUserRestricted(int userId, String restrictionKey) {
10118        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10119        if (restrictions.getBoolean(restrictionKey, false)) {
10120            Log.w(TAG, "User is restricted: " + restrictionKey);
10121            return true;
10122        }
10123        return false;
10124    }
10125
10126    @Override
10127    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10128        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10129        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10130                "setPackageSuspended for user " + userId);
10131
10132        long callingId = Binder.clearCallingIdentity();
10133        try {
10134            synchronized (mPackages) {
10135                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10136                if (pkgSetting != null) {
10137                    if (pkgSetting.getSuspended(userId) != suspended) {
10138                        pkgSetting.setSuspended(suspended, userId);
10139                        mSettings.writePackageRestrictionsLPr(userId);
10140                    }
10141
10142                    // TODO:
10143                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10144                    // * remove app from recents (kill app it if it is running)
10145                    // * erase existing notifications for this app
10146                    return true;
10147                }
10148
10149                return false;
10150            }
10151        } finally {
10152            Binder.restoreCallingIdentity(callingId);
10153        }
10154    }
10155
10156    @Override
10157    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10158        mContext.enforceCallingOrSelfPermission(
10159                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10160                "Only package verification agents can verify applications");
10161
10162        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10163        final PackageVerificationResponse response = new PackageVerificationResponse(
10164                verificationCode, Binder.getCallingUid());
10165        msg.arg1 = id;
10166        msg.obj = response;
10167        mHandler.sendMessage(msg);
10168    }
10169
10170    @Override
10171    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10172            long millisecondsToDelay) {
10173        mContext.enforceCallingOrSelfPermission(
10174                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10175                "Only package verification agents can extend verification timeouts");
10176
10177        final PackageVerificationState state = mPendingVerification.get(id);
10178        final PackageVerificationResponse response = new PackageVerificationResponse(
10179                verificationCodeAtTimeout, Binder.getCallingUid());
10180
10181        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10182            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10183        }
10184        if (millisecondsToDelay < 0) {
10185            millisecondsToDelay = 0;
10186        }
10187        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10188                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10189            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10190        }
10191
10192        if ((state != null) && !state.timeoutExtended()) {
10193            state.extendTimeout();
10194
10195            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10196            msg.arg1 = id;
10197            msg.obj = response;
10198            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10199        }
10200    }
10201
10202    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10203            int verificationCode, UserHandle user) {
10204        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10205        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10206        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10207        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10208        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10209
10210        mContext.sendBroadcastAsUser(intent, user,
10211                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10212    }
10213
10214    private ComponentName matchComponentForVerifier(String packageName,
10215            List<ResolveInfo> receivers) {
10216        ActivityInfo targetReceiver = null;
10217
10218        final int NR = receivers.size();
10219        for (int i = 0; i < NR; i++) {
10220            final ResolveInfo info = receivers.get(i);
10221            if (info.activityInfo == null) {
10222                continue;
10223            }
10224
10225            if (packageName.equals(info.activityInfo.packageName)) {
10226                targetReceiver = info.activityInfo;
10227                break;
10228            }
10229        }
10230
10231        if (targetReceiver == null) {
10232            return null;
10233        }
10234
10235        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10236    }
10237
10238    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10239            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10240        if (pkgInfo.verifiers.length == 0) {
10241            return null;
10242        }
10243
10244        final int N = pkgInfo.verifiers.length;
10245        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10246        for (int i = 0; i < N; i++) {
10247            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10248
10249            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10250                    receivers);
10251            if (comp == null) {
10252                continue;
10253            }
10254
10255            final int verifierUid = getUidForVerifier(verifierInfo);
10256            if (verifierUid == -1) {
10257                continue;
10258            }
10259
10260            if (DEBUG_VERIFY) {
10261                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10262                        + " with the correct signature");
10263            }
10264            sufficientVerifiers.add(comp);
10265            verificationState.addSufficientVerifier(verifierUid);
10266        }
10267
10268        return sufficientVerifiers;
10269    }
10270
10271    private int getUidForVerifier(VerifierInfo verifierInfo) {
10272        synchronized (mPackages) {
10273            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10274            if (pkg == null) {
10275                return -1;
10276            } else if (pkg.mSignatures.length != 1) {
10277                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10278                        + " has more than one signature; ignoring");
10279                return -1;
10280            }
10281
10282            /*
10283             * If the public key of the package's signature does not match
10284             * our expected public key, then this is a different package and
10285             * we should skip.
10286             */
10287
10288            final byte[] expectedPublicKey;
10289            try {
10290                final Signature verifierSig = pkg.mSignatures[0];
10291                final PublicKey publicKey = verifierSig.getPublicKey();
10292                expectedPublicKey = publicKey.getEncoded();
10293            } catch (CertificateException e) {
10294                return -1;
10295            }
10296
10297            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10298
10299            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10300                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10301                        + " does not have the expected public key; ignoring");
10302                return -1;
10303            }
10304
10305            return pkg.applicationInfo.uid;
10306        }
10307    }
10308
10309    @Override
10310    public void finishPackageInstall(int token) {
10311        enforceSystemOrRoot("Only the system is allowed to finish installs");
10312
10313        if (DEBUG_INSTALL) {
10314            Slog.v(TAG, "BM finishing package install for " + token);
10315        }
10316        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10317
10318        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10319        mHandler.sendMessage(msg);
10320    }
10321
10322    /**
10323     * Get the verification agent timeout.
10324     *
10325     * @return verification timeout in milliseconds
10326     */
10327    private long getVerificationTimeout() {
10328        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10329                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10330                DEFAULT_VERIFICATION_TIMEOUT);
10331    }
10332
10333    /**
10334     * Get the default verification agent response code.
10335     *
10336     * @return default verification response code
10337     */
10338    private int getDefaultVerificationResponse() {
10339        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10340                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10341                DEFAULT_VERIFICATION_RESPONSE);
10342    }
10343
10344    /**
10345     * Check whether or not package verification has been enabled.
10346     *
10347     * @return true if verification should be performed
10348     */
10349    private boolean isVerificationEnabled(int userId, int installFlags) {
10350        if (!DEFAULT_VERIFY_ENABLE) {
10351            return false;
10352        }
10353        // Ephemeral apps don't get the full verification treatment
10354        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10355            if (DEBUG_EPHEMERAL) {
10356                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10357            }
10358            return false;
10359        }
10360
10361        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10362
10363        // Check if installing from ADB
10364        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10365            // Do not run verification in a test harness environment
10366            if (ActivityManager.isRunningInTestHarness()) {
10367                return false;
10368            }
10369            if (ensureVerifyAppsEnabled) {
10370                return true;
10371            }
10372            // Check if the developer does not want package verification for ADB installs
10373            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10374                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10375                return false;
10376            }
10377        }
10378
10379        if (ensureVerifyAppsEnabled) {
10380            return true;
10381        }
10382
10383        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10384                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10385    }
10386
10387    @Override
10388    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10389            throws RemoteException {
10390        mContext.enforceCallingOrSelfPermission(
10391                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10392                "Only intentfilter verification agents can verify applications");
10393
10394        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10395        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10396                Binder.getCallingUid(), verificationCode, failedDomains);
10397        msg.arg1 = id;
10398        msg.obj = response;
10399        mHandler.sendMessage(msg);
10400    }
10401
10402    @Override
10403    public int getIntentVerificationStatus(String packageName, int userId) {
10404        synchronized (mPackages) {
10405            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10406        }
10407    }
10408
10409    @Override
10410    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10411        mContext.enforceCallingOrSelfPermission(
10412                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10413
10414        boolean result = false;
10415        synchronized (mPackages) {
10416            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10417        }
10418        if (result) {
10419            scheduleWritePackageRestrictionsLocked(userId);
10420        }
10421        return result;
10422    }
10423
10424    @Override
10425    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10426        synchronized (mPackages) {
10427            return mSettings.getIntentFilterVerificationsLPr(packageName);
10428        }
10429    }
10430
10431    @Override
10432    public List<IntentFilter> getAllIntentFilters(String packageName) {
10433        if (TextUtils.isEmpty(packageName)) {
10434            return Collections.<IntentFilter>emptyList();
10435        }
10436        synchronized (mPackages) {
10437            PackageParser.Package pkg = mPackages.get(packageName);
10438            if (pkg == null || pkg.activities == null) {
10439                return Collections.<IntentFilter>emptyList();
10440            }
10441            final int count = pkg.activities.size();
10442            ArrayList<IntentFilter> result = new ArrayList<>();
10443            for (int n=0; n<count; n++) {
10444                PackageParser.Activity activity = pkg.activities.get(n);
10445                if (activity.intents != null && activity.intents.size() > 0) {
10446                    result.addAll(activity.intents);
10447                }
10448            }
10449            return result;
10450        }
10451    }
10452
10453    @Override
10454    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10455        mContext.enforceCallingOrSelfPermission(
10456                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10457
10458        synchronized (mPackages) {
10459            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10460            if (packageName != null) {
10461                result |= updateIntentVerificationStatus(packageName,
10462                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10463                        userId);
10464                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10465                        packageName, userId);
10466            }
10467            return result;
10468        }
10469    }
10470
10471    @Override
10472    public String getDefaultBrowserPackageName(int userId) {
10473        synchronized (mPackages) {
10474            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10475        }
10476    }
10477
10478    /**
10479     * Get the "allow unknown sources" setting.
10480     *
10481     * @return the current "allow unknown sources" setting
10482     */
10483    private int getUnknownSourcesSettings() {
10484        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10485                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10486                -1);
10487    }
10488
10489    @Override
10490    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10491        final int uid = Binder.getCallingUid();
10492        // writer
10493        synchronized (mPackages) {
10494            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10495            if (targetPackageSetting == null) {
10496                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10497            }
10498
10499            PackageSetting installerPackageSetting;
10500            if (installerPackageName != null) {
10501                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10502                if (installerPackageSetting == null) {
10503                    throw new IllegalArgumentException("Unknown installer package: "
10504                            + installerPackageName);
10505                }
10506            } else {
10507                installerPackageSetting = null;
10508            }
10509
10510            Signature[] callerSignature;
10511            Object obj = mSettings.getUserIdLPr(uid);
10512            if (obj != null) {
10513                if (obj instanceof SharedUserSetting) {
10514                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10515                } else if (obj instanceof PackageSetting) {
10516                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10517                } else {
10518                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10519                }
10520            } else {
10521                throw new SecurityException("Unknown calling UID: " + uid);
10522            }
10523
10524            // Verify: can't set installerPackageName to a package that is
10525            // not signed with the same cert as the caller.
10526            if (installerPackageSetting != null) {
10527                if (compareSignatures(callerSignature,
10528                        installerPackageSetting.signatures.mSignatures)
10529                        != PackageManager.SIGNATURE_MATCH) {
10530                    throw new SecurityException(
10531                            "Caller does not have same cert as new installer package "
10532                            + installerPackageName);
10533                }
10534            }
10535
10536            // Verify: if target already has an installer package, it must
10537            // be signed with the same cert as the caller.
10538            if (targetPackageSetting.installerPackageName != null) {
10539                PackageSetting setting = mSettings.mPackages.get(
10540                        targetPackageSetting.installerPackageName);
10541                // If the currently set package isn't valid, then it's always
10542                // okay to change it.
10543                if (setting != null) {
10544                    if (compareSignatures(callerSignature,
10545                            setting.signatures.mSignatures)
10546                            != PackageManager.SIGNATURE_MATCH) {
10547                        throw new SecurityException(
10548                                "Caller does not have same cert as old installer package "
10549                                + targetPackageSetting.installerPackageName);
10550                    }
10551                }
10552            }
10553
10554            // Okay!
10555            targetPackageSetting.installerPackageName = installerPackageName;
10556            scheduleWriteSettingsLocked();
10557        }
10558    }
10559
10560    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10561        // Queue up an async operation since the package installation may take a little while.
10562        mHandler.post(new Runnable() {
10563            public void run() {
10564                mHandler.removeCallbacks(this);
10565                 // Result object to be returned
10566                PackageInstalledInfo res = new PackageInstalledInfo();
10567                res.returnCode = currentStatus;
10568                res.uid = -1;
10569                res.pkg = null;
10570                res.removedInfo = new PackageRemovedInfo();
10571                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10572                    args.doPreInstall(res.returnCode);
10573                    synchronized (mInstallLock) {
10574                        installPackageTracedLI(args, res);
10575                    }
10576                    args.doPostInstall(res.returnCode, res.uid);
10577                }
10578
10579                // A restore should be performed at this point if (a) the install
10580                // succeeded, (b) the operation is not an update, and (c) the new
10581                // package has not opted out of backup participation.
10582                final boolean update = res.removedInfo.removedPackage != null;
10583                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10584                boolean doRestore = !update
10585                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10586
10587                // Set up the post-install work request bookkeeping.  This will be used
10588                // and cleaned up by the post-install event handling regardless of whether
10589                // there's a restore pass performed.  Token values are >= 1.
10590                int token;
10591                if (mNextInstallToken < 0) mNextInstallToken = 1;
10592                token = mNextInstallToken++;
10593
10594                PostInstallData data = new PostInstallData(args, res);
10595                mRunningInstalls.put(token, data);
10596                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10597
10598                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10599                    // Pass responsibility to the Backup Manager.  It will perform a
10600                    // restore if appropriate, then pass responsibility back to the
10601                    // Package Manager to run the post-install observer callbacks
10602                    // and broadcasts.
10603                    IBackupManager bm = IBackupManager.Stub.asInterface(
10604                            ServiceManager.getService(Context.BACKUP_SERVICE));
10605                    if (bm != null) {
10606                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10607                                + " to BM for possible restore");
10608                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10609                        try {
10610                            // TODO: http://b/22388012
10611                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10612                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10613                            } else {
10614                                doRestore = false;
10615                            }
10616                        } catch (RemoteException e) {
10617                            // can't happen; the backup manager is local
10618                        } catch (Exception e) {
10619                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10620                            doRestore = false;
10621                        }
10622                    } else {
10623                        Slog.e(TAG, "Backup Manager not found!");
10624                        doRestore = false;
10625                    }
10626                }
10627
10628                if (!doRestore) {
10629                    // No restore possible, or the Backup Manager was mysteriously not
10630                    // available -- just fire the post-install work request directly.
10631                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10632
10633                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10634
10635                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10636                    mHandler.sendMessage(msg);
10637                }
10638            }
10639        });
10640    }
10641
10642    private abstract class HandlerParams {
10643        private static final int MAX_RETRIES = 4;
10644
10645        /**
10646         * Number of times startCopy() has been attempted and had a non-fatal
10647         * error.
10648         */
10649        private int mRetries = 0;
10650
10651        /** User handle for the user requesting the information or installation. */
10652        private final UserHandle mUser;
10653        String traceMethod;
10654        int traceCookie;
10655
10656        HandlerParams(UserHandle user) {
10657            mUser = user;
10658        }
10659
10660        UserHandle getUser() {
10661            return mUser;
10662        }
10663
10664        HandlerParams setTraceMethod(String traceMethod) {
10665            this.traceMethod = traceMethod;
10666            return this;
10667        }
10668
10669        HandlerParams setTraceCookie(int traceCookie) {
10670            this.traceCookie = traceCookie;
10671            return this;
10672        }
10673
10674        final boolean startCopy() {
10675            boolean res;
10676            try {
10677                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10678
10679                if (++mRetries > MAX_RETRIES) {
10680                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10681                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10682                    handleServiceError();
10683                    return false;
10684                } else {
10685                    handleStartCopy();
10686                    res = true;
10687                }
10688            } catch (RemoteException e) {
10689                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10690                mHandler.sendEmptyMessage(MCS_RECONNECT);
10691                res = false;
10692            }
10693            handleReturnCode();
10694            return res;
10695        }
10696
10697        final void serviceError() {
10698            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10699            handleServiceError();
10700            handleReturnCode();
10701        }
10702
10703        abstract void handleStartCopy() throws RemoteException;
10704        abstract void handleServiceError();
10705        abstract void handleReturnCode();
10706    }
10707
10708    class MeasureParams extends HandlerParams {
10709        private final PackageStats mStats;
10710        private boolean mSuccess;
10711
10712        private final IPackageStatsObserver mObserver;
10713
10714        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10715            super(new UserHandle(stats.userHandle));
10716            mObserver = observer;
10717            mStats = stats;
10718        }
10719
10720        @Override
10721        public String toString() {
10722            return "MeasureParams{"
10723                + Integer.toHexString(System.identityHashCode(this))
10724                + " " + mStats.packageName + "}";
10725        }
10726
10727        @Override
10728        void handleStartCopy() throws RemoteException {
10729            synchronized (mInstallLock) {
10730                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10731            }
10732
10733            if (mSuccess) {
10734                final boolean mounted;
10735                if (Environment.isExternalStorageEmulated()) {
10736                    mounted = true;
10737                } else {
10738                    final String status = Environment.getExternalStorageState();
10739                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10740                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10741                }
10742
10743                if (mounted) {
10744                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10745
10746                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10747                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10748
10749                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10750                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10751
10752                    // Always subtract cache size, since it's a subdirectory
10753                    mStats.externalDataSize -= mStats.externalCacheSize;
10754
10755                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10756                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10757
10758                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10759                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10760                }
10761            }
10762        }
10763
10764        @Override
10765        void handleReturnCode() {
10766            if (mObserver != null) {
10767                try {
10768                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10769                } catch (RemoteException e) {
10770                    Slog.i(TAG, "Observer no longer exists.");
10771                }
10772            }
10773        }
10774
10775        @Override
10776        void handleServiceError() {
10777            Slog.e(TAG, "Could not measure application " + mStats.packageName
10778                            + " external storage");
10779        }
10780    }
10781
10782    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10783            throws RemoteException {
10784        long result = 0;
10785        for (File path : paths) {
10786            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10787        }
10788        return result;
10789    }
10790
10791    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10792        for (File path : paths) {
10793            try {
10794                mcs.clearDirectory(path.getAbsolutePath());
10795            } catch (RemoteException e) {
10796            }
10797        }
10798    }
10799
10800    static class OriginInfo {
10801        /**
10802         * Location where install is coming from, before it has been
10803         * copied/renamed into place. This could be a single monolithic APK
10804         * file, or a cluster directory. This location may be untrusted.
10805         */
10806        final File file;
10807        final String cid;
10808
10809        /**
10810         * Flag indicating that {@link #file} or {@link #cid} has already been
10811         * staged, meaning downstream users don't need to defensively copy the
10812         * contents.
10813         */
10814        final boolean staged;
10815
10816        /**
10817         * Flag indicating that {@link #file} or {@link #cid} is an already
10818         * installed app that is being moved.
10819         */
10820        final boolean existing;
10821
10822        final String resolvedPath;
10823        final File resolvedFile;
10824
10825        static OriginInfo fromNothing() {
10826            return new OriginInfo(null, null, false, false);
10827        }
10828
10829        static OriginInfo fromUntrustedFile(File file) {
10830            return new OriginInfo(file, null, false, false);
10831        }
10832
10833        static OriginInfo fromExistingFile(File file) {
10834            return new OriginInfo(file, null, false, true);
10835        }
10836
10837        static OriginInfo fromStagedFile(File file) {
10838            return new OriginInfo(file, null, true, false);
10839        }
10840
10841        static OriginInfo fromStagedContainer(String cid) {
10842            return new OriginInfo(null, cid, true, false);
10843        }
10844
10845        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10846            this.file = file;
10847            this.cid = cid;
10848            this.staged = staged;
10849            this.existing = existing;
10850
10851            if (cid != null) {
10852                resolvedPath = PackageHelper.getSdDir(cid);
10853                resolvedFile = new File(resolvedPath);
10854            } else if (file != null) {
10855                resolvedPath = file.getAbsolutePath();
10856                resolvedFile = file;
10857            } else {
10858                resolvedPath = null;
10859                resolvedFile = null;
10860            }
10861        }
10862    }
10863
10864    static class MoveInfo {
10865        final int moveId;
10866        final String fromUuid;
10867        final String toUuid;
10868        final String packageName;
10869        final String dataAppName;
10870        final int appId;
10871        final String seinfo;
10872
10873        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10874                String dataAppName, int appId, String seinfo) {
10875            this.moveId = moveId;
10876            this.fromUuid = fromUuid;
10877            this.toUuid = toUuid;
10878            this.packageName = packageName;
10879            this.dataAppName = dataAppName;
10880            this.appId = appId;
10881            this.seinfo = seinfo;
10882        }
10883    }
10884
10885    class InstallParams extends HandlerParams {
10886        final OriginInfo origin;
10887        final MoveInfo move;
10888        final IPackageInstallObserver2 observer;
10889        int installFlags;
10890        final String installerPackageName;
10891        final String volumeUuid;
10892        final VerificationParams verificationParams;
10893        private InstallArgs mArgs;
10894        private int mRet;
10895        final String packageAbiOverride;
10896        final String[] grantedRuntimePermissions;
10897
10898        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10899                int installFlags, String installerPackageName, String volumeUuid,
10900                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10901                String[] grantedPermissions) {
10902            super(user);
10903            this.origin = origin;
10904            this.move = move;
10905            this.observer = observer;
10906            this.installFlags = installFlags;
10907            this.installerPackageName = installerPackageName;
10908            this.volumeUuid = volumeUuid;
10909            this.verificationParams = verificationParams;
10910            this.packageAbiOverride = packageAbiOverride;
10911            this.grantedRuntimePermissions = grantedPermissions;
10912        }
10913
10914        @Override
10915        public String toString() {
10916            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10917                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10918        }
10919
10920        private int installLocationPolicy(PackageInfoLite pkgLite) {
10921            String packageName = pkgLite.packageName;
10922            int installLocation = pkgLite.installLocation;
10923            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10924            // reader
10925            synchronized (mPackages) {
10926                PackageParser.Package pkg = mPackages.get(packageName);
10927                if (pkg != null) {
10928                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10929                        // Check for downgrading.
10930                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10931                            try {
10932                                checkDowngrade(pkg, pkgLite);
10933                            } catch (PackageManagerException e) {
10934                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10935                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10936                            }
10937                        }
10938                        // Check for updated system application.
10939                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10940                            if (onSd) {
10941                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10942                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10943                            }
10944                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10945                        } else {
10946                            if (onSd) {
10947                                // Install flag overrides everything.
10948                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10949                            }
10950                            // If current upgrade specifies particular preference
10951                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10952                                // Application explicitly specified internal.
10953                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10954                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10955                                // App explictly prefers external. Let policy decide
10956                            } else {
10957                                // Prefer previous location
10958                                if (isExternal(pkg)) {
10959                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10960                                }
10961                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10962                            }
10963                        }
10964                    } else {
10965                        // Invalid install. Return error code
10966                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10967                    }
10968                }
10969            }
10970            // All the special cases have been taken care of.
10971            // Return result based on recommended install location.
10972            if (onSd) {
10973                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10974            }
10975            return pkgLite.recommendedInstallLocation;
10976        }
10977
10978        /*
10979         * Invoke remote method to get package information and install
10980         * location values. Override install location based on default
10981         * policy if needed and then create install arguments based
10982         * on the install location.
10983         */
10984        public void handleStartCopy() throws RemoteException {
10985            int ret = PackageManager.INSTALL_SUCCEEDED;
10986
10987            // If we're already staged, we've firmly committed to an install location
10988            if (origin.staged) {
10989                if (origin.file != null) {
10990                    installFlags |= PackageManager.INSTALL_INTERNAL;
10991                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10992                } else if (origin.cid != null) {
10993                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10994                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10995                } else {
10996                    throw new IllegalStateException("Invalid stage location");
10997                }
10998            }
10999
11000            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11001            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11002            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11003            PackageInfoLite pkgLite = null;
11004
11005            if (onInt && onSd) {
11006                // Check if both bits are set.
11007                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11008                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11009            } else if (onSd && ephemeral) {
11010                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11011                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11012            } else {
11013                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11014                        packageAbiOverride);
11015
11016                if (DEBUG_EPHEMERAL && ephemeral) {
11017                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11018                }
11019
11020                /*
11021                 * If we have too little free space, try to free cache
11022                 * before giving up.
11023                 */
11024                if (!origin.staged && pkgLite.recommendedInstallLocation
11025                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11026                    // TODO: focus freeing disk space on the target device
11027                    final StorageManager storage = StorageManager.from(mContext);
11028                    final long lowThreshold = storage.getStorageLowBytes(
11029                            Environment.getDataDirectory());
11030
11031                    final long sizeBytes = mContainerService.calculateInstalledSize(
11032                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11033
11034                    try {
11035                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11036                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11037                                installFlags, packageAbiOverride);
11038                    } catch (InstallerException e) {
11039                        Slog.w(TAG, "Failed to free cache", e);
11040                    }
11041
11042                    /*
11043                     * The cache free must have deleted the file we
11044                     * downloaded to install.
11045                     *
11046                     * TODO: fix the "freeCache" call to not delete
11047                     *       the file we care about.
11048                     */
11049                    if (pkgLite.recommendedInstallLocation
11050                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11051                        pkgLite.recommendedInstallLocation
11052                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11053                    }
11054                }
11055            }
11056
11057            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11058                int loc = pkgLite.recommendedInstallLocation;
11059                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11060                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11061                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11062                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11063                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11064                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11065                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11066                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11067                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11068                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11069                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11070                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11071                } else {
11072                    // Override with defaults if needed.
11073                    loc = installLocationPolicy(pkgLite);
11074                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11075                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11076                    } else if (!onSd && !onInt) {
11077                        // Override install location with flags
11078                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11079                            // Set the flag to install on external media.
11080                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11081                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11082                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11083                            if (DEBUG_EPHEMERAL) {
11084                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11085                            }
11086                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11087                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11088                                    |PackageManager.INSTALL_INTERNAL);
11089                        } else {
11090                            // Make sure the flag for installing on external
11091                            // media is unset
11092                            installFlags |= PackageManager.INSTALL_INTERNAL;
11093                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11094                        }
11095                    }
11096                }
11097            }
11098
11099            final InstallArgs args = createInstallArgs(this);
11100            mArgs = args;
11101
11102            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11103                // TODO: http://b/22976637
11104                // Apps installed for "all" users use the device owner to verify the app
11105                UserHandle verifierUser = getUser();
11106                if (verifierUser == UserHandle.ALL) {
11107                    verifierUser = UserHandle.SYSTEM;
11108                }
11109
11110                /*
11111                 * Determine if we have any installed package verifiers. If we
11112                 * do, then we'll defer to them to verify the packages.
11113                 */
11114                final int requiredUid = mRequiredVerifierPackage == null ? -1
11115                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11116                                verifierUser.getIdentifier());
11117                if (!origin.existing && requiredUid != -1
11118                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11119                    final Intent verification = new Intent(
11120                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11121                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11122                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11123                            PACKAGE_MIME_TYPE);
11124                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11125
11126                    // Query all live verifiers based on current user state
11127                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11128                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11129
11130                    if (DEBUG_VERIFY) {
11131                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11132                                + verification.toString() + " with " + pkgLite.verifiers.length
11133                                + " optional verifiers");
11134                    }
11135
11136                    final int verificationId = mPendingVerificationToken++;
11137
11138                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11139
11140                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11141                            installerPackageName);
11142
11143                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11144                            installFlags);
11145
11146                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11147                            pkgLite.packageName);
11148
11149                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11150                            pkgLite.versionCode);
11151
11152                    if (verificationParams != null) {
11153                        if (verificationParams.getVerificationURI() != null) {
11154                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11155                                 verificationParams.getVerificationURI());
11156                        }
11157                        if (verificationParams.getOriginatingURI() != null) {
11158                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11159                                  verificationParams.getOriginatingURI());
11160                        }
11161                        if (verificationParams.getReferrer() != null) {
11162                            verification.putExtra(Intent.EXTRA_REFERRER,
11163                                  verificationParams.getReferrer());
11164                        }
11165                        if (verificationParams.getOriginatingUid() >= 0) {
11166                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11167                                  verificationParams.getOriginatingUid());
11168                        }
11169                        if (verificationParams.getInstallerUid() >= 0) {
11170                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11171                                  verificationParams.getInstallerUid());
11172                        }
11173                    }
11174
11175                    final PackageVerificationState verificationState = new PackageVerificationState(
11176                            requiredUid, args);
11177
11178                    mPendingVerification.append(verificationId, verificationState);
11179
11180                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11181                            receivers, verificationState);
11182
11183                    /*
11184                     * If any sufficient verifiers were listed in the package
11185                     * manifest, attempt to ask them.
11186                     */
11187                    if (sufficientVerifiers != null) {
11188                        final int N = sufficientVerifiers.size();
11189                        if (N == 0) {
11190                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11191                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11192                        } else {
11193                            for (int i = 0; i < N; i++) {
11194                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11195
11196                                final Intent sufficientIntent = new Intent(verification);
11197                                sufficientIntent.setComponent(verifierComponent);
11198                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11199                            }
11200                        }
11201                    }
11202
11203                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11204                            mRequiredVerifierPackage, receivers);
11205                    if (ret == PackageManager.INSTALL_SUCCEEDED
11206                            && mRequiredVerifierPackage != null) {
11207                        Trace.asyncTraceBegin(
11208                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11209                        /*
11210                         * Send the intent to the required verification agent,
11211                         * but only start the verification timeout after the
11212                         * target BroadcastReceivers have run.
11213                         */
11214                        verification.setComponent(requiredVerifierComponent);
11215                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11216                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11217                                new BroadcastReceiver() {
11218                                    @Override
11219                                    public void onReceive(Context context, Intent intent) {
11220                                        final Message msg = mHandler
11221                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11222                                        msg.arg1 = verificationId;
11223                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11224                                    }
11225                                }, null, 0, null, null);
11226
11227                        /*
11228                         * We don't want the copy to proceed until verification
11229                         * succeeds, so null out this field.
11230                         */
11231                        mArgs = null;
11232                    }
11233                } else {
11234                    /*
11235                     * No package verification is enabled, so immediately start
11236                     * the remote call to initiate copy using temporary file.
11237                     */
11238                    ret = args.copyApk(mContainerService, true);
11239                }
11240            }
11241
11242            mRet = ret;
11243        }
11244
11245        @Override
11246        void handleReturnCode() {
11247            // If mArgs is null, then MCS couldn't be reached. When it
11248            // reconnects, it will try again to install. At that point, this
11249            // will succeed.
11250            if (mArgs != null) {
11251                processPendingInstall(mArgs, mRet);
11252            }
11253        }
11254
11255        @Override
11256        void handleServiceError() {
11257            mArgs = createInstallArgs(this);
11258            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11259        }
11260
11261        public boolean isForwardLocked() {
11262            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11263        }
11264    }
11265
11266    /**
11267     * Used during creation of InstallArgs
11268     *
11269     * @param installFlags package installation flags
11270     * @return true if should be installed on external storage
11271     */
11272    private static boolean installOnExternalAsec(int installFlags) {
11273        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11274            return false;
11275        }
11276        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11277            return true;
11278        }
11279        return false;
11280    }
11281
11282    /**
11283     * Used during creation of InstallArgs
11284     *
11285     * @param installFlags package installation flags
11286     * @return true if should be installed as forward locked
11287     */
11288    private static boolean installForwardLocked(int installFlags) {
11289        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11290    }
11291
11292    private InstallArgs createInstallArgs(InstallParams params) {
11293        if (params.move != null) {
11294            return new MoveInstallArgs(params);
11295        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11296            return new AsecInstallArgs(params);
11297        } else {
11298            return new FileInstallArgs(params);
11299        }
11300    }
11301
11302    /**
11303     * Create args that describe an existing installed package. Typically used
11304     * when cleaning up old installs, or used as a move source.
11305     */
11306    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11307            String resourcePath, String[] instructionSets) {
11308        final boolean isInAsec;
11309        if (installOnExternalAsec(installFlags)) {
11310            /* Apps on SD card are always in ASEC containers. */
11311            isInAsec = true;
11312        } else if (installForwardLocked(installFlags)
11313                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11314            /*
11315             * Forward-locked apps are only in ASEC containers if they're the
11316             * new style
11317             */
11318            isInAsec = true;
11319        } else {
11320            isInAsec = false;
11321        }
11322
11323        if (isInAsec) {
11324            return new AsecInstallArgs(codePath, instructionSets,
11325                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11326        } else {
11327            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11328        }
11329    }
11330
11331    static abstract class InstallArgs {
11332        /** @see InstallParams#origin */
11333        final OriginInfo origin;
11334        /** @see InstallParams#move */
11335        final MoveInfo move;
11336
11337        final IPackageInstallObserver2 observer;
11338        // Always refers to PackageManager flags only
11339        final int installFlags;
11340        final String installerPackageName;
11341        final String volumeUuid;
11342        final UserHandle user;
11343        final String abiOverride;
11344        final String[] installGrantPermissions;
11345        /** If non-null, drop an async trace when the install completes */
11346        final String traceMethod;
11347        final int traceCookie;
11348
11349        // The list of instruction sets supported by this app. This is currently
11350        // only used during the rmdex() phase to clean up resources. We can get rid of this
11351        // if we move dex files under the common app path.
11352        /* nullable */ String[] instructionSets;
11353
11354        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11355                int installFlags, String installerPackageName, String volumeUuid,
11356                UserHandle user, String[] instructionSets,
11357                String abiOverride, String[] installGrantPermissions,
11358                String traceMethod, int traceCookie) {
11359            this.origin = origin;
11360            this.move = move;
11361            this.installFlags = installFlags;
11362            this.observer = observer;
11363            this.installerPackageName = installerPackageName;
11364            this.volumeUuid = volumeUuid;
11365            this.user = user;
11366            this.instructionSets = instructionSets;
11367            this.abiOverride = abiOverride;
11368            this.installGrantPermissions = installGrantPermissions;
11369            this.traceMethod = traceMethod;
11370            this.traceCookie = traceCookie;
11371        }
11372
11373        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11374        abstract int doPreInstall(int status);
11375
11376        /**
11377         * Rename package into final resting place. All paths on the given
11378         * scanned package should be updated to reflect the rename.
11379         */
11380        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11381        abstract int doPostInstall(int status, int uid);
11382
11383        /** @see PackageSettingBase#codePathString */
11384        abstract String getCodePath();
11385        /** @see PackageSettingBase#resourcePathString */
11386        abstract String getResourcePath();
11387
11388        // Need installer lock especially for dex file removal.
11389        abstract void cleanUpResourcesLI();
11390        abstract boolean doPostDeleteLI(boolean delete);
11391
11392        /**
11393         * Called before the source arguments are copied. This is used mostly
11394         * for MoveParams when it needs to read the source file to put it in the
11395         * destination.
11396         */
11397        int doPreCopy() {
11398            return PackageManager.INSTALL_SUCCEEDED;
11399        }
11400
11401        /**
11402         * Called after the source arguments are copied. This is used mostly for
11403         * MoveParams when it needs to read the source file to put it in the
11404         * destination.
11405         *
11406         * @return
11407         */
11408        int doPostCopy(int uid) {
11409            return PackageManager.INSTALL_SUCCEEDED;
11410        }
11411
11412        protected boolean isFwdLocked() {
11413            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11414        }
11415
11416        protected boolean isExternalAsec() {
11417            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11418        }
11419
11420        protected boolean isEphemeral() {
11421            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11422        }
11423
11424        UserHandle getUser() {
11425            return user;
11426        }
11427    }
11428
11429    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11430        if (!allCodePaths.isEmpty()) {
11431            if (instructionSets == null) {
11432                throw new IllegalStateException("instructionSet == null");
11433            }
11434            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11435            for (String codePath : allCodePaths) {
11436                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11437                    try {
11438                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
11439                    } catch (InstallerException ignored) {
11440                    }
11441                }
11442            }
11443        }
11444    }
11445
11446    /**
11447     * Logic to handle installation of non-ASEC applications, including copying
11448     * and renaming logic.
11449     */
11450    class FileInstallArgs extends InstallArgs {
11451        private File codeFile;
11452        private File resourceFile;
11453
11454        // Example topology:
11455        // /data/app/com.example/base.apk
11456        // /data/app/com.example/split_foo.apk
11457        // /data/app/com.example/lib/arm/libfoo.so
11458        // /data/app/com.example/lib/arm64/libfoo.so
11459        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11460
11461        /** New install */
11462        FileInstallArgs(InstallParams params) {
11463            super(params.origin, params.move, params.observer, params.installFlags,
11464                    params.installerPackageName, params.volumeUuid,
11465                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11466                    params.grantedRuntimePermissions,
11467                    params.traceMethod, params.traceCookie);
11468            if (isFwdLocked()) {
11469                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11470            }
11471        }
11472
11473        /** Existing install */
11474        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11475            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11476                    null, null, null, 0);
11477            this.codeFile = (codePath != null) ? new File(codePath) : null;
11478            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11479        }
11480
11481        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11482            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11483            try {
11484                return doCopyApk(imcs, temp);
11485            } finally {
11486                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11487            }
11488        }
11489
11490        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11491            if (origin.staged) {
11492                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11493                codeFile = origin.file;
11494                resourceFile = origin.file;
11495                return PackageManager.INSTALL_SUCCEEDED;
11496            }
11497
11498            try {
11499                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11500                final File tempDir =
11501                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11502                codeFile = tempDir;
11503                resourceFile = tempDir;
11504            } catch (IOException e) {
11505                Slog.w(TAG, "Failed to create copy file: " + e);
11506                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11507            }
11508
11509            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11510                @Override
11511                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11512                    if (!FileUtils.isValidExtFilename(name)) {
11513                        throw new IllegalArgumentException("Invalid filename: " + name);
11514                    }
11515                    try {
11516                        final File file = new File(codeFile, name);
11517                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11518                                O_RDWR | O_CREAT, 0644);
11519                        Os.chmod(file.getAbsolutePath(), 0644);
11520                        return new ParcelFileDescriptor(fd);
11521                    } catch (ErrnoException e) {
11522                        throw new RemoteException("Failed to open: " + e.getMessage());
11523                    }
11524                }
11525            };
11526
11527            int ret = PackageManager.INSTALL_SUCCEEDED;
11528            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11529            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11530                Slog.e(TAG, "Failed to copy package");
11531                return ret;
11532            }
11533
11534            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11535            NativeLibraryHelper.Handle handle = null;
11536            try {
11537                handle = NativeLibraryHelper.Handle.create(codeFile);
11538                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11539                        abiOverride);
11540            } catch (IOException e) {
11541                Slog.e(TAG, "Copying native libraries failed", e);
11542                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11543            } finally {
11544                IoUtils.closeQuietly(handle);
11545            }
11546
11547            return ret;
11548        }
11549
11550        int doPreInstall(int status) {
11551            if (status != PackageManager.INSTALL_SUCCEEDED) {
11552                cleanUp();
11553            }
11554            return status;
11555        }
11556
11557        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11558            if (status != PackageManager.INSTALL_SUCCEEDED) {
11559                cleanUp();
11560                return false;
11561            }
11562
11563            final File targetDir = codeFile.getParentFile();
11564            final File beforeCodeFile = codeFile;
11565            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11566
11567            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11568            try {
11569                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11570            } catch (ErrnoException e) {
11571                Slog.w(TAG, "Failed to rename", e);
11572                return false;
11573            }
11574
11575            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11576                Slog.w(TAG, "Failed to restorecon");
11577                return false;
11578            }
11579
11580            // Reflect the rename internally
11581            codeFile = afterCodeFile;
11582            resourceFile = afterCodeFile;
11583
11584            // Reflect the rename in scanned details
11585            pkg.codePath = afterCodeFile.getAbsolutePath();
11586            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11587                    pkg.baseCodePath);
11588            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11589                    pkg.splitCodePaths);
11590
11591            // Reflect the rename in app info
11592            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11593            pkg.applicationInfo.setCodePath(pkg.codePath);
11594            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11595            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11596            pkg.applicationInfo.setResourcePath(pkg.codePath);
11597            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11598            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11599
11600            return true;
11601        }
11602
11603        int doPostInstall(int status, int uid) {
11604            if (status != PackageManager.INSTALL_SUCCEEDED) {
11605                cleanUp();
11606            }
11607            return status;
11608        }
11609
11610        @Override
11611        String getCodePath() {
11612            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11613        }
11614
11615        @Override
11616        String getResourcePath() {
11617            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11618        }
11619
11620        private boolean cleanUp() {
11621            if (codeFile == null || !codeFile.exists()) {
11622                return false;
11623            }
11624
11625            removeCodePathLI(codeFile);
11626
11627            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11628                resourceFile.delete();
11629            }
11630
11631            return true;
11632        }
11633
11634        void cleanUpResourcesLI() {
11635            // Try enumerating all code paths before deleting
11636            List<String> allCodePaths = Collections.EMPTY_LIST;
11637            if (codeFile != null && codeFile.exists()) {
11638                try {
11639                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11640                    allCodePaths = pkg.getAllCodePaths();
11641                } catch (PackageParserException e) {
11642                    // Ignored; we tried our best
11643                }
11644            }
11645
11646            cleanUp();
11647            removeDexFiles(allCodePaths, instructionSets);
11648        }
11649
11650        boolean doPostDeleteLI(boolean delete) {
11651            // XXX err, shouldn't we respect the delete flag?
11652            cleanUpResourcesLI();
11653            return true;
11654        }
11655    }
11656
11657    private boolean isAsecExternal(String cid) {
11658        final String asecPath = PackageHelper.getSdFilesystem(cid);
11659        return !asecPath.startsWith(mAsecInternalPath);
11660    }
11661
11662    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11663            PackageManagerException {
11664        if (copyRet < 0) {
11665            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11666                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11667                throw new PackageManagerException(copyRet, message);
11668            }
11669        }
11670    }
11671
11672    /**
11673     * Extract the MountService "container ID" from the full code path of an
11674     * .apk.
11675     */
11676    static String cidFromCodePath(String fullCodePath) {
11677        int eidx = fullCodePath.lastIndexOf("/");
11678        String subStr1 = fullCodePath.substring(0, eidx);
11679        int sidx = subStr1.lastIndexOf("/");
11680        return subStr1.substring(sidx+1, eidx);
11681    }
11682
11683    /**
11684     * Logic to handle installation of ASEC applications, including copying and
11685     * renaming logic.
11686     */
11687    class AsecInstallArgs extends InstallArgs {
11688        static final String RES_FILE_NAME = "pkg.apk";
11689        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11690
11691        String cid;
11692        String packagePath;
11693        String resourcePath;
11694
11695        /** New install */
11696        AsecInstallArgs(InstallParams params) {
11697            super(params.origin, params.move, params.observer, params.installFlags,
11698                    params.installerPackageName, params.volumeUuid,
11699                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11700                    params.grantedRuntimePermissions,
11701                    params.traceMethod, params.traceCookie);
11702        }
11703
11704        /** Existing install */
11705        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11706                        boolean isExternal, boolean isForwardLocked) {
11707            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11708                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11709                    instructionSets, null, null, null, 0);
11710            // Hackily pretend we're still looking at a full code path
11711            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11712                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11713            }
11714
11715            // Extract cid from fullCodePath
11716            int eidx = fullCodePath.lastIndexOf("/");
11717            String subStr1 = fullCodePath.substring(0, eidx);
11718            int sidx = subStr1.lastIndexOf("/");
11719            cid = subStr1.substring(sidx+1, eidx);
11720            setMountPath(subStr1);
11721        }
11722
11723        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11724            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11725                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11726                    instructionSets, null, null, null, 0);
11727            this.cid = cid;
11728            setMountPath(PackageHelper.getSdDir(cid));
11729        }
11730
11731        void createCopyFile() {
11732            cid = mInstallerService.allocateExternalStageCidLegacy();
11733        }
11734
11735        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11736            if (origin.staged && origin.cid != null) {
11737                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11738                cid = origin.cid;
11739                setMountPath(PackageHelper.getSdDir(cid));
11740                return PackageManager.INSTALL_SUCCEEDED;
11741            }
11742
11743            if (temp) {
11744                createCopyFile();
11745            } else {
11746                /*
11747                 * Pre-emptively destroy the container since it's destroyed if
11748                 * copying fails due to it existing anyway.
11749                 */
11750                PackageHelper.destroySdDir(cid);
11751            }
11752
11753            final String newMountPath = imcs.copyPackageToContainer(
11754                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11755                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11756
11757            if (newMountPath != null) {
11758                setMountPath(newMountPath);
11759                return PackageManager.INSTALL_SUCCEEDED;
11760            } else {
11761                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11762            }
11763        }
11764
11765        @Override
11766        String getCodePath() {
11767            return packagePath;
11768        }
11769
11770        @Override
11771        String getResourcePath() {
11772            return resourcePath;
11773        }
11774
11775        int doPreInstall(int status) {
11776            if (status != PackageManager.INSTALL_SUCCEEDED) {
11777                // Destroy container
11778                PackageHelper.destroySdDir(cid);
11779            } else {
11780                boolean mounted = PackageHelper.isContainerMounted(cid);
11781                if (!mounted) {
11782                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11783                            Process.SYSTEM_UID);
11784                    if (newMountPath != null) {
11785                        setMountPath(newMountPath);
11786                    } else {
11787                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11788                    }
11789                }
11790            }
11791            return status;
11792        }
11793
11794        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11795            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11796            String newMountPath = null;
11797            if (PackageHelper.isContainerMounted(cid)) {
11798                // Unmount the container
11799                if (!PackageHelper.unMountSdDir(cid)) {
11800                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11801                    return false;
11802                }
11803            }
11804            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11805                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11806                        " which might be stale. Will try to clean up.");
11807                // Clean up the stale container and proceed to recreate.
11808                if (!PackageHelper.destroySdDir(newCacheId)) {
11809                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11810                    return false;
11811                }
11812                // Successfully cleaned up stale container. Try to rename again.
11813                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11814                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11815                            + " inspite of cleaning it up.");
11816                    return false;
11817                }
11818            }
11819            if (!PackageHelper.isContainerMounted(newCacheId)) {
11820                Slog.w(TAG, "Mounting container " + newCacheId);
11821                newMountPath = PackageHelper.mountSdDir(newCacheId,
11822                        getEncryptKey(), Process.SYSTEM_UID);
11823            } else {
11824                newMountPath = PackageHelper.getSdDir(newCacheId);
11825            }
11826            if (newMountPath == null) {
11827                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11828                return false;
11829            }
11830            Log.i(TAG, "Succesfully renamed " + cid +
11831                    " to " + newCacheId +
11832                    " at new path: " + newMountPath);
11833            cid = newCacheId;
11834
11835            final File beforeCodeFile = new File(packagePath);
11836            setMountPath(newMountPath);
11837            final File afterCodeFile = new File(packagePath);
11838
11839            // Reflect the rename in scanned details
11840            pkg.codePath = afterCodeFile.getAbsolutePath();
11841            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11842                    pkg.baseCodePath);
11843            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11844                    pkg.splitCodePaths);
11845
11846            // Reflect the rename in app info
11847            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11848            pkg.applicationInfo.setCodePath(pkg.codePath);
11849            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11850            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11851            pkg.applicationInfo.setResourcePath(pkg.codePath);
11852            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11853            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11854
11855            return true;
11856        }
11857
11858        private void setMountPath(String mountPath) {
11859            final File mountFile = new File(mountPath);
11860
11861            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11862            if (monolithicFile.exists()) {
11863                packagePath = monolithicFile.getAbsolutePath();
11864                if (isFwdLocked()) {
11865                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11866                } else {
11867                    resourcePath = packagePath;
11868                }
11869            } else {
11870                packagePath = mountFile.getAbsolutePath();
11871                resourcePath = packagePath;
11872            }
11873        }
11874
11875        int doPostInstall(int status, int uid) {
11876            if (status != PackageManager.INSTALL_SUCCEEDED) {
11877                cleanUp();
11878            } else {
11879                final int groupOwner;
11880                final String protectedFile;
11881                if (isFwdLocked()) {
11882                    groupOwner = UserHandle.getSharedAppGid(uid);
11883                    protectedFile = RES_FILE_NAME;
11884                } else {
11885                    groupOwner = -1;
11886                    protectedFile = null;
11887                }
11888
11889                if (uid < Process.FIRST_APPLICATION_UID
11890                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11891                    Slog.e(TAG, "Failed to finalize " + cid);
11892                    PackageHelper.destroySdDir(cid);
11893                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11894                }
11895
11896                boolean mounted = PackageHelper.isContainerMounted(cid);
11897                if (!mounted) {
11898                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11899                }
11900            }
11901            return status;
11902        }
11903
11904        private void cleanUp() {
11905            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11906
11907            // Destroy secure container
11908            PackageHelper.destroySdDir(cid);
11909        }
11910
11911        private List<String> getAllCodePaths() {
11912            final File codeFile = new File(getCodePath());
11913            if (codeFile != null && codeFile.exists()) {
11914                try {
11915                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11916                    return pkg.getAllCodePaths();
11917                } catch (PackageParserException e) {
11918                    // Ignored; we tried our best
11919                }
11920            }
11921            return Collections.EMPTY_LIST;
11922        }
11923
11924        void cleanUpResourcesLI() {
11925            // Enumerate all code paths before deleting
11926            cleanUpResourcesLI(getAllCodePaths());
11927        }
11928
11929        private void cleanUpResourcesLI(List<String> allCodePaths) {
11930            cleanUp();
11931            removeDexFiles(allCodePaths, instructionSets);
11932        }
11933
11934        String getPackageName() {
11935            return getAsecPackageName(cid);
11936        }
11937
11938        boolean doPostDeleteLI(boolean delete) {
11939            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11940            final List<String> allCodePaths = getAllCodePaths();
11941            boolean mounted = PackageHelper.isContainerMounted(cid);
11942            if (mounted) {
11943                // Unmount first
11944                if (PackageHelper.unMountSdDir(cid)) {
11945                    mounted = false;
11946                }
11947            }
11948            if (!mounted && delete) {
11949                cleanUpResourcesLI(allCodePaths);
11950            }
11951            return !mounted;
11952        }
11953
11954        @Override
11955        int doPreCopy() {
11956            if (isFwdLocked()) {
11957                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
11958                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
11959                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11960                }
11961            }
11962
11963            return PackageManager.INSTALL_SUCCEEDED;
11964        }
11965
11966        @Override
11967        int doPostCopy(int uid) {
11968            if (isFwdLocked()) {
11969                if (uid < Process.FIRST_APPLICATION_UID
11970                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11971                                RES_FILE_NAME)) {
11972                    Slog.e(TAG, "Failed to finalize " + cid);
11973                    PackageHelper.destroySdDir(cid);
11974                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11975                }
11976            }
11977
11978            return PackageManager.INSTALL_SUCCEEDED;
11979        }
11980    }
11981
11982    /**
11983     * Logic to handle movement of existing installed applications.
11984     */
11985    class MoveInstallArgs extends InstallArgs {
11986        private File codeFile;
11987        private File resourceFile;
11988
11989        /** New install */
11990        MoveInstallArgs(InstallParams params) {
11991            super(params.origin, params.move, params.observer, params.installFlags,
11992                    params.installerPackageName, params.volumeUuid,
11993                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11994                    params.grantedRuntimePermissions,
11995                    params.traceMethod, params.traceCookie);
11996        }
11997
11998        int copyApk(IMediaContainerService imcs, boolean temp) {
11999            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12000                    + move.fromUuid + " to " + move.toUuid);
12001            synchronized (mInstaller) {
12002                try {
12003                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12004                            move.dataAppName, move.appId, move.seinfo);
12005                } catch (InstallerException e) {
12006                    Slog.w(TAG, "Failed to move app", e);
12007                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12008                }
12009            }
12010
12011            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12012            resourceFile = codeFile;
12013            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12014
12015            return PackageManager.INSTALL_SUCCEEDED;
12016        }
12017
12018        int doPreInstall(int status) {
12019            if (status != PackageManager.INSTALL_SUCCEEDED) {
12020                cleanUp(move.toUuid);
12021            }
12022            return status;
12023        }
12024
12025        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12026            if (status != PackageManager.INSTALL_SUCCEEDED) {
12027                cleanUp(move.toUuid);
12028                return false;
12029            }
12030
12031            // Reflect the move in app info
12032            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12033            pkg.applicationInfo.setCodePath(pkg.codePath);
12034            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12035            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12036            pkg.applicationInfo.setResourcePath(pkg.codePath);
12037            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12038            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12039
12040            return true;
12041        }
12042
12043        int doPostInstall(int status, int uid) {
12044            if (status == PackageManager.INSTALL_SUCCEEDED) {
12045                cleanUp(move.fromUuid);
12046            } else {
12047                cleanUp(move.toUuid);
12048            }
12049            return status;
12050        }
12051
12052        @Override
12053        String getCodePath() {
12054            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12055        }
12056
12057        @Override
12058        String getResourcePath() {
12059            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12060        }
12061
12062        private boolean cleanUp(String volumeUuid) {
12063            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12064                    move.dataAppName);
12065            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12066            synchronized (mInstallLock) {
12067                // Clean up both app data and code
12068                removeDataDirsLI(volumeUuid, move.packageName);
12069                removeCodePathLI(codeFile);
12070            }
12071            return true;
12072        }
12073
12074        void cleanUpResourcesLI() {
12075            throw new UnsupportedOperationException();
12076        }
12077
12078        boolean doPostDeleteLI(boolean delete) {
12079            throw new UnsupportedOperationException();
12080        }
12081    }
12082
12083    static String getAsecPackageName(String packageCid) {
12084        int idx = packageCid.lastIndexOf("-");
12085        if (idx == -1) {
12086            return packageCid;
12087        }
12088        return packageCid.substring(0, idx);
12089    }
12090
12091    // Utility method used to create code paths based on package name and available index.
12092    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12093        String idxStr = "";
12094        int idx = 1;
12095        // Fall back to default value of idx=1 if prefix is not
12096        // part of oldCodePath
12097        if (oldCodePath != null) {
12098            String subStr = oldCodePath;
12099            // Drop the suffix right away
12100            if (suffix != null && subStr.endsWith(suffix)) {
12101                subStr = subStr.substring(0, subStr.length() - suffix.length());
12102            }
12103            // If oldCodePath already contains prefix find out the
12104            // ending index to either increment or decrement.
12105            int sidx = subStr.lastIndexOf(prefix);
12106            if (sidx != -1) {
12107                subStr = subStr.substring(sidx + prefix.length());
12108                if (subStr != null) {
12109                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12110                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12111                    }
12112                    try {
12113                        idx = Integer.parseInt(subStr);
12114                        if (idx <= 1) {
12115                            idx++;
12116                        } else {
12117                            idx--;
12118                        }
12119                    } catch(NumberFormatException e) {
12120                    }
12121                }
12122            }
12123        }
12124        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12125        return prefix + idxStr;
12126    }
12127
12128    private File getNextCodePath(File targetDir, String packageName) {
12129        int suffix = 1;
12130        File result;
12131        do {
12132            result = new File(targetDir, packageName + "-" + suffix);
12133            suffix++;
12134        } while (result.exists());
12135        return result;
12136    }
12137
12138    // Utility method that returns the relative package path with respect
12139    // to the installation directory. Like say for /data/data/com.test-1.apk
12140    // string com.test-1 is returned.
12141    static String deriveCodePathName(String codePath) {
12142        if (codePath == null) {
12143            return null;
12144        }
12145        final File codeFile = new File(codePath);
12146        final String name = codeFile.getName();
12147        if (codeFile.isDirectory()) {
12148            return name;
12149        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12150            final int lastDot = name.lastIndexOf('.');
12151            return name.substring(0, lastDot);
12152        } else {
12153            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12154            return null;
12155        }
12156    }
12157
12158    static class PackageInstalledInfo {
12159        String name;
12160        int uid;
12161        // The set of users that originally had this package installed.
12162        int[] origUsers;
12163        // The set of users that now have this package installed.
12164        int[] newUsers;
12165        PackageParser.Package pkg;
12166        int returnCode;
12167        String returnMsg;
12168        PackageRemovedInfo removedInfo;
12169
12170        public void setError(int code, String msg) {
12171            returnCode = code;
12172            returnMsg = msg;
12173            Slog.w(TAG, msg);
12174        }
12175
12176        public void setError(String msg, PackageParserException e) {
12177            returnCode = e.error;
12178            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12179            Slog.w(TAG, msg, e);
12180        }
12181
12182        public void setError(String msg, PackageManagerException e) {
12183            returnCode = e.error;
12184            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12185            Slog.w(TAG, msg, e);
12186        }
12187
12188        // In some error cases we want to convey more info back to the observer
12189        String origPackage;
12190        String origPermission;
12191    }
12192
12193    /*
12194     * Install a non-existing package.
12195     */
12196    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12197            UserHandle user, String installerPackageName, String volumeUuid,
12198            PackageInstalledInfo res) {
12199        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12200
12201        // Remember this for later, in case we need to rollback this install
12202        String pkgName = pkg.packageName;
12203
12204        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12205        // TODO: b/23350563
12206        final boolean dataDirExists = Environment
12207                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12208
12209        synchronized(mPackages) {
12210            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12211                // A package with the same name is already installed, though
12212                // it has been renamed to an older name.  The package we
12213                // are trying to install should be installed as an update to
12214                // the existing one, but that has not been requested, so bail.
12215                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12216                        + " without first uninstalling package running as "
12217                        + mSettings.mRenamedPackages.get(pkgName));
12218                return;
12219            }
12220            if (mPackages.containsKey(pkgName)) {
12221                // Don't allow installation over an existing package with the same name.
12222                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12223                        + " without first uninstalling.");
12224                return;
12225            }
12226        }
12227
12228        try {
12229            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12230                    System.currentTimeMillis(), user);
12231
12232            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12233            prepareAppDataAfterInstall(newPackage);
12234
12235            // delete the partially installed application. the data directory will have to be
12236            // restored if it was already existing
12237            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12238                // remove package from internal structures.  Note that we want deletePackageX to
12239                // delete the package data and cache directories that it created in
12240                // scanPackageLocked, unless those directories existed before we even tried to
12241                // install.
12242                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12243                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12244                                res.removedInfo, true);
12245            }
12246
12247        } catch (PackageManagerException e) {
12248            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12249        }
12250
12251        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12252    }
12253
12254    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12255        // Can't rotate keys during boot or if sharedUser.
12256        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12257                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12258            return false;
12259        }
12260        // app is using upgradeKeySets; make sure all are valid
12261        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12262        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12263        for (int i = 0; i < upgradeKeySets.length; i++) {
12264            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12265                Slog.wtf(TAG, "Package "
12266                         + (oldPs.name != null ? oldPs.name : "<null>")
12267                         + " contains upgrade-key-set reference to unknown key-set: "
12268                         + upgradeKeySets[i]
12269                         + " reverting to signatures check.");
12270                return false;
12271            }
12272        }
12273        return true;
12274    }
12275
12276    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12277        // Upgrade keysets are being used.  Determine if new package has a superset of the
12278        // required keys.
12279        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12280        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12281        for (int i = 0; i < upgradeKeySets.length; i++) {
12282            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12283            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12284                return true;
12285            }
12286        }
12287        return false;
12288    }
12289
12290    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12291            UserHandle user, String installerPackageName, String volumeUuid,
12292            PackageInstalledInfo res) {
12293        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12294
12295        final PackageParser.Package oldPackage;
12296        final String pkgName = pkg.packageName;
12297        final int[] allUsers;
12298        final boolean[] perUserInstalled;
12299
12300        // First find the old package info and check signatures
12301        synchronized(mPackages) {
12302            oldPackage = mPackages.get(pkgName);
12303            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12304            if (isEphemeral && !oldIsEphemeral) {
12305                // can't downgrade from full to ephemeral
12306                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12307                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12308                return;
12309            }
12310            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12311            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12312            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12313                if(!checkUpgradeKeySetLP(ps, pkg)) {
12314                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12315                            "New package not signed by keys specified by upgrade-keysets: "
12316                            + pkgName);
12317                    return;
12318                }
12319            } else {
12320                // default to original signature matching
12321                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12322                    != PackageManager.SIGNATURE_MATCH) {
12323                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12324                            "New package has a different signature: " + pkgName);
12325                    return;
12326                }
12327            }
12328
12329            // In case of rollback, remember per-user/profile install state
12330            allUsers = sUserManager.getUserIds();
12331            perUserInstalled = new boolean[allUsers.length];
12332            for (int i = 0; i < allUsers.length; i++) {
12333                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12334            }
12335        }
12336
12337        boolean sysPkg = (isSystemApp(oldPackage));
12338        if (sysPkg) {
12339            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12340                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12341        } else {
12342            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12343                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12344        }
12345    }
12346
12347    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12348            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12349            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12350            String volumeUuid, PackageInstalledInfo res) {
12351        String pkgName = deletedPackage.packageName;
12352        boolean deletedPkg = true;
12353        boolean updatedSettings = false;
12354
12355        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12356                + deletedPackage);
12357        long origUpdateTime;
12358        if (pkg.mExtras != null) {
12359            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12360        } else {
12361            origUpdateTime = 0;
12362        }
12363
12364        // First delete the existing package while retaining the data directory
12365        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12366                res.removedInfo, true)) {
12367            // If the existing package wasn't successfully deleted
12368            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12369            deletedPkg = false;
12370        } else {
12371            // Successfully deleted the old package; proceed with replace.
12372
12373            // If deleted package lived in a container, give users a chance to
12374            // relinquish resources before killing.
12375            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12376                if (DEBUG_INSTALL) {
12377                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12378                }
12379                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12380                final ArrayList<String> pkgList = new ArrayList<String>(1);
12381                pkgList.add(deletedPackage.applicationInfo.packageName);
12382                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12383            }
12384
12385            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12386            try {
12387                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12388                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12389                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12390                        perUserInstalled, res, user);
12391                prepareAppDataAfterInstall(newPackage);
12392                updatedSettings = true;
12393            } catch (PackageManagerException e) {
12394                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12395            }
12396        }
12397
12398        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12399            // remove package from internal structures.  Note that we want deletePackageX to
12400            // delete the package data and cache directories that it created in
12401            // scanPackageLocked, unless those directories existed before we even tried to
12402            // install.
12403            if(updatedSettings) {
12404                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12405                deletePackageLI(
12406                        pkgName, null, true, allUsers, perUserInstalled,
12407                        PackageManager.DELETE_KEEP_DATA,
12408                                res.removedInfo, true);
12409            }
12410            // Since we failed to install the new package we need to restore the old
12411            // package that we deleted.
12412            if (deletedPkg) {
12413                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12414                File restoreFile = new File(deletedPackage.codePath);
12415                // Parse old package
12416                boolean oldExternal = isExternal(deletedPackage);
12417                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12418                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12419                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12420                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12421                try {
12422                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12423                            null);
12424                } catch (PackageManagerException e) {
12425                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12426                            + e.getMessage());
12427                    return;
12428                }
12429                // Restore of old package succeeded. Update permissions.
12430                // writer
12431                synchronized (mPackages) {
12432                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12433                            UPDATE_PERMISSIONS_ALL);
12434                    // can downgrade to reader
12435                    mSettings.writeLPr();
12436                }
12437                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12438            }
12439        }
12440    }
12441
12442    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12443            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12444            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12445            String volumeUuid, PackageInstalledInfo res) {
12446        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12447                + ", old=" + deletedPackage);
12448        boolean disabledSystem = false;
12449        boolean updatedSettings = false;
12450        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12451        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12452                != 0) {
12453            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12454        }
12455        String packageName = deletedPackage.packageName;
12456        if (packageName == null) {
12457            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12458                    "Attempt to delete null packageName.");
12459            return;
12460        }
12461        PackageParser.Package oldPkg;
12462        PackageSetting oldPkgSetting;
12463        // reader
12464        synchronized (mPackages) {
12465            oldPkg = mPackages.get(packageName);
12466            oldPkgSetting = mSettings.mPackages.get(packageName);
12467            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12468                    (oldPkgSetting == null)) {
12469                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12470                        "Couldn't find package " + packageName + " information");
12471                return;
12472            }
12473        }
12474
12475        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12476
12477        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12478        res.removedInfo.removedPackage = packageName;
12479        // Remove existing system package
12480        removePackageLI(oldPkgSetting, true);
12481        // writer
12482        synchronized (mPackages) {
12483            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12484            if (!disabledSystem && deletedPackage != null) {
12485                // We didn't need to disable the .apk as a current system package,
12486                // which means we are replacing another update that is already
12487                // installed.  We need to make sure to delete the older one's .apk.
12488                res.removedInfo.args = createInstallArgsForExisting(0,
12489                        deletedPackage.applicationInfo.getCodePath(),
12490                        deletedPackage.applicationInfo.getResourcePath(),
12491                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12492            } else {
12493                res.removedInfo.args = null;
12494            }
12495        }
12496
12497        // Successfully disabled the old package. Now proceed with re-installation
12498        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12499
12500        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12501        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12502
12503        PackageParser.Package newPackage = null;
12504        try {
12505            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12506            if (newPackage.mExtras != null) {
12507                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12508                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12509                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12510
12511                // is the update attempting to change shared user? that isn't going to work...
12512                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12513                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12514                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12515                            + " to " + newPkgSetting.sharedUser);
12516                    updatedSettings = true;
12517                }
12518            }
12519
12520            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12521                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12522                        perUserInstalled, res, user);
12523                prepareAppDataAfterInstall(newPackage);
12524                updatedSettings = true;
12525            }
12526
12527        } catch (PackageManagerException e) {
12528            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12529        }
12530
12531        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12532            // Re installation failed. Restore old information
12533            // Remove new pkg information
12534            if (newPackage != null) {
12535                removeInstalledPackageLI(newPackage, true);
12536            }
12537            // Add back the old system package
12538            try {
12539                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12540            } catch (PackageManagerException e) {
12541                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12542            }
12543            // Restore the old system information in Settings
12544            synchronized (mPackages) {
12545                if (disabledSystem) {
12546                    mSettings.enableSystemPackageLPw(packageName);
12547                }
12548                if (updatedSettings) {
12549                    mSettings.setInstallerPackageName(packageName,
12550                            oldPkgSetting.installerPackageName);
12551                }
12552                mSettings.writeLPr();
12553            }
12554        }
12555    }
12556
12557    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12558        // Collect all used permissions in the UID
12559        ArraySet<String> usedPermissions = new ArraySet<>();
12560        final int packageCount = su.packages.size();
12561        for (int i = 0; i < packageCount; i++) {
12562            PackageSetting ps = su.packages.valueAt(i);
12563            if (ps.pkg == null) {
12564                continue;
12565            }
12566            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12567            for (int j = 0; j < requestedPermCount; j++) {
12568                String permission = ps.pkg.requestedPermissions.get(j);
12569                BasePermission bp = mSettings.mPermissions.get(permission);
12570                if (bp != null) {
12571                    usedPermissions.add(permission);
12572                }
12573            }
12574        }
12575
12576        PermissionsState permissionsState = su.getPermissionsState();
12577        // Prune install permissions
12578        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12579        final int installPermCount = installPermStates.size();
12580        for (int i = installPermCount - 1; i >= 0;  i--) {
12581            PermissionState permissionState = installPermStates.get(i);
12582            if (!usedPermissions.contains(permissionState.getName())) {
12583                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12584                if (bp != null) {
12585                    permissionsState.revokeInstallPermission(bp);
12586                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12587                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12588                }
12589            }
12590        }
12591
12592        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12593
12594        // Prune runtime permissions
12595        for (int userId : allUserIds) {
12596            List<PermissionState> runtimePermStates = permissionsState
12597                    .getRuntimePermissionStates(userId);
12598            final int runtimePermCount = runtimePermStates.size();
12599            for (int i = runtimePermCount - 1; i >= 0; i--) {
12600                PermissionState permissionState = runtimePermStates.get(i);
12601                if (!usedPermissions.contains(permissionState.getName())) {
12602                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12603                    if (bp != null) {
12604                        permissionsState.revokeRuntimePermission(bp, userId);
12605                        permissionsState.updatePermissionFlags(bp, userId,
12606                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12607                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12608                                runtimePermissionChangedUserIds, userId);
12609                    }
12610                }
12611            }
12612        }
12613
12614        return runtimePermissionChangedUserIds;
12615    }
12616
12617    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12618            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12619            UserHandle user) {
12620        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12621
12622        String pkgName = newPackage.packageName;
12623        synchronized (mPackages) {
12624            //write settings. the installStatus will be incomplete at this stage.
12625            //note that the new package setting would have already been
12626            //added to mPackages. It hasn't been persisted yet.
12627            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12628            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12629            mSettings.writeLPr();
12630            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12631        }
12632
12633        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12634        synchronized (mPackages) {
12635            updatePermissionsLPw(newPackage.packageName, newPackage,
12636                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12637                            ? UPDATE_PERMISSIONS_ALL : 0));
12638            // For system-bundled packages, we assume that installing an upgraded version
12639            // of the package implies that the user actually wants to run that new code,
12640            // so we enable the package.
12641            PackageSetting ps = mSettings.mPackages.get(pkgName);
12642            if (ps != null) {
12643                if (isSystemApp(newPackage)) {
12644                    // NB: implicit assumption that system package upgrades apply to all users
12645                    if (DEBUG_INSTALL) {
12646                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12647                    }
12648                    if (res.origUsers != null) {
12649                        for (int userHandle : res.origUsers) {
12650                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12651                                    userHandle, installerPackageName);
12652                        }
12653                    }
12654                    // Also convey the prior install/uninstall state
12655                    if (allUsers != null && perUserInstalled != null) {
12656                        for (int i = 0; i < allUsers.length; i++) {
12657                            if (DEBUG_INSTALL) {
12658                                Slog.d(TAG, "    user " + allUsers[i]
12659                                        + " => " + perUserInstalled[i]);
12660                            }
12661                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12662                        }
12663                        // these install state changes will be persisted in the
12664                        // upcoming call to mSettings.writeLPr().
12665                    }
12666                }
12667                // It's implied that when a user requests installation, they want the app to be
12668                // installed and enabled.
12669                int userId = user.getIdentifier();
12670                if (userId != UserHandle.USER_ALL) {
12671                    ps.setInstalled(true, userId);
12672                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12673                }
12674            }
12675            res.name = pkgName;
12676            res.uid = newPackage.applicationInfo.uid;
12677            res.pkg = newPackage;
12678            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12679            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12680            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12681            //to update install status
12682            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12683            mSettings.writeLPr();
12684            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12685        }
12686
12687        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12688    }
12689
12690    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12691        try {
12692            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12693            installPackageLI(args, res);
12694        } finally {
12695            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12696        }
12697    }
12698
12699    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12700        final int installFlags = args.installFlags;
12701        final String installerPackageName = args.installerPackageName;
12702        final String volumeUuid = args.volumeUuid;
12703        final File tmpPackageFile = new File(args.getCodePath());
12704        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12705        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12706                || (args.volumeUuid != null));
12707        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12708        boolean replace = false;
12709        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12710        if (args.move != null) {
12711            // moving a complete application; perfom an initial scan on the new install location
12712            scanFlags |= SCAN_INITIAL;
12713        }
12714        // Result object to be returned
12715        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12716
12717        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12718
12719        // Sanity check
12720        if (ephemeral && (forwardLocked || onExternal)) {
12721            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12722                    + " external=" + onExternal);
12723            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12724            return;
12725        }
12726
12727        // Retrieve PackageSettings and parse package
12728        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12729                | PackageParser.PARSE_ENFORCE_CODE
12730                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12731                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12732                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12733        PackageParser pp = new PackageParser();
12734        pp.setSeparateProcesses(mSeparateProcesses);
12735        pp.setDisplayMetrics(mMetrics);
12736
12737        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12738        final PackageParser.Package pkg;
12739        try {
12740            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12741        } catch (PackageParserException e) {
12742            res.setError("Failed parse during installPackageLI", e);
12743            return;
12744        } finally {
12745            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12746        }
12747
12748        // Mark that we have an install time CPU ABI override.
12749        pkg.cpuAbiOverride = args.abiOverride;
12750
12751        String pkgName = res.name = pkg.packageName;
12752        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12753            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12754                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12755                return;
12756            }
12757        }
12758
12759        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12760        try {
12761            pp.collectCertificates(pkg, parseFlags);
12762        } catch (PackageParserException e) {
12763            res.setError("Failed collect during installPackageLI", e);
12764            return;
12765        } finally {
12766            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12767        }
12768
12769        // Get rid of all references to package scan path via parser.
12770        pp = null;
12771        String oldCodePath = null;
12772        boolean systemApp = false;
12773        synchronized (mPackages) {
12774            // Check if installing already existing package
12775            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12776                String oldName = mSettings.mRenamedPackages.get(pkgName);
12777                if (pkg.mOriginalPackages != null
12778                        && pkg.mOriginalPackages.contains(oldName)
12779                        && mPackages.containsKey(oldName)) {
12780                    // This package is derived from an original package,
12781                    // and this device has been updating from that original
12782                    // name.  We must continue using the original name, so
12783                    // rename the new package here.
12784                    pkg.setPackageName(oldName);
12785                    pkgName = pkg.packageName;
12786                    replace = true;
12787                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12788                            + oldName + " pkgName=" + pkgName);
12789                } else if (mPackages.containsKey(pkgName)) {
12790                    // This package, under its official name, already exists
12791                    // on the device; we should replace it.
12792                    replace = true;
12793                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12794                }
12795
12796                // Prevent apps opting out from runtime permissions
12797                if (replace) {
12798                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12799                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12800                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12801                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12802                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12803                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12804                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12805                                        + " doesn't support runtime permissions but the old"
12806                                        + " target SDK " + oldTargetSdk + " does.");
12807                        return;
12808                    }
12809                }
12810            }
12811
12812            PackageSetting ps = mSettings.mPackages.get(pkgName);
12813            if (ps != null) {
12814                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12815
12816                // Quick sanity check that we're signed correctly if updating;
12817                // we'll check this again later when scanning, but we want to
12818                // bail early here before tripping over redefined permissions.
12819                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12820                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12821                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12822                                + pkg.packageName + " upgrade keys do not match the "
12823                                + "previously installed version");
12824                        return;
12825                    }
12826                } else {
12827                    try {
12828                        verifySignaturesLP(ps, pkg);
12829                    } catch (PackageManagerException e) {
12830                        res.setError(e.error, e.getMessage());
12831                        return;
12832                    }
12833                }
12834
12835                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12836                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12837                    systemApp = (ps.pkg.applicationInfo.flags &
12838                            ApplicationInfo.FLAG_SYSTEM) != 0;
12839                }
12840                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12841            }
12842
12843            // Check whether the newly-scanned package wants to define an already-defined perm
12844            int N = pkg.permissions.size();
12845            for (int i = N-1; i >= 0; i--) {
12846                PackageParser.Permission perm = pkg.permissions.get(i);
12847                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12848                if (bp != null) {
12849                    // If the defining package is signed with our cert, it's okay.  This
12850                    // also includes the "updating the same package" case, of course.
12851                    // "updating same package" could also involve key-rotation.
12852                    final boolean sigsOk;
12853                    if (bp.sourcePackage.equals(pkg.packageName)
12854                            && (bp.packageSetting instanceof PackageSetting)
12855                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12856                                    scanFlags))) {
12857                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12858                    } else {
12859                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12860                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12861                    }
12862                    if (!sigsOk) {
12863                        // If the owning package is the system itself, we log but allow
12864                        // install to proceed; we fail the install on all other permission
12865                        // redefinitions.
12866                        if (!bp.sourcePackage.equals("android")) {
12867                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12868                                    + pkg.packageName + " attempting to redeclare permission "
12869                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12870                            res.origPermission = perm.info.name;
12871                            res.origPackage = bp.sourcePackage;
12872                            return;
12873                        } else {
12874                            Slog.w(TAG, "Package " + pkg.packageName
12875                                    + " attempting to redeclare system permission "
12876                                    + perm.info.name + "; ignoring new declaration");
12877                            pkg.permissions.remove(i);
12878                        }
12879                    }
12880                }
12881            }
12882
12883        }
12884
12885        if (systemApp) {
12886            if (onExternal) {
12887                // Abort update; system app can't be replaced with app on sdcard
12888                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12889                        "Cannot install updates to system apps on sdcard");
12890                return;
12891            } else if (ephemeral) {
12892                // Abort update; system app can't be replaced with an ephemeral app
12893                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12894                        "Cannot update a system app with an ephemeral app");
12895                return;
12896            }
12897        }
12898
12899        if (args.move != null) {
12900            // We did an in-place move, so dex is ready to roll
12901            scanFlags |= SCAN_NO_DEX;
12902            scanFlags |= SCAN_MOVE;
12903
12904            synchronized (mPackages) {
12905                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12906                if (ps == null) {
12907                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12908                            "Missing settings for moved package " + pkgName);
12909                }
12910
12911                // We moved the entire application as-is, so bring over the
12912                // previously derived ABI information.
12913                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12914                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12915            }
12916
12917        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12918            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12919            scanFlags |= SCAN_NO_DEX;
12920
12921            try {
12922                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12923                        true /* extract libs */);
12924            } catch (PackageManagerException pme) {
12925                Slog.e(TAG, "Error deriving application ABI", pme);
12926                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12927                return;
12928            }
12929        }
12930
12931        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12932            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12933            return;
12934        }
12935
12936        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12937
12938        if (replace) {
12939            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12940                    installerPackageName, volumeUuid, res);
12941        } else {
12942            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12943                    args.user, installerPackageName, volumeUuid, res);
12944        }
12945        synchronized (mPackages) {
12946            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12947            if (ps != null) {
12948                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12949            }
12950        }
12951    }
12952
12953    private void startIntentFilterVerifications(int userId, boolean replacing,
12954            PackageParser.Package pkg) {
12955        if (mIntentFilterVerifierComponent == null) {
12956            Slog.w(TAG, "No IntentFilter verification will not be done as "
12957                    + "there is no IntentFilterVerifier available!");
12958            return;
12959        }
12960
12961        final int verifierUid = getPackageUid(
12962                mIntentFilterVerifierComponent.getPackageName(),
12963                MATCH_DEBUG_TRIAGED_MISSING,
12964                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12965
12966        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12967        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12968        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12969        mHandler.sendMessage(msg);
12970    }
12971
12972    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12973            PackageParser.Package pkg) {
12974        int size = pkg.activities.size();
12975        if (size == 0) {
12976            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12977                    "No activity, so no need to verify any IntentFilter!");
12978            return;
12979        }
12980
12981        final boolean hasDomainURLs = hasDomainURLs(pkg);
12982        if (!hasDomainURLs) {
12983            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12984                    "No domain URLs, so no need to verify any IntentFilter!");
12985            return;
12986        }
12987
12988        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12989                + " if any IntentFilter from the " + size
12990                + " Activities needs verification ...");
12991
12992        int count = 0;
12993        final String packageName = pkg.packageName;
12994
12995        synchronized (mPackages) {
12996            // If this is a new install and we see that we've already run verification for this
12997            // package, we have nothing to do: it means the state was restored from backup.
12998            if (!replacing) {
12999                IntentFilterVerificationInfo ivi =
13000                        mSettings.getIntentFilterVerificationLPr(packageName);
13001                if (ivi != null) {
13002                    if (DEBUG_DOMAIN_VERIFICATION) {
13003                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13004                                + ivi.getStatusString());
13005                    }
13006                    return;
13007                }
13008            }
13009
13010            // If any filters need to be verified, then all need to be.
13011            boolean needToVerify = false;
13012            for (PackageParser.Activity a : pkg.activities) {
13013                for (ActivityIntentInfo filter : a.intents) {
13014                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13015                        if (DEBUG_DOMAIN_VERIFICATION) {
13016                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13017                        }
13018                        needToVerify = true;
13019                        break;
13020                    }
13021                }
13022            }
13023
13024            if (needToVerify) {
13025                final int verificationId = mIntentFilterVerificationToken++;
13026                for (PackageParser.Activity a : pkg.activities) {
13027                    for (ActivityIntentInfo filter : a.intents) {
13028                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13029                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13030                                    "Verification needed for IntentFilter:" + filter.toString());
13031                            mIntentFilterVerifier.addOneIntentFilterVerification(
13032                                    verifierUid, userId, verificationId, filter, packageName);
13033                            count++;
13034                        }
13035                    }
13036                }
13037            }
13038        }
13039
13040        if (count > 0) {
13041            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13042                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13043                    +  " for userId:" + userId);
13044            mIntentFilterVerifier.startVerifications(userId);
13045        } else {
13046            if (DEBUG_DOMAIN_VERIFICATION) {
13047                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13048            }
13049        }
13050    }
13051
13052    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13053        final ComponentName cn  = filter.activity.getComponentName();
13054        final String packageName = cn.getPackageName();
13055
13056        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13057                packageName);
13058        if (ivi == null) {
13059            return true;
13060        }
13061        int status = ivi.getStatus();
13062        switch (status) {
13063            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13064            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13065                return true;
13066
13067            default:
13068                // Nothing to do
13069                return false;
13070        }
13071    }
13072
13073    private static boolean isMultiArch(ApplicationInfo info) {
13074        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13075    }
13076
13077    private static boolean isExternal(PackageParser.Package pkg) {
13078        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13079    }
13080
13081    private static boolean isExternal(PackageSetting ps) {
13082        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13083    }
13084
13085    private static boolean isEphemeral(PackageParser.Package pkg) {
13086        return pkg.applicationInfo.isEphemeralApp();
13087    }
13088
13089    private static boolean isEphemeral(PackageSetting ps) {
13090        return ps.pkg != null && isEphemeral(ps.pkg);
13091    }
13092
13093    private static boolean isSystemApp(PackageParser.Package pkg) {
13094        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13095    }
13096
13097    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13098        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13099    }
13100
13101    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13102        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13103    }
13104
13105    private static boolean isSystemApp(PackageSetting ps) {
13106        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13107    }
13108
13109    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13110        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13111    }
13112
13113    private int packageFlagsToInstallFlags(PackageSetting ps) {
13114        int installFlags = 0;
13115        if (isEphemeral(ps)) {
13116            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13117        }
13118        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13119            // This existing package was an external ASEC install when we have
13120            // the external flag without a UUID
13121            installFlags |= PackageManager.INSTALL_EXTERNAL;
13122        }
13123        if (ps.isForwardLocked()) {
13124            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13125        }
13126        return installFlags;
13127    }
13128
13129    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13130        if (isExternal(pkg)) {
13131            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13132                return StorageManager.UUID_PRIMARY_PHYSICAL;
13133            } else {
13134                return pkg.volumeUuid;
13135            }
13136        } else {
13137            return StorageManager.UUID_PRIVATE_INTERNAL;
13138        }
13139    }
13140
13141    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13142        if (isExternal(pkg)) {
13143            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13144                return mSettings.getExternalVersion();
13145            } else {
13146                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13147            }
13148        } else {
13149            return mSettings.getInternalVersion();
13150        }
13151    }
13152
13153    private void deleteTempPackageFiles() {
13154        final FilenameFilter filter = new FilenameFilter() {
13155            public boolean accept(File dir, String name) {
13156                return name.startsWith("vmdl") && name.endsWith(".tmp");
13157            }
13158        };
13159        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13160            file.delete();
13161        }
13162    }
13163
13164    @Override
13165    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13166            int flags) {
13167        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13168                flags);
13169    }
13170
13171    @Override
13172    public void deletePackage(final String packageName,
13173            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13174        mContext.enforceCallingOrSelfPermission(
13175                android.Manifest.permission.DELETE_PACKAGES, null);
13176        Preconditions.checkNotNull(packageName);
13177        Preconditions.checkNotNull(observer);
13178        final int uid = Binder.getCallingUid();
13179        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13180        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13181        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13182            mContext.enforceCallingOrSelfPermission(
13183                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13184                    "deletePackage for user " + userId);
13185        }
13186
13187        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13188            try {
13189                observer.onPackageDeleted(packageName,
13190                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13191            } catch (RemoteException re) {
13192            }
13193            return;
13194        }
13195
13196        for (int currentUserId : users) {
13197            if (getBlockUninstallForUser(packageName, currentUserId)) {
13198                try {
13199                    observer.onPackageDeleted(packageName,
13200                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13201                } catch (RemoteException re) {
13202                }
13203                return;
13204            }
13205        }
13206
13207        if (DEBUG_REMOVE) {
13208            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13209        }
13210        // Queue up an async operation since the package deletion may take a little while.
13211        mHandler.post(new Runnable() {
13212            public void run() {
13213                mHandler.removeCallbacks(this);
13214                final int returnCode = deletePackageX(packageName, userId, flags);
13215                try {
13216                    observer.onPackageDeleted(packageName, returnCode, null);
13217                } catch (RemoteException e) {
13218                    Log.i(TAG, "Observer no longer exists.");
13219                } //end catch
13220            } //end run
13221        });
13222    }
13223
13224    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13225        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13226                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13227        try {
13228            if (dpm != null) {
13229                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13230                        /* callingUserOnly =*/ false);
13231                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13232                        : deviceOwnerComponentName.getPackageName();
13233                // Does the package contains the device owner?
13234                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13235                // this check is probably not needed, since DO should be registered as a device
13236                // admin on some user too. (Original bug for this: b/17657954)
13237                if (packageName.equals(deviceOwnerPackageName)) {
13238                    return true;
13239                }
13240                // Does it contain a device admin for any user?
13241                int[] users;
13242                if (userId == UserHandle.USER_ALL) {
13243                    users = sUserManager.getUserIds();
13244                } else {
13245                    users = new int[]{userId};
13246                }
13247                for (int i = 0; i < users.length; ++i) {
13248                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13249                        return true;
13250                    }
13251                }
13252            }
13253        } catch (RemoteException e) {
13254        }
13255        return false;
13256    }
13257
13258    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13259        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13260    }
13261
13262    /**
13263     *  This method is an internal method that could be get invoked either
13264     *  to delete an installed package or to clean up a failed installation.
13265     *  After deleting an installed package, a broadcast is sent to notify any
13266     *  listeners that the package has been installed. For cleaning up a failed
13267     *  installation, the broadcast is not necessary since the package's
13268     *  installation wouldn't have sent the initial broadcast either
13269     *  The key steps in deleting a package are
13270     *  deleting the package information in internal structures like mPackages,
13271     *  deleting the packages base directories through installd
13272     *  updating mSettings to reflect current status
13273     *  persisting settings for later use
13274     *  sending a broadcast if necessary
13275     */
13276    private int deletePackageX(String packageName, int userId, int flags) {
13277        final PackageRemovedInfo info = new PackageRemovedInfo();
13278        final boolean res;
13279
13280        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13281                ? UserHandle.ALL : new UserHandle(userId);
13282
13283        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13284            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13285            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13286        }
13287
13288        boolean removedForAllUsers = false;
13289        boolean systemUpdate = false;
13290
13291        PackageParser.Package uninstalledPkg;
13292
13293        // for the uninstall-updates case and restricted profiles, remember the per-
13294        // userhandle installed state
13295        int[] allUsers;
13296        boolean[] perUserInstalled;
13297        synchronized (mPackages) {
13298            uninstalledPkg = mPackages.get(packageName);
13299            PackageSetting ps = mSettings.mPackages.get(packageName);
13300            allUsers = sUserManager.getUserIds();
13301            perUserInstalled = new boolean[allUsers.length];
13302            for (int i = 0; i < allUsers.length; i++) {
13303                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13304            }
13305        }
13306
13307        synchronized (mInstallLock) {
13308            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13309            res = deletePackageLI(packageName, removeForUser,
13310                    true, allUsers, perUserInstalled,
13311                    flags | REMOVE_CHATTY, info, true);
13312            systemUpdate = info.isRemovedPackageSystemUpdate;
13313            synchronized (mPackages) {
13314                if (res) {
13315                    if (!systemUpdate && mPackages.get(packageName) == null) {
13316                        removedForAllUsers = true;
13317                    }
13318                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13319                }
13320            }
13321            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13322                    + " removedForAllUsers=" + removedForAllUsers);
13323        }
13324
13325        if (res) {
13326            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13327
13328            // If the removed package was a system update, the old system package
13329            // was re-enabled; we need to broadcast this information
13330            if (systemUpdate) {
13331                Bundle extras = new Bundle(1);
13332                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13333                        ? info.removedAppId : info.uid);
13334                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13335
13336                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13337                        extras, 0, null, null, null);
13338                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13339                        extras, 0, null, null, null);
13340                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13341                        null, 0, packageName, null, null);
13342            }
13343        }
13344        // Force a gc here.
13345        Runtime.getRuntime().gc();
13346        // Delete the resources here after sending the broadcast to let
13347        // other processes clean up before deleting resources.
13348        if (info.args != null) {
13349            synchronized (mInstallLock) {
13350                info.args.doPostDeleteLI(true);
13351            }
13352        }
13353
13354        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13355    }
13356
13357    class PackageRemovedInfo {
13358        String removedPackage;
13359        int uid = -1;
13360        int removedAppId = -1;
13361        int[] removedUsers = null;
13362        boolean isRemovedPackageSystemUpdate = false;
13363        // Clean up resources deleted packages.
13364        InstallArgs args = null;
13365
13366        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13367            Bundle extras = new Bundle(1);
13368            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13369            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13370            if (replacing) {
13371                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13372            }
13373            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13374            if (removedPackage != null) {
13375                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13376                        extras, 0, null, null, removedUsers);
13377                if (fullRemove && !replacing) {
13378                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13379                            extras, 0, null, null, removedUsers);
13380                }
13381            }
13382            if (removedAppId >= 0) {
13383                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13384                        removedUsers);
13385            }
13386        }
13387    }
13388
13389    /*
13390     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13391     * flag is not set, the data directory is removed as well.
13392     * make sure this flag is set for partially installed apps. If not its meaningless to
13393     * delete a partially installed application.
13394     */
13395    private void removePackageDataLI(PackageSetting ps,
13396            int[] allUserHandles, boolean[] perUserInstalled,
13397            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13398        String packageName = ps.name;
13399        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13400        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13401        // Retrieve object to delete permissions for shared user later on
13402        final PackageSetting deletedPs;
13403        // reader
13404        synchronized (mPackages) {
13405            deletedPs = mSettings.mPackages.get(packageName);
13406            if (outInfo != null) {
13407                outInfo.removedPackage = packageName;
13408                outInfo.removedUsers = deletedPs != null
13409                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13410                        : null;
13411            }
13412        }
13413        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13414            removeDataDirsLI(ps.volumeUuid, packageName);
13415            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13416        }
13417        // writer
13418        synchronized (mPackages) {
13419            if (deletedPs != null) {
13420                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13421                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13422                    clearDefaultBrowserIfNeeded(packageName);
13423                    if (outInfo != null) {
13424                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13425                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13426                    }
13427                    updatePermissionsLPw(deletedPs.name, null, 0);
13428                    if (deletedPs.sharedUser != null) {
13429                        // Remove permissions associated with package. Since runtime
13430                        // permissions are per user we have to kill the removed package
13431                        // or packages running under the shared user of the removed
13432                        // package if revoking the permissions requested only by the removed
13433                        // package is successful and this causes a change in gids.
13434                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13435                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13436                                    userId);
13437                            if (userIdToKill == UserHandle.USER_ALL
13438                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13439                                // If gids changed for this user, kill all affected packages.
13440                                mHandler.post(new Runnable() {
13441                                    @Override
13442                                    public void run() {
13443                                        // This has to happen with no lock held.
13444                                        killApplication(deletedPs.name, deletedPs.appId,
13445                                                KILL_APP_REASON_GIDS_CHANGED);
13446                                    }
13447                                });
13448                                break;
13449                            }
13450                        }
13451                    }
13452                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13453                }
13454                // make sure to preserve per-user disabled state if this removal was just
13455                // a downgrade of a system app to the factory package
13456                if (allUserHandles != null && perUserInstalled != null) {
13457                    if (DEBUG_REMOVE) {
13458                        Slog.d(TAG, "Propagating install state across downgrade");
13459                    }
13460                    for (int i = 0; i < allUserHandles.length; i++) {
13461                        if (DEBUG_REMOVE) {
13462                            Slog.d(TAG, "    user " + allUserHandles[i]
13463                                    + " => " + perUserInstalled[i]);
13464                        }
13465                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13466                    }
13467                }
13468            }
13469            // can downgrade to reader
13470            if (writeSettings) {
13471                // Save settings now
13472                mSettings.writeLPr();
13473            }
13474        }
13475        if (outInfo != null) {
13476            // A user ID was deleted here. Go through all users and remove it
13477            // from KeyStore.
13478            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13479        }
13480    }
13481
13482    static boolean locationIsPrivileged(File path) {
13483        try {
13484            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13485                    .getCanonicalPath();
13486            return path.getCanonicalPath().startsWith(privilegedAppDir);
13487        } catch (IOException e) {
13488            Slog.e(TAG, "Unable to access code path " + path);
13489        }
13490        return false;
13491    }
13492
13493    /*
13494     * Tries to delete system package.
13495     */
13496    private boolean deleteSystemPackageLI(PackageSetting newPs,
13497            int[] allUserHandles, boolean[] perUserInstalled,
13498            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13499        final boolean applyUserRestrictions
13500                = (allUserHandles != null) && (perUserInstalled != null);
13501        PackageSetting disabledPs = null;
13502        // Confirm if the system package has been updated
13503        // An updated system app can be deleted. This will also have to restore
13504        // the system pkg from system partition
13505        // reader
13506        synchronized (mPackages) {
13507            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13508        }
13509        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13510                + " disabledPs=" + disabledPs);
13511        if (disabledPs == null) {
13512            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13513            return false;
13514        } else if (DEBUG_REMOVE) {
13515            Slog.d(TAG, "Deleting system pkg from data partition");
13516        }
13517        if (DEBUG_REMOVE) {
13518            if (applyUserRestrictions) {
13519                Slog.d(TAG, "Remembering install states:");
13520                for (int i = 0; i < allUserHandles.length; i++) {
13521                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13522                }
13523            }
13524        }
13525        // Delete the updated package
13526        outInfo.isRemovedPackageSystemUpdate = true;
13527        if (disabledPs.versionCode < newPs.versionCode) {
13528            // Delete data for downgrades
13529            flags &= ~PackageManager.DELETE_KEEP_DATA;
13530        } else {
13531            // Preserve data by setting flag
13532            flags |= PackageManager.DELETE_KEEP_DATA;
13533        }
13534        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13535                allUserHandles, perUserInstalled, outInfo, writeSettings);
13536        if (!ret) {
13537            return false;
13538        }
13539        // writer
13540        synchronized (mPackages) {
13541            // Reinstate the old system package
13542            mSettings.enableSystemPackageLPw(newPs.name);
13543            // Remove any native libraries from the upgraded package.
13544            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13545        }
13546        // Install the system package
13547        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13548        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13549        if (locationIsPrivileged(disabledPs.codePath)) {
13550            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13551        }
13552
13553        final PackageParser.Package newPkg;
13554        try {
13555            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13556        } catch (PackageManagerException e) {
13557            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13558            return false;
13559        }
13560
13561        prepareAppDataAfterInstall(newPkg);
13562
13563        // writer
13564        synchronized (mPackages) {
13565            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13566
13567            // Propagate the permissions state as we do not want to drop on the floor
13568            // runtime permissions. The update permissions method below will take
13569            // care of removing obsolete permissions and grant install permissions.
13570            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13571            updatePermissionsLPw(newPkg.packageName, newPkg,
13572                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13573
13574            if (applyUserRestrictions) {
13575                if (DEBUG_REMOVE) {
13576                    Slog.d(TAG, "Propagating install state across reinstall");
13577                }
13578                for (int i = 0; i < allUserHandles.length; i++) {
13579                    if (DEBUG_REMOVE) {
13580                        Slog.d(TAG, "    user " + allUserHandles[i]
13581                                + " => " + perUserInstalled[i]);
13582                    }
13583                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13584
13585                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13586                }
13587                // Regardless of writeSettings we need to ensure that this restriction
13588                // state propagation is persisted
13589                mSettings.writeAllUsersPackageRestrictionsLPr();
13590            }
13591            // can downgrade to reader here
13592            if (writeSettings) {
13593                mSettings.writeLPr();
13594            }
13595        }
13596        return true;
13597    }
13598
13599    private boolean deleteInstalledPackageLI(PackageSetting ps,
13600            boolean deleteCodeAndResources, int flags,
13601            int[] allUserHandles, boolean[] perUserInstalled,
13602            PackageRemovedInfo outInfo, boolean writeSettings) {
13603        if (outInfo != null) {
13604            outInfo.uid = ps.appId;
13605        }
13606
13607        // Delete package data from internal structures and also remove data if flag is set
13608        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13609
13610        // Delete application code and resources
13611        if (deleteCodeAndResources && (outInfo != null)) {
13612            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13613                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13614            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13615        }
13616        return true;
13617    }
13618
13619    @Override
13620    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13621            int userId) {
13622        mContext.enforceCallingOrSelfPermission(
13623                android.Manifest.permission.DELETE_PACKAGES, null);
13624        synchronized (mPackages) {
13625            PackageSetting ps = mSettings.mPackages.get(packageName);
13626            if (ps == null) {
13627                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13628                return false;
13629            }
13630            if (!ps.getInstalled(userId)) {
13631                // Can't block uninstall for an app that is not installed or enabled.
13632                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13633                return false;
13634            }
13635            ps.setBlockUninstall(blockUninstall, userId);
13636            mSettings.writePackageRestrictionsLPr(userId);
13637        }
13638        return true;
13639    }
13640
13641    @Override
13642    public boolean getBlockUninstallForUser(String packageName, int userId) {
13643        synchronized (mPackages) {
13644            PackageSetting ps = mSettings.mPackages.get(packageName);
13645            if (ps == null) {
13646                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13647                return false;
13648            }
13649            return ps.getBlockUninstall(userId);
13650        }
13651    }
13652
13653    @Override
13654    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13655        int callingUid = Binder.getCallingUid();
13656        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13657            throw new SecurityException(
13658                    "setRequiredForSystemUser can only be run by the system or root");
13659        }
13660        synchronized (mPackages) {
13661            PackageSetting ps = mSettings.mPackages.get(packageName);
13662            if (ps == null) {
13663                Log.w(TAG, "Package doesn't exist: " + packageName);
13664                return false;
13665            }
13666            if (systemUserApp) {
13667                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13668            } else {
13669                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13670            }
13671            mSettings.writeLPr();
13672        }
13673        return true;
13674    }
13675
13676    /*
13677     * This method handles package deletion in general
13678     */
13679    private boolean deletePackageLI(String packageName, UserHandle user,
13680            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13681            int flags, PackageRemovedInfo outInfo,
13682            boolean writeSettings) {
13683        if (packageName == null) {
13684            Slog.w(TAG, "Attempt to delete null packageName.");
13685            return false;
13686        }
13687        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13688        PackageSetting ps;
13689        boolean dataOnly = false;
13690        int removeUser = -1;
13691        int appId = -1;
13692        synchronized (mPackages) {
13693            ps = mSettings.mPackages.get(packageName);
13694            if (ps == null) {
13695                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13696                return false;
13697            }
13698            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13699                    && user.getIdentifier() != UserHandle.USER_ALL) {
13700                // The caller is asking that the package only be deleted for a single
13701                // user.  To do this, we just mark its uninstalled state and delete
13702                // its data.  If this is a system app, we only allow this to happen if
13703                // they have set the special DELETE_SYSTEM_APP which requests different
13704                // semantics than normal for uninstalling system apps.
13705                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13706                final int userId = user.getIdentifier();
13707                ps.setUserState(userId,
13708                        COMPONENT_ENABLED_STATE_DEFAULT,
13709                        false, //installed
13710                        true,  //stopped
13711                        true,  //notLaunched
13712                        false, //hidden
13713                        false, //suspended
13714                        null, null, null,
13715                        false, // blockUninstall
13716                        ps.readUserState(userId).domainVerificationStatus, 0);
13717                if (!isSystemApp(ps)) {
13718                    // Do not uninstall the APK if an app should be cached
13719                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13720                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13721                        // Other user still have this package installed, so all
13722                        // we need to do is clear this user's data and save that
13723                        // it is uninstalled.
13724                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13725                        removeUser = user.getIdentifier();
13726                        appId = ps.appId;
13727                        scheduleWritePackageRestrictionsLocked(removeUser);
13728                    } else {
13729                        // We need to set it back to 'installed' so the uninstall
13730                        // broadcasts will be sent correctly.
13731                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13732                        ps.setInstalled(true, user.getIdentifier());
13733                    }
13734                } else {
13735                    // This is a system app, so we assume that the
13736                    // other users still have this package installed, so all
13737                    // we need to do is clear this user's data and save that
13738                    // it is uninstalled.
13739                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13740                    removeUser = user.getIdentifier();
13741                    appId = ps.appId;
13742                    scheduleWritePackageRestrictionsLocked(removeUser);
13743                }
13744            }
13745        }
13746
13747        if (removeUser >= 0) {
13748            // From above, we determined that we are deleting this only
13749            // for a single user.  Continue the work here.
13750            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13751            if (outInfo != null) {
13752                outInfo.removedPackage = packageName;
13753                outInfo.removedAppId = appId;
13754                outInfo.removedUsers = new int[] {removeUser};
13755            }
13756            // TODO: triage flags as part of 26466827
13757            final int installerFlags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13758            try {
13759                mInstaller.destroyAppData(ps.volumeUuid, packageName, removeUser, installerFlags);
13760            } catch (InstallerException e) {
13761                Slog.w(TAG, "Failed to delete app data", e);
13762            }
13763            removeKeystoreDataIfNeeded(removeUser, appId);
13764            schedulePackageCleaning(packageName, removeUser, false);
13765            synchronized (mPackages) {
13766                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13767                    scheduleWritePackageRestrictionsLocked(removeUser);
13768                }
13769                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13770            }
13771            return true;
13772        }
13773
13774        if (dataOnly) {
13775            // Delete application data first
13776            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13777            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13778            return true;
13779        }
13780
13781        boolean ret = false;
13782        if (isSystemApp(ps)) {
13783            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13784            // When an updated system application is deleted we delete the existing resources as well and
13785            // fall back to existing code in system partition
13786            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13787                    flags, outInfo, writeSettings);
13788        } else {
13789            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13790            // Kill application pre-emptively especially for apps on sd.
13791            killApplication(packageName, ps.appId, "uninstall pkg");
13792            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13793                    allUserHandles, perUserInstalled,
13794                    outInfo, writeSettings);
13795        }
13796
13797        return ret;
13798    }
13799
13800    private final static class ClearStorageConnection implements ServiceConnection {
13801        IMediaContainerService mContainerService;
13802
13803        @Override
13804        public void onServiceConnected(ComponentName name, IBinder service) {
13805            synchronized (this) {
13806                mContainerService = IMediaContainerService.Stub.asInterface(service);
13807                notifyAll();
13808            }
13809        }
13810
13811        @Override
13812        public void onServiceDisconnected(ComponentName name) {
13813        }
13814    }
13815
13816    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13817        final boolean mounted;
13818        if (Environment.isExternalStorageEmulated()) {
13819            mounted = true;
13820        } else {
13821            final String status = Environment.getExternalStorageState();
13822
13823            mounted = status.equals(Environment.MEDIA_MOUNTED)
13824                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13825        }
13826
13827        if (!mounted) {
13828            return;
13829        }
13830
13831        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13832        int[] users;
13833        if (userId == UserHandle.USER_ALL) {
13834            users = sUserManager.getUserIds();
13835        } else {
13836            users = new int[] { userId };
13837        }
13838        final ClearStorageConnection conn = new ClearStorageConnection();
13839        if (mContext.bindServiceAsUser(
13840                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13841            try {
13842                for (int curUser : users) {
13843                    long timeout = SystemClock.uptimeMillis() + 5000;
13844                    synchronized (conn) {
13845                        long now = SystemClock.uptimeMillis();
13846                        while (conn.mContainerService == null && now < timeout) {
13847                            try {
13848                                conn.wait(timeout - now);
13849                            } catch (InterruptedException e) {
13850                            }
13851                        }
13852                    }
13853                    if (conn.mContainerService == null) {
13854                        return;
13855                    }
13856
13857                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13858                    clearDirectory(conn.mContainerService,
13859                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13860                    if (allData) {
13861                        clearDirectory(conn.mContainerService,
13862                                userEnv.buildExternalStorageAppDataDirs(packageName));
13863                        clearDirectory(conn.mContainerService,
13864                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13865                    }
13866                }
13867            } finally {
13868                mContext.unbindService(conn);
13869            }
13870        }
13871    }
13872
13873    @Override
13874    public void clearApplicationUserData(final String packageName,
13875            final IPackageDataObserver observer, final int userId) {
13876        mContext.enforceCallingOrSelfPermission(
13877                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13878        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13879        // Queue up an async operation since the package deletion may take a little while.
13880        mHandler.post(new Runnable() {
13881            public void run() {
13882                mHandler.removeCallbacks(this);
13883                final boolean succeeded;
13884                synchronized (mInstallLock) {
13885                    succeeded = clearApplicationUserDataLI(packageName, userId);
13886                }
13887                clearExternalStorageDataSync(packageName, userId, true);
13888                if (succeeded) {
13889                    // invoke DeviceStorageMonitor's update method to clear any notifications
13890                    DeviceStorageMonitorInternal
13891                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13892                    if (dsm != null) {
13893                        dsm.checkMemory();
13894                    }
13895                }
13896                if(observer != null) {
13897                    try {
13898                        observer.onRemoveCompleted(packageName, succeeded);
13899                    } catch (RemoteException e) {
13900                        Log.i(TAG, "Observer no longer exists.");
13901                    }
13902                } //end if observer
13903            } //end run
13904        });
13905    }
13906
13907    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13908        if (packageName == null) {
13909            Slog.w(TAG, "Attempt to delete null packageName.");
13910            return false;
13911        }
13912
13913        // Try finding details about the requested package
13914        PackageParser.Package pkg;
13915        synchronized (mPackages) {
13916            pkg = mPackages.get(packageName);
13917            if (pkg == null) {
13918                final PackageSetting ps = mSettings.mPackages.get(packageName);
13919                if (ps != null) {
13920                    pkg = ps.pkg;
13921                }
13922            }
13923
13924            if (pkg == null) {
13925                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13926                return false;
13927            }
13928
13929            PackageSetting ps = (PackageSetting) pkg.mExtras;
13930            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13931        }
13932
13933        // Always delete data directories for package, even if we found no other
13934        // record of app. This helps users recover from UID mismatches without
13935        // resorting to a full data wipe.
13936        // TODO: triage flags as part of 26466827
13937        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
13938        try {
13939            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
13940        } catch (InstallerException e) {
13941            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
13942            return false;
13943        }
13944
13945        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
13946        removeKeystoreDataIfNeeded(userId, appId);
13947
13948        // Create a native library symlink only if we have native libraries
13949        // and if the native libraries are 32 bit libraries. We do not provide
13950        // this symlink for 64 bit libraries.
13951        if (pkg.applicationInfo.primaryCpuAbi != null &&
13952                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13953            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13954            try {
13955                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13956                        nativeLibPath, userId);
13957            } catch (InstallerException e) {
13958                Slog.w(TAG, "Failed linking native library dir", e);
13959                return false;
13960            }
13961        }
13962
13963        return true;
13964    }
13965
13966    /**
13967     * Reverts user permission state changes (permissions and flags) in
13968     * all packages for a given user.
13969     *
13970     * @param userId The device user for which to do a reset.
13971     */
13972    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13973        final int packageCount = mPackages.size();
13974        for (int i = 0; i < packageCount; i++) {
13975            PackageParser.Package pkg = mPackages.valueAt(i);
13976            PackageSetting ps = (PackageSetting) pkg.mExtras;
13977            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13978        }
13979    }
13980
13981    /**
13982     * Reverts user permission state changes (permissions and flags).
13983     *
13984     * @param ps The package for which to reset.
13985     * @param userId The device user for which to do a reset.
13986     */
13987    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13988            final PackageSetting ps, final int userId) {
13989        if (ps.pkg == null) {
13990            return;
13991        }
13992
13993        // These are flags that can change base on user actions.
13994        final int userSettableMask = FLAG_PERMISSION_USER_SET
13995                | FLAG_PERMISSION_USER_FIXED
13996                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
13997                | FLAG_PERMISSION_REVIEW_REQUIRED;
13998
13999        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14000                | FLAG_PERMISSION_POLICY_FIXED;
14001
14002        boolean writeInstallPermissions = false;
14003        boolean writeRuntimePermissions = false;
14004
14005        final int permissionCount = ps.pkg.requestedPermissions.size();
14006        for (int i = 0; i < permissionCount; i++) {
14007            String permission = ps.pkg.requestedPermissions.get(i);
14008
14009            BasePermission bp = mSettings.mPermissions.get(permission);
14010            if (bp == null) {
14011                continue;
14012            }
14013
14014            // If shared user we just reset the state to which only this app contributed.
14015            if (ps.sharedUser != null) {
14016                boolean used = false;
14017                final int packageCount = ps.sharedUser.packages.size();
14018                for (int j = 0; j < packageCount; j++) {
14019                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14020                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14021                            && pkg.pkg.requestedPermissions.contains(permission)) {
14022                        used = true;
14023                        break;
14024                    }
14025                }
14026                if (used) {
14027                    continue;
14028                }
14029            }
14030
14031            PermissionsState permissionsState = ps.getPermissionsState();
14032
14033            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14034
14035            // Always clear the user settable flags.
14036            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14037                    bp.name) != null;
14038            // If permission review is enabled and this is a legacy app, mark the
14039            // permission as requiring a review as this is the initial state.
14040            int flags = 0;
14041            if (Build.PERMISSIONS_REVIEW_REQUIRED
14042                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14043                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14044            }
14045            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14046                if (hasInstallState) {
14047                    writeInstallPermissions = true;
14048                } else {
14049                    writeRuntimePermissions = true;
14050                }
14051            }
14052
14053            // Below is only runtime permission handling.
14054            if (!bp.isRuntime()) {
14055                continue;
14056            }
14057
14058            // Never clobber system or policy.
14059            if ((oldFlags & policyOrSystemFlags) != 0) {
14060                continue;
14061            }
14062
14063            // If this permission was granted by default, make sure it is.
14064            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14065                if (permissionsState.grantRuntimePermission(bp, userId)
14066                        != PERMISSION_OPERATION_FAILURE) {
14067                    writeRuntimePermissions = true;
14068                }
14069            // If permission review is enabled the permissions for a legacy apps
14070            // are represented as constantly granted runtime ones, so don't revoke.
14071            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14072                // Otherwise, reset the permission.
14073                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14074                switch (revokeResult) {
14075                    case PERMISSION_OPERATION_SUCCESS: {
14076                        writeRuntimePermissions = true;
14077                    } break;
14078
14079                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14080                        writeRuntimePermissions = true;
14081                        final int appId = ps.appId;
14082                        mHandler.post(new Runnable() {
14083                            @Override
14084                            public void run() {
14085                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14086                            }
14087                        });
14088                    } break;
14089                }
14090            }
14091        }
14092
14093        // Synchronously write as we are taking permissions away.
14094        if (writeRuntimePermissions) {
14095            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14096        }
14097
14098        // Synchronously write as we are taking permissions away.
14099        if (writeInstallPermissions) {
14100            mSettings.writeLPr();
14101        }
14102    }
14103
14104    /**
14105     * Remove entries from the keystore daemon. Will only remove it if the
14106     * {@code appId} is valid.
14107     */
14108    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14109        if (appId < 0) {
14110            return;
14111        }
14112
14113        final KeyStore keyStore = KeyStore.getInstance();
14114        if (keyStore != null) {
14115            if (userId == UserHandle.USER_ALL) {
14116                for (final int individual : sUserManager.getUserIds()) {
14117                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14118                }
14119            } else {
14120                keyStore.clearUid(UserHandle.getUid(userId, appId));
14121            }
14122        } else {
14123            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14124        }
14125    }
14126
14127    @Override
14128    public void deleteApplicationCacheFiles(final String packageName,
14129            final IPackageDataObserver observer) {
14130        mContext.enforceCallingOrSelfPermission(
14131                android.Manifest.permission.DELETE_CACHE_FILES, null);
14132        // Queue up an async operation since the package deletion may take a little while.
14133        final int userId = UserHandle.getCallingUserId();
14134        mHandler.post(new Runnable() {
14135            public void run() {
14136                mHandler.removeCallbacks(this);
14137                final boolean succeded;
14138                synchronized (mInstallLock) {
14139                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14140                }
14141                clearExternalStorageDataSync(packageName, userId, false);
14142                if (observer != null) {
14143                    try {
14144                        observer.onRemoveCompleted(packageName, succeded);
14145                    } catch (RemoteException e) {
14146                        Log.i(TAG, "Observer no longer exists.");
14147                    }
14148                } //end if observer
14149            } //end run
14150        });
14151    }
14152
14153    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14154        if (packageName == null) {
14155            Slog.w(TAG, "Attempt to delete null packageName.");
14156            return false;
14157        }
14158        PackageParser.Package p;
14159        synchronized (mPackages) {
14160            p = mPackages.get(packageName);
14161        }
14162        if (p == null) {
14163            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14164            return false;
14165        }
14166        final ApplicationInfo applicationInfo = p.applicationInfo;
14167        if (applicationInfo == null) {
14168            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14169            return false;
14170        }
14171        // TODO: triage flags as part of 26466827
14172        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14173        try {
14174            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
14175                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
14176        } catch (InstallerException e) {
14177            Slog.w(TAG, "Couldn't remove cache files for package "
14178                    + packageName + " u" + userId, e);
14179            return false;
14180        }
14181        return true;
14182    }
14183
14184    @Override
14185    public void getPackageSizeInfo(final String packageName, int userHandle,
14186            final IPackageStatsObserver observer) {
14187        mContext.enforceCallingOrSelfPermission(
14188                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14189        if (packageName == null) {
14190            throw new IllegalArgumentException("Attempt to get size of null packageName");
14191        }
14192
14193        PackageStats stats = new PackageStats(packageName, userHandle);
14194
14195        /*
14196         * Queue up an async operation since the package measurement may take a
14197         * little while.
14198         */
14199        Message msg = mHandler.obtainMessage(INIT_COPY);
14200        msg.obj = new MeasureParams(stats, observer);
14201        mHandler.sendMessage(msg);
14202    }
14203
14204    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14205            PackageStats pStats) {
14206        if (packageName == null) {
14207            Slog.w(TAG, "Attempt to get size of null packageName.");
14208            return false;
14209        }
14210        PackageParser.Package p;
14211        boolean dataOnly = false;
14212        String libDirRoot = null;
14213        String asecPath = null;
14214        PackageSetting ps = null;
14215        synchronized (mPackages) {
14216            p = mPackages.get(packageName);
14217            ps = mSettings.mPackages.get(packageName);
14218            if(p == null) {
14219                dataOnly = true;
14220                if((ps == null) || (ps.pkg == null)) {
14221                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14222                    return false;
14223                }
14224                p = ps.pkg;
14225            }
14226            if (ps != null) {
14227                libDirRoot = ps.legacyNativeLibraryPathString;
14228            }
14229            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14230                final long token = Binder.clearCallingIdentity();
14231                try {
14232                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14233                    if (secureContainerId != null) {
14234                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14235                    }
14236                } finally {
14237                    Binder.restoreCallingIdentity(token);
14238                }
14239            }
14240        }
14241        String publicSrcDir = null;
14242        if(!dataOnly) {
14243            final ApplicationInfo applicationInfo = p.applicationInfo;
14244            if (applicationInfo == null) {
14245                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14246                return false;
14247            }
14248            if (p.isForwardLocked()) {
14249                publicSrcDir = applicationInfo.getBaseResourcePath();
14250            }
14251        }
14252        // TODO: extend to measure size of split APKs
14253        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14254        // not just the first level.
14255        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14256        // just the primary.
14257        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14258
14259        String apkPath;
14260        File packageDir = new File(p.codePath);
14261
14262        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14263            apkPath = packageDir.getAbsolutePath();
14264            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14265            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14266                libDirRoot = null;
14267            }
14268        } else {
14269            apkPath = p.baseCodePath;
14270        }
14271
14272        // TODO: triage flags as part of 26466827
14273        final int flags = Installer.FLAG_CE_STORAGE | Installer.FLAG_DE_STORAGE;
14274        try {
14275            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
14276                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14277        } catch (InstallerException e) {
14278            return false;
14279        }
14280
14281        // Fix-up for forward-locked applications in ASEC containers.
14282        if (!isExternal(p)) {
14283            pStats.codeSize += pStats.externalCodeSize;
14284            pStats.externalCodeSize = 0L;
14285        }
14286
14287        return true;
14288    }
14289
14290
14291    @Override
14292    public void addPackageToPreferred(String packageName) {
14293        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14294    }
14295
14296    @Override
14297    public void removePackageFromPreferred(String packageName) {
14298        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14299    }
14300
14301    @Override
14302    public List<PackageInfo> getPreferredPackages(int flags) {
14303        return new ArrayList<PackageInfo>();
14304    }
14305
14306    private int getUidTargetSdkVersionLockedLPr(int uid) {
14307        Object obj = mSettings.getUserIdLPr(uid);
14308        if (obj instanceof SharedUserSetting) {
14309            final SharedUserSetting sus = (SharedUserSetting) obj;
14310            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14311            final Iterator<PackageSetting> it = sus.packages.iterator();
14312            while (it.hasNext()) {
14313                final PackageSetting ps = it.next();
14314                if (ps.pkg != null) {
14315                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14316                    if (v < vers) vers = v;
14317                }
14318            }
14319            return vers;
14320        } else if (obj instanceof PackageSetting) {
14321            final PackageSetting ps = (PackageSetting) obj;
14322            if (ps.pkg != null) {
14323                return ps.pkg.applicationInfo.targetSdkVersion;
14324            }
14325        }
14326        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14327    }
14328
14329    @Override
14330    public void addPreferredActivity(IntentFilter filter, int match,
14331            ComponentName[] set, ComponentName activity, int userId) {
14332        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14333                "Adding preferred");
14334    }
14335
14336    private void addPreferredActivityInternal(IntentFilter filter, int match,
14337            ComponentName[] set, ComponentName activity, boolean always, int userId,
14338            String opname) {
14339        // writer
14340        int callingUid = Binder.getCallingUid();
14341        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14342        if (filter.countActions() == 0) {
14343            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14344            return;
14345        }
14346        synchronized (mPackages) {
14347            if (mContext.checkCallingOrSelfPermission(
14348                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14349                    != PackageManager.PERMISSION_GRANTED) {
14350                if (getUidTargetSdkVersionLockedLPr(callingUid)
14351                        < Build.VERSION_CODES.FROYO) {
14352                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14353                            + callingUid);
14354                    return;
14355                }
14356                mContext.enforceCallingOrSelfPermission(
14357                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14358            }
14359
14360            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14361            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14362                    + userId + ":");
14363            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14364            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14365            scheduleWritePackageRestrictionsLocked(userId);
14366        }
14367    }
14368
14369    @Override
14370    public void replacePreferredActivity(IntentFilter filter, int match,
14371            ComponentName[] set, ComponentName activity, int userId) {
14372        if (filter.countActions() != 1) {
14373            throw new IllegalArgumentException(
14374                    "replacePreferredActivity expects filter to have only 1 action.");
14375        }
14376        if (filter.countDataAuthorities() != 0
14377                || filter.countDataPaths() != 0
14378                || filter.countDataSchemes() > 1
14379                || filter.countDataTypes() != 0) {
14380            throw new IllegalArgumentException(
14381                    "replacePreferredActivity expects filter to have no data authorities, " +
14382                    "paths, or types; and at most one scheme.");
14383        }
14384
14385        final int callingUid = Binder.getCallingUid();
14386        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14387        synchronized (mPackages) {
14388            if (mContext.checkCallingOrSelfPermission(
14389                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14390                    != PackageManager.PERMISSION_GRANTED) {
14391                if (getUidTargetSdkVersionLockedLPr(callingUid)
14392                        < Build.VERSION_CODES.FROYO) {
14393                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14394                            + Binder.getCallingUid());
14395                    return;
14396                }
14397                mContext.enforceCallingOrSelfPermission(
14398                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14399            }
14400
14401            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14402            if (pir != null) {
14403                // Get all of the existing entries that exactly match this filter.
14404                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14405                if (existing != null && existing.size() == 1) {
14406                    PreferredActivity cur = existing.get(0);
14407                    if (DEBUG_PREFERRED) {
14408                        Slog.i(TAG, "Checking replace of preferred:");
14409                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14410                        if (!cur.mPref.mAlways) {
14411                            Slog.i(TAG, "  -- CUR; not mAlways!");
14412                        } else {
14413                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14414                            Slog.i(TAG, "  -- CUR: mSet="
14415                                    + Arrays.toString(cur.mPref.mSetComponents));
14416                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14417                            Slog.i(TAG, "  -- NEW: mMatch="
14418                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14419                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14420                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14421                        }
14422                    }
14423                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14424                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14425                            && cur.mPref.sameSet(set)) {
14426                        // Setting the preferred activity to what it happens to be already
14427                        if (DEBUG_PREFERRED) {
14428                            Slog.i(TAG, "Replacing with same preferred activity "
14429                                    + cur.mPref.mShortComponent + " for user "
14430                                    + userId + ":");
14431                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14432                        }
14433                        return;
14434                    }
14435                }
14436
14437                if (existing != null) {
14438                    if (DEBUG_PREFERRED) {
14439                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14440                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14441                    }
14442                    for (int i = 0; i < existing.size(); i++) {
14443                        PreferredActivity pa = existing.get(i);
14444                        if (DEBUG_PREFERRED) {
14445                            Slog.i(TAG, "Removing existing preferred activity "
14446                                    + pa.mPref.mComponent + ":");
14447                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14448                        }
14449                        pir.removeFilter(pa);
14450                    }
14451                }
14452            }
14453            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14454                    "Replacing preferred");
14455        }
14456    }
14457
14458    @Override
14459    public void clearPackagePreferredActivities(String packageName) {
14460        final int uid = Binder.getCallingUid();
14461        // writer
14462        synchronized (mPackages) {
14463            PackageParser.Package pkg = mPackages.get(packageName);
14464            if (pkg == null || pkg.applicationInfo.uid != uid) {
14465                if (mContext.checkCallingOrSelfPermission(
14466                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14467                        != PackageManager.PERMISSION_GRANTED) {
14468                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14469                            < Build.VERSION_CODES.FROYO) {
14470                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14471                                + Binder.getCallingUid());
14472                        return;
14473                    }
14474                    mContext.enforceCallingOrSelfPermission(
14475                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14476                }
14477            }
14478
14479            int user = UserHandle.getCallingUserId();
14480            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14481                scheduleWritePackageRestrictionsLocked(user);
14482            }
14483        }
14484    }
14485
14486    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14487    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14488        ArrayList<PreferredActivity> removed = null;
14489        boolean changed = false;
14490        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14491            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14492            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14493            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14494                continue;
14495            }
14496            Iterator<PreferredActivity> it = pir.filterIterator();
14497            while (it.hasNext()) {
14498                PreferredActivity pa = it.next();
14499                // Mark entry for removal only if it matches the package name
14500                // and the entry is of type "always".
14501                if (packageName == null ||
14502                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14503                                && pa.mPref.mAlways)) {
14504                    if (removed == null) {
14505                        removed = new ArrayList<PreferredActivity>();
14506                    }
14507                    removed.add(pa);
14508                }
14509            }
14510            if (removed != null) {
14511                for (int j=0; j<removed.size(); j++) {
14512                    PreferredActivity pa = removed.get(j);
14513                    pir.removeFilter(pa);
14514                }
14515                changed = true;
14516            }
14517        }
14518        return changed;
14519    }
14520
14521    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14522    private void clearIntentFilterVerificationsLPw(int userId) {
14523        final int packageCount = mPackages.size();
14524        for (int i = 0; i < packageCount; i++) {
14525            PackageParser.Package pkg = mPackages.valueAt(i);
14526            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14527        }
14528    }
14529
14530    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14531    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14532        if (userId == UserHandle.USER_ALL) {
14533            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14534                    sUserManager.getUserIds())) {
14535                for (int oneUserId : sUserManager.getUserIds()) {
14536                    scheduleWritePackageRestrictionsLocked(oneUserId);
14537                }
14538            }
14539        } else {
14540            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14541                scheduleWritePackageRestrictionsLocked(userId);
14542            }
14543        }
14544    }
14545
14546    void clearDefaultBrowserIfNeeded(String packageName) {
14547        for (int oneUserId : sUserManager.getUserIds()) {
14548            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14549            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14550            if (packageName.equals(defaultBrowserPackageName)) {
14551                setDefaultBrowserPackageName(null, oneUserId);
14552            }
14553        }
14554    }
14555
14556    @Override
14557    public void resetApplicationPreferences(int userId) {
14558        mContext.enforceCallingOrSelfPermission(
14559                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14560        // writer
14561        synchronized (mPackages) {
14562            final long identity = Binder.clearCallingIdentity();
14563            try {
14564                clearPackagePreferredActivitiesLPw(null, userId);
14565                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14566                // TODO: We have to reset the default SMS and Phone. This requires
14567                // significant refactoring to keep all default apps in the package
14568                // manager (cleaner but more work) or have the services provide
14569                // callbacks to the package manager to request a default app reset.
14570                applyFactoryDefaultBrowserLPw(userId);
14571                clearIntentFilterVerificationsLPw(userId);
14572                primeDomainVerificationsLPw(userId);
14573                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14574                scheduleWritePackageRestrictionsLocked(userId);
14575            } finally {
14576                Binder.restoreCallingIdentity(identity);
14577            }
14578        }
14579    }
14580
14581    @Override
14582    public int getPreferredActivities(List<IntentFilter> outFilters,
14583            List<ComponentName> outActivities, String packageName) {
14584
14585        int num = 0;
14586        final int userId = UserHandle.getCallingUserId();
14587        // reader
14588        synchronized (mPackages) {
14589            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14590            if (pir != null) {
14591                final Iterator<PreferredActivity> it = pir.filterIterator();
14592                while (it.hasNext()) {
14593                    final PreferredActivity pa = it.next();
14594                    if (packageName == null
14595                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14596                                    && pa.mPref.mAlways)) {
14597                        if (outFilters != null) {
14598                            outFilters.add(new IntentFilter(pa));
14599                        }
14600                        if (outActivities != null) {
14601                            outActivities.add(pa.mPref.mComponent);
14602                        }
14603                    }
14604                }
14605            }
14606        }
14607
14608        return num;
14609    }
14610
14611    @Override
14612    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14613            int userId) {
14614        int callingUid = Binder.getCallingUid();
14615        if (callingUid != Process.SYSTEM_UID) {
14616            throw new SecurityException(
14617                    "addPersistentPreferredActivity can only be run by the system");
14618        }
14619        if (filter.countActions() == 0) {
14620            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14621            return;
14622        }
14623        synchronized (mPackages) {
14624            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14625                    ":");
14626            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14627            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14628                    new PersistentPreferredActivity(filter, activity));
14629            scheduleWritePackageRestrictionsLocked(userId);
14630        }
14631    }
14632
14633    @Override
14634    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14635        int callingUid = Binder.getCallingUid();
14636        if (callingUid != Process.SYSTEM_UID) {
14637            throw new SecurityException(
14638                    "clearPackagePersistentPreferredActivities can only be run by the system");
14639        }
14640        ArrayList<PersistentPreferredActivity> removed = null;
14641        boolean changed = false;
14642        synchronized (mPackages) {
14643            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14644                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14645                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14646                        .valueAt(i);
14647                if (userId != thisUserId) {
14648                    continue;
14649                }
14650                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14651                while (it.hasNext()) {
14652                    PersistentPreferredActivity ppa = it.next();
14653                    // Mark entry for removal only if it matches the package name.
14654                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14655                        if (removed == null) {
14656                            removed = new ArrayList<PersistentPreferredActivity>();
14657                        }
14658                        removed.add(ppa);
14659                    }
14660                }
14661                if (removed != null) {
14662                    for (int j=0; j<removed.size(); j++) {
14663                        PersistentPreferredActivity ppa = removed.get(j);
14664                        ppir.removeFilter(ppa);
14665                    }
14666                    changed = true;
14667                }
14668            }
14669
14670            if (changed) {
14671                scheduleWritePackageRestrictionsLocked(userId);
14672            }
14673        }
14674    }
14675
14676    /**
14677     * Common machinery for picking apart a restored XML blob and passing
14678     * it to a caller-supplied functor to be applied to the running system.
14679     */
14680    private void restoreFromXml(XmlPullParser parser, int userId,
14681            String expectedStartTag, BlobXmlRestorer functor)
14682            throws IOException, XmlPullParserException {
14683        int type;
14684        while ((type = parser.next()) != XmlPullParser.START_TAG
14685                && type != XmlPullParser.END_DOCUMENT) {
14686        }
14687        if (type != XmlPullParser.START_TAG) {
14688            // oops didn't find a start tag?!
14689            if (DEBUG_BACKUP) {
14690                Slog.e(TAG, "Didn't find start tag during restore");
14691            }
14692            return;
14693        }
14694
14695        // this is supposed to be TAG_PREFERRED_BACKUP
14696        if (!expectedStartTag.equals(parser.getName())) {
14697            if (DEBUG_BACKUP) {
14698                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14699            }
14700            return;
14701        }
14702
14703        // skip interfering stuff, then we're aligned with the backing implementation
14704        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14705        functor.apply(parser, userId);
14706    }
14707
14708    private interface BlobXmlRestorer {
14709        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14710    }
14711
14712    /**
14713     * Non-Binder method, support for the backup/restore mechanism: write the
14714     * full set of preferred activities in its canonical XML format.  Returns the
14715     * XML output as a byte array, or null if there is none.
14716     */
14717    @Override
14718    public byte[] getPreferredActivityBackup(int userId) {
14719        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14720            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14721        }
14722
14723        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14724        try {
14725            final XmlSerializer serializer = new FastXmlSerializer();
14726            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14727            serializer.startDocument(null, true);
14728            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14729
14730            synchronized (mPackages) {
14731                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14732            }
14733
14734            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14735            serializer.endDocument();
14736            serializer.flush();
14737        } catch (Exception e) {
14738            if (DEBUG_BACKUP) {
14739                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14740            }
14741            return null;
14742        }
14743
14744        return dataStream.toByteArray();
14745    }
14746
14747    @Override
14748    public void restorePreferredActivities(byte[] backup, int userId) {
14749        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14750            throw new SecurityException("Only the system may call restorePreferredActivities()");
14751        }
14752
14753        try {
14754            final XmlPullParser parser = Xml.newPullParser();
14755            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14756            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14757                    new BlobXmlRestorer() {
14758                        @Override
14759                        public void apply(XmlPullParser parser, int userId)
14760                                throws XmlPullParserException, IOException {
14761                            synchronized (mPackages) {
14762                                mSettings.readPreferredActivitiesLPw(parser, userId);
14763                            }
14764                        }
14765                    } );
14766        } catch (Exception e) {
14767            if (DEBUG_BACKUP) {
14768                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14769            }
14770        }
14771    }
14772
14773    /**
14774     * Non-Binder method, support for the backup/restore mechanism: write the
14775     * default browser (etc) settings in its canonical XML format.  Returns the default
14776     * browser XML representation as a byte array, or null if there is none.
14777     */
14778    @Override
14779    public byte[] getDefaultAppsBackup(int userId) {
14780        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14781            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14782        }
14783
14784        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14785        try {
14786            final XmlSerializer serializer = new FastXmlSerializer();
14787            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14788            serializer.startDocument(null, true);
14789            serializer.startTag(null, TAG_DEFAULT_APPS);
14790
14791            synchronized (mPackages) {
14792                mSettings.writeDefaultAppsLPr(serializer, userId);
14793            }
14794
14795            serializer.endTag(null, TAG_DEFAULT_APPS);
14796            serializer.endDocument();
14797            serializer.flush();
14798        } catch (Exception e) {
14799            if (DEBUG_BACKUP) {
14800                Slog.e(TAG, "Unable to write default apps for backup", e);
14801            }
14802            return null;
14803        }
14804
14805        return dataStream.toByteArray();
14806    }
14807
14808    @Override
14809    public void restoreDefaultApps(byte[] backup, int userId) {
14810        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14811            throw new SecurityException("Only the system may call restoreDefaultApps()");
14812        }
14813
14814        try {
14815            final XmlPullParser parser = Xml.newPullParser();
14816            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14817            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14818                    new BlobXmlRestorer() {
14819                        @Override
14820                        public void apply(XmlPullParser parser, int userId)
14821                                throws XmlPullParserException, IOException {
14822                            synchronized (mPackages) {
14823                                mSettings.readDefaultAppsLPw(parser, userId);
14824                            }
14825                        }
14826                    } );
14827        } catch (Exception e) {
14828            if (DEBUG_BACKUP) {
14829                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14830            }
14831        }
14832    }
14833
14834    @Override
14835    public byte[] getIntentFilterVerificationBackup(int userId) {
14836        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14837            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14838        }
14839
14840        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14841        try {
14842            final XmlSerializer serializer = new FastXmlSerializer();
14843            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14844            serializer.startDocument(null, true);
14845            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14846
14847            synchronized (mPackages) {
14848                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14849            }
14850
14851            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14852            serializer.endDocument();
14853            serializer.flush();
14854        } catch (Exception e) {
14855            if (DEBUG_BACKUP) {
14856                Slog.e(TAG, "Unable to write default apps for backup", e);
14857            }
14858            return null;
14859        }
14860
14861        return dataStream.toByteArray();
14862    }
14863
14864    @Override
14865    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14866        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14867            throw new SecurityException("Only the system may call restorePreferredActivities()");
14868        }
14869
14870        try {
14871            final XmlPullParser parser = Xml.newPullParser();
14872            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14873            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14874                    new BlobXmlRestorer() {
14875                        @Override
14876                        public void apply(XmlPullParser parser, int userId)
14877                                throws XmlPullParserException, IOException {
14878                            synchronized (mPackages) {
14879                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14880                                mSettings.writeLPr();
14881                            }
14882                        }
14883                    } );
14884        } catch (Exception e) {
14885            if (DEBUG_BACKUP) {
14886                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14887            }
14888        }
14889    }
14890
14891    @Override
14892    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14893            int sourceUserId, int targetUserId, int flags) {
14894        mContext.enforceCallingOrSelfPermission(
14895                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14896        int callingUid = Binder.getCallingUid();
14897        enforceOwnerRights(ownerPackage, callingUid);
14898        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14899        if (intentFilter.countActions() == 0) {
14900            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14901            return;
14902        }
14903        synchronized (mPackages) {
14904            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14905                    ownerPackage, targetUserId, flags);
14906            CrossProfileIntentResolver resolver =
14907                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14908            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14909            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14910            if (existing != null) {
14911                int size = existing.size();
14912                for (int i = 0; i < size; i++) {
14913                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14914                        return;
14915                    }
14916                }
14917            }
14918            resolver.addFilter(newFilter);
14919            scheduleWritePackageRestrictionsLocked(sourceUserId);
14920        }
14921    }
14922
14923    @Override
14924    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14925        mContext.enforceCallingOrSelfPermission(
14926                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14927        int callingUid = Binder.getCallingUid();
14928        enforceOwnerRights(ownerPackage, callingUid);
14929        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14930        synchronized (mPackages) {
14931            CrossProfileIntentResolver resolver =
14932                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14933            ArraySet<CrossProfileIntentFilter> set =
14934                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14935            for (CrossProfileIntentFilter filter : set) {
14936                if (filter.getOwnerPackage().equals(ownerPackage)) {
14937                    resolver.removeFilter(filter);
14938                }
14939            }
14940            scheduleWritePackageRestrictionsLocked(sourceUserId);
14941        }
14942    }
14943
14944    // Enforcing that callingUid is owning pkg on userId
14945    private void enforceOwnerRights(String pkg, int callingUid) {
14946        // The system owns everything.
14947        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14948            return;
14949        }
14950        int callingUserId = UserHandle.getUserId(callingUid);
14951        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14952        if (pi == null) {
14953            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14954                    + callingUserId);
14955        }
14956        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14957            throw new SecurityException("Calling uid " + callingUid
14958                    + " does not own package " + pkg);
14959        }
14960    }
14961
14962    @Override
14963    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14964        Intent intent = new Intent(Intent.ACTION_MAIN);
14965        intent.addCategory(Intent.CATEGORY_HOME);
14966
14967        final int callingUserId = UserHandle.getCallingUserId();
14968        List<ResolveInfo> list = queryIntentActivities(intent, null,
14969                PackageManager.GET_META_DATA, callingUserId);
14970        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14971                true, false, false, callingUserId);
14972
14973        allHomeCandidates.clear();
14974        if (list != null) {
14975            for (ResolveInfo ri : list) {
14976                allHomeCandidates.add(ri);
14977            }
14978        }
14979        return (preferred == null || preferred.activityInfo == null)
14980                ? null
14981                : new ComponentName(preferred.activityInfo.packageName,
14982                        preferred.activityInfo.name);
14983    }
14984
14985    @Override
14986    public void setApplicationEnabledSetting(String appPackageName,
14987            int newState, int flags, int userId, String callingPackage) {
14988        if (!sUserManager.exists(userId)) return;
14989        if (callingPackage == null) {
14990            callingPackage = Integer.toString(Binder.getCallingUid());
14991        }
14992        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14993    }
14994
14995    @Override
14996    public void setComponentEnabledSetting(ComponentName componentName,
14997            int newState, int flags, int userId) {
14998        if (!sUserManager.exists(userId)) return;
14999        setEnabledSetting(componentName.getPackageName(),
15000                componentName.getClassName(), newState, flags, userId, null);
15001    }
15002
15003    private void setEnabledSetting(final String packageName, String className, int newState,
15004            final int flags, int userId, String callingPackage) {
15005        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15006              || newState == COMPONENT_ENABLED_STATE_ENABLED
15007              || newState == COMPONENT_ENABLED_STATE_DISABLED
15008              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15009              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15010            throw new IllegalArgumentException("Invalid new component state: "
15011                    + newState);
15012        }
15013        PackageSetting pkgSetting;
15014        final int uid = Binder.getCallingUid();
15015        final int permission = mContext.checkCallingOrSelfPermission(
15016                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15017        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15018        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15019        boolean sendNow = false;
15020        boolean isApp = (className == null);
15021        String componentName = isApp ? packageName : className;
15022        int packageUid = -1;
15023        ArrayList<String> components;
15024
15025        // writer
15026        synchronized (mPackages) {
15027            pkgSetting = mSettings.mPackages.get(packageName);
15028            if (pkgSetting == null) {
15029                if (className == null) {
15030                    throw new IllegalArgumentException("Unknown package: " + packageName);
15031                }
15032                throw new IllegalArgumentException(
15033                        "Unknown component: " + packageName + "/" + className);
15034            }
15035            // Allow root and verify that userId is not being specified by a different user
15036            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15037                throw new SecurityException(
15038                        "Permission Denial: attempt to change component state from pid="
15039                        + Binder.getCallingPid()
15040                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15041            }
15042            if (className == null) {
15043                // We're dealing with an application/package level state change
15044                if (pkgSetting.getEnabled(userId) == newState) {
15045                    // Nothing to do
15046                    return;
15047                }
15048                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15049                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15050                    // Don't care about who enables an app.
15051                    callingPackage = null;
15052                }
15053                pkgSetting.setEnabled(newState, userId, callingPackage);
15054                // pkgSetting.pkg.mSetEnabled = newState;
15055            } else {
15056                // We're dealing with a component level state change
15057                // First, verify that this is a valid class name.
15058                PackageParser.Package pkg = pkgSetting.pkg;
15059                if (pkg == null || !pkg.hasComponentClassName(className)) {
15060                    if (pkg != null &&
15061                            pkg.applicationInfo.targetSdkVersion >=
15062                                    Build.VERSION_CODES.JELLY_BEAN) {
15063                        throw new IllegalArgumentException("Component class " + className
15064                                + " does not exist in " + packageName);
15065                    } else {
15066                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15067                                + className + " does not exist in " + packageName);
15068                    }
15069                }
15070                switch (newState) {
15071                case COMPONENT_ENABLED_STATE_ENABLED:
15072                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15073                        return;
15074                    }
15075                    break;
15076                case COMPONENT_ENABLED_STATE_DISABLED:
15077                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15078                        return;
15079                    }
15080                    break;
15081                case COMPONENT_ENABLED_STATE_DEFAULT:
15082                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15083                        return;
15084                    }
15085                    break;
15086                default:
15087                    Slog.e(TAG, "Invalid new component state: " + newState);
15088                    return;
15089                }
15090            }
15091            scheduleWritePackageRestrictionsLocked(userId);
15092            components = mPendingBroadcasts.get(userId, packageName);
15093            final boolean newPackage = components == null;
15094            if (newPackage) {
15095                components = new ArrayList<String>();
15096            }
15097            if (!components.contains(componentName)) {
15098                components.add(componentName);
15099            }
15100            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15101                sendNow = true;
15102                // Purge entry from pending broadcast list if another one exists already
15103                // since we are sending one right away.
15104                mPendingBroadcasts.remove(userId, packageName);
15105            } else {
15106                if (newPackage) {
15107                    mPendingBroadcasts.put(userId, packageName, components);
15108                }
15109                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15110                    // Schedule a message
15111                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15112                }
15113            }
15114        }
15115
15116        long callingId = Binder.clearCallingIdentity();
15117        try {
15118            if (sendNow) {
15119                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15120                sendPackageChangedBroadcast(packageName,
15121                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15122            }
15123        } finally {
15124            Binder.restoreCallingIdentity(callingId);
15125        }
15126    }
15127
15128    private void sendPackageChangedBroadcast(String packageName,
15129            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15130        if (DEBUG_INSTALL)
15131            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15132                    + componentNames);
15133        Bundle extras = new Bundle(4);
15134        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15135        String nameList[] = new String[componentNames.size()];
15136        componentNames.toArray(nameList);
15137        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15138        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15139        extras.putInt(Intent.EXTRA_UID, packageUid);
15140        // If this is not reporting a change of the overall package, then only send it
15141        // to registered receivers.  We don't want to launch a swath of apps for every
15142        // little component state change.
15143        final int flags = !componentNames.contains(packageName)
15144                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15145        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15146                new int[] {UserHandle.getUserId(packageUid)});
15147    }
15148
15149    @Override
15150    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15151        if (!sUserManager.exists(userId)) return;
15152        final int uid = Binder.getCallingUid();
15153        final int permission = mContext.checkCallingOrSelfPermission(
15154                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15155        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15156        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15157        // writer
15158        synchronized (mPackages) {
15159            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15160                    allowedByPermission, uid, userId)) {
15161                scheduleWritePackageRestrictionsLocked(userId);
15162            }
15163        }
15164    }
15165
15166    @Override
15167    public String getInstallerPackageName(String packageName) {
15168        // reader
15169        synchronized (mPackages) {
15170            return mSettings.getInstallerPackageNameLPr(packageName);
15171        }
15172    }
15173
15174    @Override
15175    public int getApplicationEnabledSetting(String packageName, int userId) {
15176        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15177        int uid = Binder.getCallingUid();
15178        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15179        // reader
15180        synchronized (mPackages) {
15181            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15182        }
15183    }
15184
15185    @Override
15186    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15187        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15188        int uid = Binder.getCallingUid();
15189        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15190        // reader
15191        synchronized (mPackages) {
15192            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15193        }
15194    }
15195
15196    @Override
15197    public void enterSafeMode() {
15198        enforceSystemOrRoot("Only the system can request entering safe mode");
15199
15200        if (!mSystemReady) {
15201            mSafeMode = true;
15202        }
15203    }
15204
15205    @Override
15206    public void systemReady() {
15207        mSystemReady = true;
15208
15209        // Read the compatibilty setting when the system is ready.
15210        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15211                mContext.getContentResolver(),
15212                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15213        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15214        if (DEBUG_SETTINGS) {
15215            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15216        }
15217
15218        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15219
15220        synchronized (mPackages) {
15221            // Verify that all of the preferred activity components actually
15222            // exist.  It is possible for applications to be updated and at
15223            // that point remove a previously declared activity component that
15224            // had been set as a preferred activity.  We try to clean this up
15225            // the next time we encounter that preferred activity, but it is
15226            // possible for the user flow to never be able to return to that
15227            // situation so here we do a sanity check to make sure we haven't
15228            // left any junk around.
15229            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15230            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15231                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15232                removed.clear();
15233                for (PreferredActivity pa : pir.filterSet()) {
15234                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15235                        removed.add(pa);
15236                    }
15237                }
15238                if (removed.size() > 0) {
15239                    for (int r=0; r<removed.size(); r++) {
15240                        PreferredActivity pa = removed.get(r);
15241                        Slog.w(TAG, "Removing dangling preferred activity: "
15242                                + pa.mPref.mComponent);
15243                        pir.removeFilter(pa);
15244                    }
15245                    mSettings.writePackageRestrictionsLPr(
15246                            mSettings.mPreferredActivities.keyAt(i));
15247                }
15248            }
15249
15250            for (int userId : UserManagerService.getInstance().getUserIds()) {
15251                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15252                    grantPermissionsUserIds = ArrayUtils.appendInt(
15253                            grantPermissionsUserIds, userId);
15254                }
15255            }
15256        }
15257        sUserManager.systemReady();
15258
15259        // If we upgraded grant all default permissions before kicking off.
15260        for (int userId : grantPermissionsUserIds) {
15261            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15262        }
15263
15264        // Kick off any messages waiting for system ready
15265        if (mPostSystemReadyMessages != null) {
15266            for (Message msg : mPostSystemReadyMessages) {
15267                msg.sendToTarget();
15268            }
15269            mPostSystemReadyMessages = null;
15270        }
15271
15272        // Watch for external volumes that come and go over time
15273        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15274        storage.registerListener(mStorageListener);
15275
15276        mInstallerService.systemReady();
15277        mPackageDexOptimizer.systemReady();
15278
15279        MountServiceInternal mountServiceInternal = LocalServices.getService(
15280                MountServiceInternal.class);
15281        mountServiceInternal.addExternalStoragePolicy(
15282                new MountServiceInternal.ExternalStorageMountPolicy() {
15283            @Override
15284            public int getMountMode(int uid, String packageName) {
15285                if (Process.isIsolated(uid)) {
15286                    return Zygote.MOUNT_EXTERNAL_NONE;
15287                }
15288                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15289                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15290                }
15291                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15292                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15293                }
15294                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15295                    return Zygote.MOUNT_EXTERNAL_READ;
15296                }
15297                return Zygote.MOUNT_EXTERNAL_WRITE;
15298            }
15299
15300            @Override
15301            public boolean hasExternalStorage(int uid, String packageName) {
15302                return true;
15303            }
15304        });
15305    }
15306
15307    @Override
15308    public boolean isSafeMode() {
15309        return mSafeMode;
15310    }
15311
15312    @Override
15313    public boolean hasSystemUidErrors() {
15314        return mHasSystemUidErrors;
15315    }
15316
15317    static String arrayToString(int[] array) {
15318        StringBuffer buf = new StringBuffer(128);
15319        buf.append('[');
15320        if (array != null) {
15321            for (int i=0; i<array.length; i++) {
15322                if (i > 0) buf.append(", ");
15323                buf.append(array[i]);
15324            }
15325        }
15326        buf.append(']');
15327        return buf.toString();
15328    }
15329
15330    static class DumpState {
15331        public static final int DUMP_LIBS = 1 << 0;
15332        public static final int DUMP_FEATURES = 1 << 1;
15333        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15334        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15335        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15336        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15337        public static final int DUMP_PERMISSIONS = 1 << 6;
15338        public static final int DUMP_PACKAGES = 1 << 7;
15339        public static final int DUMP_SHARED_USERS = 1 << 8;
15340        public static final int DUMP_MESSAGES = 1 << 9;
15341        public static final int DUMP_PROVIDERS = 1 << 10;
15342        public static final int DUMP_VERIFIERS = 1 << 11;
15343        public static final int DUMP_PREFERRED = 1 << 12;
15344        public static final int DUMP_PREFERRED_XML = 1 << 13;
15345        public static final int DUMP_KEYSETS = 1 << 14;
15346        public static final int DUMP_VERSION = 1 << 15;
15347        public static final int DUMP_INSTALLS = 1 << 16;
15348        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15349        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15350
15351        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15352
15353        private int mTypes;
15354
15355        private int mOptions;
15356
15357        private boolean mTitlePrinted;
15358
15359        private SharedUserSetting mSharedUser;
15360
15361        public boolean isDumping(int type) {
15362            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15363                return true;
15364            }
15365
15366            return (mTypes & type) != 0;
15367        }
15368
15369        public void setDump(int type) {
15370            mTypes |= type;
15371        }
15372
15373        public boolean isOptionEnabled(int option) {
15374            return (mOptions & option) != 0;
15375        }
15376
15377        public void setOptionEnabled(int option) {
15378            mOptions |= option;
15379        }
15380
15381        public boolean onTitlePrinted() {
15382            final boolean printed = mTitlePrinted;
15383            mTitlePrinted = true;
15384            return printed;
15385        }
15386
15387        public boolean getTitlePrinted() {
15388            return mTitlePrinted;
15389        }
15390
15391        public void setTitlePrinted(boolean enabled) {
15392            mTitlePrinted = enabled;
15393        }
15394
15395        public SharedUserSetting getSharedUser() {
15396            return mSharedUser;
15397        }
15398
15399        public void setSharedUser(SharedUserSetting user) {
15400            mSharedUser = user;
15401        }
15402    }
15403
15404    @Override
15405    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15406            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15407        (new PackageManagerShellCommand(this)).exec(
15408                this, in, out, err, args, resultReceiver);
15409    }
15410
15411    @Override
15412    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15413        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15414                != PackageManager.PERMISSION_GRANTED) {
15415            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15416                    + Binder.getCallingPid()
15417                    + ", uid=" + Binder.getCallingUid()
15418                    + " without permission "
15419                    + android.Manifest.permission.DUMP);
15420            return;
15421        }
15422
15423        DumpState dumpState = new DumpState();
15424        boolean fullPreferred = false;
15425        boolean checkin = false;
15426
15427        String packageName = null;
15428        ArraySet<String> permissionNames = null;
15429
15430        int opti = 0;
15431        while (opti < args.length) {
15432            String opt = args[opti];
15433            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15434                break;
15435            }
15436            opti++;
15437
15438            if ("-a".equals(opt)) {
15439                // Right now we only know how to print all.
15440            } else if ("-h".equals(opt)) {
15441                pw.println("Package manager dump options:");
15442                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15443                pw.println("    --checkin: dump for a checkin");
15444                pw.println("    -f: print details of intent filters");
15445                pw.println("    -h: print this help");
15446                pw.println("  cmd may be one of:");
15447                pw.println("    l[ibraries]: list known shared libraries");
15448                pw.println("    f[eatures]: list device features");
15449                pw.println("    k[eysets]: print known keysets");
15450                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15451                pw.println("    perm[issions]: dump permissions");
15452                pw.println("    permission [name ...]: dump declaration and use of given permission");
15453                pw.println("    pref[erred]: print preferred package settings");
15454                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15455                pw.println("    prov[iders]: dump content providers");
15456                pw.println("    p[ackages]: dump installed packages");
15457                pw.println("    s[hared-users]: dump shared user IDs");
15458                pw.println("    m[essages]: print collected runtime messages");
15459                pw.println("    v[erifiers]: print package verifier info");
15460                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15461                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15462                pw.println("    version: print database version info");
15463                pw.println("    write: write current settings now");
15464                pw.println("    installs: details about install sessions");
15465                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15466                pw.println("    <package.name>: info about given package");
15467                return;
15468            } else if ("--checkin".equals(opt)) {
15469                checkin = true;
15470            } else if ("-f".equals(opt)) {
15471                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15472            } else {
15473                pw.println("Unknown argument: " + opt + "; use -h for help");
15474            }
15475        }
15476
15477        // Is the caller requesting to dump a particular piece of data?
15478        if (opti < args.length) {
15479            String cmd = args[opti];
15480            opti++;
15481            // Is this a package name?
15482            if ("android".equals(cmd) || cmd.contains(".")) {
15483                packageName = cmd;
15484                // When dumping a single package, we always dump all of its
15485                // filter information since the amount of data will be reasonable.
15486                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15487            } else if ("check-permission".equals(cmd)) {
15488                if (opti >= args.length) {
15489                    pw.println("Error: check-permission missing permission argument");
15490                    return;
15491                }
15492                String perm = args[opti];
15493                opti++;
15494                if (opti >= args.length) {
15495                    pw.println("Error: check-permission missing package argument");
15496                    return;
15497                }
15498                String pkg = args[opti];
15499                opti++;
15500                int user = UserHandle.getUserId(Binder.getCallingUid());
15501                if (opti < args.length) {
15502                    try {
15503                        user = Integer.parseInt(args[opti]);
15504                    } catch (NumberFormatException e) {
15505                        pw.println("Error: check-permission user argument is not a number: "
15506                                + args[opti]);
15507                        return;
15508                    }
15509                }
15510                pw.println(checkPermission(perm, pkg, user));
15511                return;
15512            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15513                dumpState.setDump(DumpState.DUMP_LIBS);
15514            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15515                dumpState.setDump(DumpState.DUMP_FEATURES);
15516            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15517                if (opti >= args.length) {
15518                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15519                            | DumpState.DUMP_SERVICE_RESOLVERS
15520                            | DumpState.DUMP_RECEIVER_RESOLVERS
15521                            | DumpState.DUMP_CONTENT_RESOLVERS);
15522                } else {
15523                    while (opti < args.length) {
15524                        String name = args[opti];
15525                        if ("a".equals(name) || "activity".equals(name)) {
15526                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15527                        } else if ("s".equals(name) || "service".equals(name)) {
15528                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15529                        } else if ("r".equals(name) || "receiver".equals(name)) {
15530                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15531                        } else if ("c".equals(name) || "content".equals(name)) {
15532                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15533                        } else {
15534                            pw.println("Error: unknown resolver table type: " + name);
15535                            return;
15536                        }
15537                        opti++;
15538                    }
15539                }
15540            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15541                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15542            } else if ("permission".equals(cmd)) {
15543                if (opti >= args.length) {
15544                    pw.println("Error: permission requires permission name");
15545                    return;
15546                }
15547                permissionNames = new ArraySet<>();
15548                while (opti < args.length) {
15549                    permissionNames.add(args[opti]);
15550                    opti++;
15551                }
15552                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15553                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15554            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15555                dumpState.setDump(DumpState.DUMP_PREFERRED);
15556            } else if ("preferred-xml".equals(cmd)) {
15557                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15558                if (opti < args.length && "--full".equals(args[opti])) {
15559                    fullPreferred = true;
15560                    opti++;
15561                }
15562            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15563                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15564            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15565                dumpState.setDump(DumpState.DUMP_PACKAGES);
15566            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15567                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15568            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15569                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15570            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15571                dumpState.setDump(DumpState.DUMP_MESSAGES);
15572            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15573                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15574            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15575                    || "intent-filter-verifiers".equals(cmd)) {
15576                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15577            } else if ("version".equals(cmd)) {
15578                dumpState.setDump(DumpState.DUMP_VERSION);
15579            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15580                dumpState.setDump(DumpState.DUMP_KEYSETS);
15581            } else if ("installs".equals(cmd)) {
15582                dumpState.setDump(DumpState.DUMP_INSTALLS);
15583            } else if ("write".equals(cmd)) {
15584                synchronized (mPackages) {
15585                    mSettings.writeLPr();
15586                    pw.println("Settings written.");
15587                    return;
15588                }
15589            }
15590        }
15591
15592        if (checkin) {
15593            pw.println("vers,1");
15594        }
15595
15596        // reader
15597        synchronized (mPackages) {
15598            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15599                if (!checkin) {
15600                    if (dumpState.onTitlePrinted())
15601                        pw.println();
15602                    pw.println("Database versions:");
15603                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15604                }
15605            }
15606
15607            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15608                if (!checkin) {
15609                    if (dumpState.onTitlePrinted())
15610                        pw.println();
15611                    pw.println("Verifiers:");
15612                    pw.print("  Required: ");
15613                    pw.print(mRequiredVerifierPackage);
15614                    pw.print(" (uid=");
15615                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15616                            UserHandle.USER_SYSTEM));
15617                    pw.println(")");
15618                } else if (mRequiredVerifierPackage != null) {
15619                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15620                    pw.print(",");
15621                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15622                            UserHandle.USER_SYSTEM));
15623                }
15624            }
15625
15626            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15627                    packageName == null) {
15628                if (mIntentFilterVerifierComponent != null) {
15629                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15630                    if (!checkin) {
15631                        if (dumpState.onTitlePrinted())
15632                            pw.println();
15633                        pw.println("Intent Filter Verifier:");
15634                        pw.print("  Using: ");
15635                        pw.print(verifierPackageName);
15636                        pw.print(" (uid=");
15637                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15638                                UserHandle.USER_SYSTEM));
15639                        pw.println(")");
15640                    } else if (verifierPackageName != null) {
15641                        pw.print("ifv,"); pw.print(verifierPackageName);
15642                        pw.print(",");
15643                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15644                                UserHandle.USER_SYSTEM));
15645                    }
15646                } else {
15647                    pw.println();
15648                    pw.println("No Intent Filter Verifier available!");
15649                }
15650            }
15651
15652            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15653                boolean printedHeader = false;
15654                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15655                while (it.hasNext()) {
15656                    String name = it.next();
15657                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15658                    if (!checkin) {
15659                        if (!printedHeader) {
15660                            if (dumpState.onTitlePrinted())
15661                                pw.println();
15662                            pw.println("Libraries:");
15663                            printedHeader = true;
15664                        }
15665                        pw.print("  ");
15666                    } else {
15667                        pw.print("lib,");
15668                    }
15669                    pw.print(name);
15670                    if (!checkin) {
15671                        pw.print(" -> ");
15672                    }
15673                    if (ent.path != null) {
15674                        if (!checkin) {
15675                            pw.print("(jar) ");
15676                            pw.print(ent.path);
15677                        } else {
15678                            pw.print(",jar,");
15679                            pw.print(ent.path);
15680                        }
15681                    } else {
15682                        if (!checkin) {
15683                            pw.print("(apk) ");
15684                            pw.print(ent.apk);
15685                        } else {
15686                            pw.print(",apk,");
15687                            pw.print(ent.apk);
15688                        }
15689                    }
15690                    pw.println();
15691                }
15692            }
15693
15694            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15695                if (dumpState.onTitlePrinted())
15696                    pw.println();
15697                if (!checkin) {
15698                    pw.println("Features:");
15699                }
15700                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15701                while (it.hasNext()) {
15702                    String name = it.next();
15703                    if (!checkin) {
15704                        pw.print("  ");
15705                    } else {
15706                        pw.print("feat,");
15707                    }
15708                    pw.println(name);
15709                }
15710            }
15711
15712            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15713                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15714                        : "Activity Resolver Table:", "  ", packageName,
15715                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15716                    dumpState.setTitlePrinted(true);
15717                }
15718            }
15719            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15720                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15721                        : "Receiver Resolver Table:", "  ", packageName,
15722                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15723                    dumpState.setTitlePrinted(true);
15724                }
15725            }
15726            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15727                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15728                        : "Service Resolver Table:", "  ", packageName,
15729                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15730                    dumpState.setTitlePrinted(true);
15731                }
15732            }
15733            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15734                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15735                        : "Provider Resolver Table:", "  ", packageName,
15736                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15737                    dumpState.setTitlePrinted(true);
15738                }
15739            }
15740
15741            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15742                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15743                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15744                    int user = mSettings.mPreferredActivities.keyAt(i);
15745                    if (pir.dump(pw,
15746                            dumpState.getTitlePrinted()
15747                                ? "\nPreferred Activities User " + user + ":"
15748                                : "Preferred Activities User " + user + ":", "  ",
15749                            packageName, true, false)) {
15750                        dumpState.setTitlePrinted(true);
15751                    }
15752                }
15753            }
15754
15755            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15756                pw.flush();
15757                FileOutputStream fout = new FileOutputStream(fd);
15758                BufferedOutputStream str = new BufferedOutputStream(fout);
15759                XmlSerializer serializer = new FastXmlSerializer();
15760                try {
15761                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15762                    serializer.startDocument(null, true);
15763                    serializer.setFeature(
15764                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15765                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15766                    serializer.endDocument();
15767                    serializer.flush();
15768                } catch (IllegalArgumentException e) {
15769                    pw.println("Failed writing: " + e);
15770                } catch (IllegalStateException e) {
15771                    pw.println("Failed writing: " + e);
15772                } catch (IOException e) {
15773                    pw.println("Failed writing: " + e);
15774                }
15775            }
15776
15777            if (!checkin
15778                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15779                    && packageName == null) {
15780                pw.println();
15781                int count = mSettings.mPackages.size();
15782                if (count == 0) {
15783                    pw.println("No applications!");
15784                    pw.println();
15785                } else {
15786                    final String prefix = "  ";
15787                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15788                    if (allPackageSettings.size() == 0) {
15789                        pw.println("No domain preferred apps!");
15790                        pw.println();
15791                    } else {
15792                        pw.println("App verification status:");
15793                        pw.println();
15794                        count = 0;
15795                        for (PackageSetting ps : allPackageSettings) {
15796                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15797                            if (ivi == null || ivi.getPackageName() == null) continue;
15798                            pw.println(prefix + "Package: " + ivi.getPackageName());
15799                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15800                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15801                            pw.println();
15802                            count++;
15803                        }
15804                        if (count == 0) {
15805                            pw.println(prefix + "No app verification established.");
15806                            pw.println();
15807                        }
15808                        for (int userId : sUserManager.getUserIds()) {
15809                            pw.println("App linkages for user " + userId + ":");
15810                            pw.println();
15811                            count = 0;
15812                            for (PackageSetting ps : allPackageSettings) {
15813                                final long status = ps.getDomainVerificationStatusForUser(userId);
15814                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15815                                    continue;
15816                                }
15817                                pw.println(prefix + "Package: " + ps.name);
15818                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15819                                String statusStr = IntentFilterVerificationInfo.
15820                                        getStatusStringFromValue(status);
15821                                pw.println(prefix + "Status:  " + statusStr);
15822                                pw.println();
15823                                count++;
15824                            }
15825                            if (count == 0) {
15826                                pw.println(prefix + "No configured app linkages.");
15827                                pw.println();
15828                            }
15829                        }
15830                    }
15831                }
15832            }
15833
15834            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15835                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15836                if (packageName == null && permissionNames == null) {
15837                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15838                        if (iperm == 0) {
15839                            if (dumpState.onTitlePrinted())
15840                                pw.println();
15841                            pw.println("AppOp Permissions:");
15842                        }
15843                        pw.print("  AppOp Permission ");
15844                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15845                        pw.println(":");
15846                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15847                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15848                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15849                        }
15850                    }
15851                }
15852            }
15853
15854            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15855                boolean printedSomething = false;
15856                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15857                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15858                        continue;
15859                    }
15860                    if (!printedSomething) {
15861                        if (dumpState.onTitlePrinted())
15862                            pw.println();
15863                        pw.println("Registered ContentProviders:");
15864                        printedSomething = true;
15865                    }
15866                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15867                    pw.print("    "); pw.println(p.toString());
15868                }
15869                printedSomething = false;
15870                for (Map.Entry<String, PackageParser.Provider> entry :
15871                        mProvidersByAuthority.entrySet()) {
15872                    PackageParser.Provider p = entry.getValue();
15873                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15874                        continue;
15875                    }
15876                    if (!printedSomething) {
15877                        if (dumpState.onTitlePrinted())
15878                            pw.println();
15879                        pw.println("ContentProvider Authorities:");
15880                        printedSomething = true;
15881                    }
15882                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15883                    pw.print("    "); pw.println(p.toString());
15884                    if (p.info != null && p.info.applicationInfo != null) {
15885                        final String appInfo = p.info.applicationInfo.toString();
15886                        pw.print("      applicationInfo="); pw.println(appInfo);
15887                    }
15888                }
15889            }
15890
15891            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15892                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15893            }
15894
15895            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15896                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15897            }
15898
15899            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15900                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15901            }
15902
15903            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15904                // XXX should handle packageName != null by dumping only install data that
15905                // the given package is involved with.
15906                if (dumpState.onTitlePrinted()) pw.println();
15907                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15908            }
15909
15910            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15911                if (dumpState.onTitlePrinted()) pw.println();
15912                mSettings.dumpReadMessagesLPr(pw, dumpState);
15913
15914                pw.println();
15915                pw.println("Package warning messages:");
15916                BufferedReader in = null;
15917                String line = null;
15918                try {
15919                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15920                    while ((line = in.readLine()) != null) {
15921                        if (line.contains("ignored: updated version")) continue;
15922                        pw.println(line);
15923                    }
15924                } catch (IOException ignored) {
15925                } finally {
15926                    IoUtils.closeQuietly(in);
15927                }
15928            }
15929
15930            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15931                BufferedReader in = null;
15932                String line = null;
15933                try {
15934                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15935                    while ((line = in.readLine()) != null) {
15936                        if (line.contains("ignored: updated version")) continue;
15937                        pw.print("msg,");
15938                        pw.println(line);
15939                    }
15940                } catch (IOException ignored) {
15941                } finally {
15942                    IoUtils.closeQuietly(in);
15943                }
15944            }
15945        }
15946    }
15947
15948    private String dumpDomainString(String packageName) {
15949        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15950        List<IntentFilter> filters = getAllIntentFilters(packageName);
15951
15952        ArraySet<String> result = new ArraySet<>();
15953        if (iviList.size() > 0) {
15954            for (IntentFilterVerificationInfo ivi : iviList) {
15955                for (String host : ivi.getDomains()) {
15956                    result.add(host);
15957                }
15958            }
15959        }
15960        if (filters != null && filters.size() > 0) {
15961            for (IntentFilter filter : filters) {
15962                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15963                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15964                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15965                    result.addAll(filter.getHostsList());
15966                }
15967            }
15968        }
15969
15970        StringBuilder sb = new StringBuilder(result.size() * 16);
15971        for (String domain : result) {
15972            if (sb.length() > 0) sb.append(" ");
15973            sb.append(domain);
15974        }
15975        return sb.toString();
15976    }
15977
15978    // ------- apps on sdcard specific code -------
15979    static final boolean DEBUG_SD_INSTALL = false;
15980
15981    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15982
15983    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15984
15985    private boolean mMediaMounted = false;
15986
15987    static String getEncryptKey() {
15988        try {
15989            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15990                    SD_ENCRYPTION_KEYSTORE_NAME);
15991            if (sdEncKey == null) {
15992                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15993                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15994                if (sdEncKey == null) {
15995                    Slog.e(TAG, "Failed to create encryption keys");
15996                    return null;
15997                }
15998            }
15999            return sdEncKey;
16000        } catch (NoSuchAlgorithmException nsae) {
16001            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16002            return null;
16003        } catch (IOException ioe) {
16004            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16005            return null;
16006        }
16007    }
16008
16009    /*
16010     * Update media status on PackageManager.
16011     */
16012    @Override
16013    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16014        int callingUid = Binder.getCallingUid();
16015        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16016            throw new SecurityException("Media status can only be updated by the system");
16017        }
16018        // reader; this apparently protects mMediaMounted, but should probably
16019        // be a different lock in that case.
16020        synchronized (mPackages) {
16021            Log.i(TAG, "Updating external media status from "
16022                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16023                    + (mediaStatus ? "mounted" : "unmounted"));
16024            if (DEBUG_SD_INSTALL)
16025                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16026                        + ", mMediaMounted=" + mMediaMounted);
16027            if (mediaStatus == mMediaMounted) {
16028                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16029                        : 0, -1);
16030                mHandler.sendMessage(msg);
16031                return;
16032            }
16033            mMediaMounted = mediaStatus;
16034        }
16035        // Queue up an async operation since the package installation may take a
16036        // little while.
16037        mHandler.post(new Runnable() {
16038            public void run() {
16039                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16040            }
16041        });
16042    }
16043
16044    /**
16045     * Called by MountService when the initial ASECs to scan are available.
16046     * Should block until all the ASEC containers are finished being scanned.
16047     */
16048    public void scanAvailableAsecs() {
16049        updateExternalMediaStatusInner(true, false, false);
16050    }
16051
16052    /*
16053     * Collect information of applications on external media, map them against
16054     * existing containers and update information based on current mount status.
16055     * Please note that we always have to report status if reportStatus has been
16056     * set to true especially when unloading packages.
16057     */
16058    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16059            boolean externalStorage) {
16060        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16061        int[] uidArr = EmptyArray.INT;
16062
16063        final String[] list = PackageHelper.getSecureContainerList();
16064        if (ArrayUtils.isEmpty(list)) {
16065            Log.i(TAG, "No secure containers found");
16066        } else {
16067            // Process list of secure containers and categorize them
16068            // as active or stale based on their package internal state.
16069
16070            // reader
16071            synchronized (mPackages) {
16072                for (String cid : list) {
16073                    // Leave stages untouched for now; installer service owns them
16074                    if (PackageInstallerService.isStageName(cid)) continue;
16075
16076                    if (DEBUG_SD_INSTALL)
16077                        Log.i(TAG, "Processing container " + cid);
16078                    String pkgName = getAsecPackageName(cid);
16079                    if (pkgName == null) {
16080                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16081                        continue;
16082                    }
16083                    if (DEBUG_SD_INSTALL)
16084                        Log.i(TAG, "Looking for pkg : " + pkgName);
16085
16086                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16087                    if (ps == null) {
16088                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16089                        continue;
16090                    }
16091
16092                    /*
16093                     * Skip packages that are not external if we're unmounting
16094                     * external storage.
16095                     */
16096                    if (externalStorage && !isMounted && !isExternal(ps)) {
16097                        continue;
16098                    }
16099
16100                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16101                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16102                    // The package status is changed only if the code path
16103                    // matches between settings and the container id.
16104                    if (ps.codePathString != null
16105                            && ps.codePathString.startsWith(args.getCodePath())) {
16106                        if (DEBUG_SD_INSTALL) {
16107                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16108                                    + " at code path: " + ps.codePathString);
16109                        }
16110
16111                        // We do have a valid package installed on sdcard
16112                        processCids.put(args, ps.codePathString);
16113                        final int uid = ps.appId;
16114                        if (uid != -1) {
16115                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16116                        }
16117                    } else {
16118                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16119                                + ps.codePathString);
16120                    }
16121                }
16122            }
16123
16124            Arrays.sort(uidArr);
16125        }
16126
16127        // Process packages with valid entries.
16128        if (isMounted) {
16129            if (DEBUG_SD_INSTALL)
16130                Log.i(TAG, "Loading packages");
16131            loadMediaPackages(processCids, uidArr, externalStorage);
16132            startCleaningPackages();
16133            mInstallerService.onSecureContainersAvailable();
16134        } else {
16135            if (DEBUG_SD_INSTALL)
16136                Log.i(TAG, "Unloading packages");
16137            unloadMediaPackages(processCids, uidArr, reportStatus);
16138        }
16139    }
16140
16141    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16142            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16143        final int size = infos.size();
16144        final String[] packageNames = new String[size];
16145        final int[] packageUids = new int[size];
16146        for (int i = 0; i < size; i++) {
16147            final ApplicationInfo info = infos.get(i);
16148            packageNames[i] = info.packageName;
16149            packageUids[i] = info.uid;
16150        }
16151        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16152                finishedReceiver);
16153    }
16154
16155    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16156            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16157        sendResourcesChangedBroadcast(mediaStatus, replacing,
16158                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16159    }
16160
16161    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16162            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16163        int size = pkgList.length;
16164        if (size > 0) {
16165            // Send broadcasts here
16166            Bundle extras = new Bundle();
16167            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16168            if (uidArr != null) {
16169                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16170            }
16171            if (replacing) {
16172                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16173            }
16174            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16175                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16176            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16177        }
16178    }
16179
16180   /*
16181     * Look at potentially valid container ids from processCids If package
16182     * information doesn't match the one on record or package scanning fails,
16183     * the cid is added to list of removeCids. We currently don't delete stale
16184     * containers.
16185     */
16186    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16187            boolean externalStorage) {
16188        ArrayList<String> pkgList = new ArrayList<String>();
16189        Set<AsecInstallArgs> keys = processCids.keySet();
16190
16191        for (AsecInstallArgs args : keys) {
16192            String codePath = processCids.get(args);
16193            if (DEBUG_SD_INSTALL)
16194                Log.i(TAG, "Loading container : " + args.cid);
16195            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16196            try {
16197                // Make sure there are no container errors first.
16198                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16199                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16200                            + " when installing from sdcard");
16201                    continue;
16202                }
16203                // Check code path here.
16204                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16205                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16206                            + " does not match one in settings " + codePath);
16207                    continue;
16208                }
16209                // Parse package
16210                int parseFlags = mDefParseFlags;
16211                if (args.isExternalAsec()) {
16212                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16213                }
16214                if (args.isFwdLocked()) {
16215                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16216                }
16217
16218                synchronized (mInstallLock) {
16219                    PackageParser.Package pkg = null;
16220                    try {
16221                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16222                    } catch (PackageManagerException e) {
16223                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16224                    }
16225                    // Scan the package
16226                    if (pkg != null) {
16227                        /*
16228                         * TODO why is the lock being held? doPostInstall is
16229                         * called in other places without the lock. This needs
16230                         * to be straightened out.
16231                         */
16232                        // writer
16233                        synchronized (mPackages) {
16234                            retCode = PackageManager.INSTALL_SUCCEEDED;
16235                            pkgList.add(pkg.packageName);
16236                            // Post process args
16237                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16238                                    pkg.applicationInfo.uid);
16239                        }
16240                    } else {
16241                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16242                    }
16243                }
16244
16245            } finally {
16246                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16247                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16248                }
16249            }
16250        }
16251        // writer
16252        synchronized (mPackages) {
16253            // If the platform SDK has changed since the last time we booted,
16254            // we need to re-grant app permission to catch any new ones that
16255            // appear. This is really a hack, and means that apps can in some
16256            // cases get permissions that the user didn't initially explicitly
16257            // allow... it would be nice to have some better way to handle
16258            // this situation.
16259            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16260                    : mSettings.getInternalVersion();
16261            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16262                    : StorageManager.UUID_PRIVATE_INTERNAL;
16263
16264            int updateFlags = UPDATE_PERMISSIONS_ALL;
16265            if (ver.sdkVersion != mSdkVersion) {
16266                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16267                        + mSdkVersion + "; regranting permissions for external");
16268                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16269            }
16270            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16271
16272            // Yay, everything is now upgraded
16273            ver.forceCurrent();
16274
16275            // can downgrade to reader
16276            // Persist settings
16277            mSettings.writeLPr();
16278        }
16279        // Send a broadcast to let everyone know we are done processing
16280        if (pkgList.size() > 0) {
16281            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16282        }
16283    }
16284
16285   /*
16286     * Utility method to unload a list of specified containers
16287     */
16288    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16289        // Just unmount all valid containers.
16290        for (AsecInstallArgs arg : cidArgs) {
16291            synchronized (mInstallLock) {
16292                arg.doPostDeleteLI(false);
16293           }
16294       }
16295   }
16296
16297    /*
16298     * Unload packages mounted on external media. This involves deleting package
16299     * data from internal structures, sending broadcasts about diabled packages,
16300     * gc'ing to free up references, unmounting all secure containers
16301     * corresponding to packages on external media, and posting a
16302     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16303     * that we always have to post this message if status has been requested no
16304     * matter what.
16305     */
16306    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16307            final boolean reportStatus) {
16308        if (DEBUG_SD_INSTALL)
16309            Log.i(TAG, "unloading media packages");
16310        ArrayList<String> pkgList = new ArrayList<String>();
16311        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16312        final Set<AsecInstallArgs> keys = processCids.keySet();
16313        for (AsecInstallArgs args : keys) {
16314            String pkgName = args.getPackageName();
16315            if (DEBUG_SD_INSTALL)
16316                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16317            // Delete package internally
16318            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16319            synchronized (mInstallLock) {
16320                boolean res = deletePackageLI(pkgName, null, false, null, null,
16321                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16322                if (res) {
16323                    pkgList.add(pkgName);
16324                } else {
16325                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16326                    failedList.add(args);
16327                }
16328            }
16329        }
16330
16331        // reader
16332        synchronized (mPackages) {
16333            // We didn't update the settings after removing each package;
16334            // write them now for all packages.
16335            mSettings.writeLPr();
16336        }
16337
16338        // We have to absolutely send UPDATED_MEDIA_STATUS only
16339        // after confirming that all the receivers processed the ordered
16340        // broadcast when packages get disabled, force a gc to clean things up.
16341        // and unload all the containers.
16342        if (pkgList.size() > 0) {
16343            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16344                    new IIntentReceiver.Stub() {
16345                public void performReceive(Intent intent, int resultCode, String data,
16346                        Bundle extras, boolean ordered, boolean sticky,
16347                        int sendingUser) throws RemoteException {
16348                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16349                            reportStatus ? 1 : 0, 1, keys);
16350                    mHandler.sendMessage(msg);
16351                }
16352            });
16353        } else {
16354            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16355                    keys);
16356            mHandler.sendMessage(msg);
16357        }
16358    }
16359
16360    private void loadPrivatePackages(final VolumeInfo vol) {
16361        mHandler.post(new Runnable() {
16362            @Override
16363            public void run() {
16364                loadPrivatePackagesInner(vol);
16365            }
16366        });
16367    }
16368
16369    private void loadPrivatePackagesInner(VolumeInfo vol) {
16370        final String volumeUuid = vol.fsUuid;
16371        if (TextUtils.isEmpty(volumeUuid)) {
16372            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
16373            return;
16374        }
16375
16376        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16377        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16378
16379        final VersionInfo ver;
16380        final List<PackageSetting> packages;
16381        synchronized (mPackages) {
16382            ver = mSettings.findOrCreateVersion(volumeUuid);
16383            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16384        }
16385
16386        // TODO: introduce a new concept similar to "frozen" to prevent these
16387        // apps from being launched until after data has been fully reconciled
16388        for (PackageSetting ps : packages) {
16389            synchronized (mInstallLock) {
16390                final PackageParser.Package pkg;
16391                try {
16392                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16393                    loaded.add(pkg.applicationInfo);
16394
16395                } catch (PackageManagerException e) {
16396                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16397                }
16398
16399                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16400                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16401                }
16402            }
16403        }
16404
16405        // Reconcile app data for all started/unlocked users
16406        final UserManager um = mContext.getSystemService(UserManager.class);
16407        for (UserInfo user : um.getUsers()) {
16408            if (um.isUserUnlocked(user.id)) {
16409                reconcileAppsData(volumeUuid, user.id,
16410                        Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE);
16411            } else if (um.isUserRunning(user.id)) {
16412                reconcileAppsData(volumeUuid, user.id, Installer.FLAG_DE_STORAGE);
16413            } else {
16414                continue;
16415            }
16416        }
16417
16418        synchronized (mPackages) {
16419            int updateFlags = UPDATE_PERMISSIONS_ALL;
16420            if (ver.sdkVersion != mSdkVersion) {
16421                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16422                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
16423                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16424            }
16425            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16426
16427            // Yay, everything is now upgraded
16428            ver.forceCurrent();
16429
16430            mSettings.writeLPr();
16431        }
16432
16433        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16434        sendResourcesChangedBroadcast(true, false, loaded, null);
16435    }
16436
16437    private void unloadPrivatePackages(final VolumeInfo vol) {
16438        mHandler.post(new Runnable() {
16439            @Override
16440            public void run() {
16441                unloadPrivatePackagesInner(vol);
16442            }
16443        });
16444    }
16445
16446    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16447        final String volumeUuid = vol.fsUuid;
16448        if (TextUtils.isEmpty(volumeUuid)) {
16449            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
16450            return;
16451        }
16452
16453        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16454        synchronized (mInstallLock) {
16455        synchronized (mPackages) {
16456            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
16457            for (PackageSetting ps : packages) {
16458                if (ps.pkg == null) continue;
16459
16460                final ApplicationInfo info = ps.pkg.applicationInfo;
16461                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16462                if (deletePackageLI(ps.name, null, false, null, null,
16463                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16464                    unloaded.add(info);
16465                } else {
16466                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16467                }
16468            }
16469
16470            mSettings.writeLPr();
16471        }
16472        }
16473
16474        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16475        sendResourcesChangedBroadcast(false, false, unloaded, null);
16476    }
16477
16478    /**
16479     * Examine all users present on given mounted volume, and destroy data
16480     * belonging to users that are no longer valid, or whose user ID has been
16481     * recycled.
16482     */
16483    private void reconcileUsers(String volumeUuid) {
16484        final File[] files = FileUtils
16485                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16486        for (File file : files) {
16487            if (!file.isDirectory()) continue;
16488
16489            final int userId;
16490            final UserInfo info;
16491            try {
16492                userId = Integer.parseInt(file.getName());
16493                info = sUserManager.getUserInfo(userId);
16494            } catch (NumberFormatException e) {
16495                Slog.w(TAG, "Invalid user directory " + file);
16496                continue;
16497            }
16498
16499            boolean destroyUser = false;
16500            if (info == null) {
16501                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16502                        + " because no matching user was found");
16503                destroyUser = true;
16504            } else {
16505                try {
16506                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16507                } catch (IOException e) {
16508                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16509                            + " because we failed to enforce serial number: " + e);
16510                    destroyUser = true;
16511                }
16512            }
16513
16514            if (destroyUser) {
16515                synchronized (mInstallLock) {
16516                    try {
16517                        mInstaller.removeUserDataDirs(volumeUuid, userId);
16518                    } catch (InstallerException e) {
16519                        Slog.w(TAG, "Failed to clean up user dirs", e);
16520                    }
16521                }
16522            }
16523        }
16524
16525        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16526        final UserManager um = mContext.getSystemService(UserManager.class);
16527        for (UserInfo user : um.getUsers()) {
16528            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16529            if (userDir.exists()) continue;
16530
16531            try {
16532                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16533                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16534            } catch (IOException e) {
16535                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16536            }
16537        }
16538    }
16539
16540    private void assertPackageKnown(String volumeUuid, String packageName)
16541            throws PackageManagerException {
16542        synchronized (mPackages) {
16543            final PackageSetting ps = mSettings.mPackages.get(packageName);
16544            if (ps == null) {
16545                throw new PackageManagerException("Package " + packageName + " is unknown");
16546            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16547                throw new PackageManagerException(
16548                        "Package " + packageName + " found on unknown volume " + volumeUuid
16549                                + "; expected volume " + ps.volumeUuid);
16550            }
16551        }
16552    }
16553
16554    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
16555            throws PackageManagerException {
16556        synchronized (mPackages) {
16557            final PackageSetting ps = mSettings.mPackages.get(packageName);
16558            if (ps == null) {
16559                throw new PackageManagerException("Package " + packageName + " is unknown");
16560            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16561                throw new PackageManagerException(
16562                        "Package " + packageName + " found on unknown volume " + volumeUuid
16563                                + "; expected volume " + ps.volumeUuid);
16564            } else if (!ps.getInstalled(userId)) {
16565                throw new PackageManagerException(
16566                        "Package " + packageName + " not installed for user " + userId);
16567            }
16568        }
16569    }
16570
16571    /**
16572     * Examine all apps present on given mounted volume, and destroy apps that
16573     * aren't expected, either due to uninstallation or reinstallation on
16574     * another volume.
16575     */
16576    private void reconcileApps(String volumeUuid) {
16577        final File[] files = FileUtils
16578                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16579        for (File file : files) {
16580            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16581                    && !PackageInstallerService.isStageName(file.getName());
16582            if (!isPackage) {
16583                // Ignore entries which are not packages
16584                continue;
16585            }
16586
16587            try {
16588                final PackageLite pkg = PackageParser.parsePackageLite(file,
16589                        PackageParser.PARSE_MUST_BE_APK);
16590                assertPackageKnown(volumeUuid, pkg.packageName);
16591
16592            } catch (PackageParserException | PackageManagerException e) {
16593                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16594                synchronized (mInstallLock) {
16595                    removeCodePathLI(file);
16596                }
16597            }
16598        }
16599    }
16600
16601    /**
16602     * Reconcile all app data for the given user.
16603     * <p>
16604     * Verifies that directories exist and that ownership and labeling is
16605     * correct for all installed apps on all mounted volumes.
16606     */
16607    void reconcileAppsData(int userId, @StorageFlags int flags) {
16608        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16609        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16610            final String volumeUuid = vol.getFsUuid();
16611            reconcileAppsData(volumeUuid, userId, flags);
16612        }
16613    }
16614
16615    /**
16616     * Reconcile all app data on given mounted volume.
16617     * <p>
16618     * Destroys app data that isn't expected, either due to uninstallation or
16619     * reinstallation on another volume.
16620     * <p>
16621     * Verifies that directories exist and that ownership and labeling is
16622     * correct for all installed apps.
16623     */
16624    private void reconcileAppsData(String volumeUuid, int userId, @StorageFlags int flags) {
16625        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
16626                + Integer.toHexString(flags));
16627
16628        final File ceDir = Environment.getDataUserCredentialEncryptedDirectory(volumeUuid, userId);
16629        final File deDir = Environment.getDataUserDeviceEncryptedDirectory(volumeUuid, userId);
16630
16631        boolean restoreconNeeded = false;
16632
16633        // First look for stale data that doesn't belong, and check if things
16634        // have changed since we did our last restorecon
16635        if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
16636            if (!isUserKeyUnlocked(userId)) {
16637                throw new RuntimeException(
16638                        "Yikes, someone asked us to reconcile CE storage while " + userId
16639                                + " was still locked; this would have caused massive data loss!");
16640            }
16641
16642            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
16643
16644            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
16645            for (File file : files) {
16646                final String packageName = file.getName();
16647                try {
16648                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
16649                } catch (PackageManagerException e) {
16650                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16651                    synchronized (mInstallLock) {
16652                        destroyAppDataLI(volumeUuid, packageName, userId,
16653                                Installer.FLAG_CE_STORAGE);
16654                    }
16655                }
16656            }
16657        }
16658        if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
16659            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
16660
16661            final File[] files = FileUtils.listFilesOrEmpty(deDir);
16662            for (File file : files) {
16663                final String packageName = file.getName();
16664                try {
16665                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
16666                } catch (PackageManagerException e) {
16667                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
16668                    synchronized (mInstallLock) {
16669                        destroyAppDataLI(volumeUuid, packageName, userId,
16670                                Installer.FLAG_DE_STORAGE);
16671                    }
16672                }
16673            }
16674        }
16675
16676        // Ensure that data directories are ready to roll for all packages
16677        // installed for this volume and user
16678        final List<PackageSetting> packages;
16679        synchronized (mPackages) {
16680            packages = mSettings.getVolumePackagesLPr(volumeUuid);
16681        }
16682        int preparedCount = 0;
16683        for (PackageSetting ps : packages) {
16684            final String packageName = ps.name;
16685            if (ps.pkg == null) {
16686                Slog.w(TAG, "Odd, missing scanned package " + packageName);
16687                // TODO: might be due to legacy ASEC apps; we should circle back
16688                // and reconcile again once they're scanned
16689                continue;
16690            }
16691
16692            if (ps.getInstalled(userId)) {
16693                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
16694                preparedCount++;
16695            }
16696        }
16697
16698        if (restoreconNeeded) {
16699            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
16700                SELinuxMMAC.setRestoreconDone(ceDir);
16701            }
16702            if ((flags & Installer.FLAG_DE_STORAGE) != 0) {
16703                SELinuxMMAC.setRestoreconDone(deDir);
16704            }
16705        }
16706
16707        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
16708                + " packages; restoreconNeeded was " + restoreconNeeded);
16709    }
16710
16711    /**
16712     * Prepare app data for the given app just after it was installed or
16713     * upgraded. This method carefully only touches users that it's installed
16714     * for, and it forces a restorecon to handle any seinfo changes.
16715     * <p>
16716     * Verifies that directories exist and that ownership and labeling is
16717     * correct for all installed apps. If there is an ownership mismatch, it
16718     * will try recovering system apps by wiping data; third-party app data is
16719     * left intact.
16720     */
16721    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
16722        final PackageSetting ps;
16723        synchronized (mPackages) {
16724            ps = mSettings.mPackages.get(pkg.packageName);
16725        }
16726
16727        final UserManager um = mContext.getSystemService(UserManager.class);
16728        for (UserInfo user : um.getUsers()) {
16729            final int flags;
16730            if (um.isUserUnlocked(user.id)) {
16731                flags = Installer.FLAG_DE_STORAGE | Installer.FLAG_CE_STORAGE;
16732            } else if (um.isUserRunning(user.id)) {
16733                flags = Installer.FLAG_DE_STORAGE;
16734            } else {
16735                continue;
16736            }
16737
16738            if (ps.getInstalled(user.id)) {
16739                // Whenever an app changes, force a restorecon of its data
16740                // TODO: when user data is locked, mark that we're still dirty
16741                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
16742            }
16743        }
16744    }
16745
16746    /**
16747     * Prepare app data for the given app.
16748     * <p>
16749     * Verifies that directories exist and that ownership and labeling is
16750     * correct for all installed apps. If there is an ownership mismatch, this
16751     * will try recovering system apps by wiping data; third-party app data is
16752     * left intact.
16753     */
16754    private void prepareAppData(String volumeUuid, int userId, @StorageFlags int flags,
16755            PackageParser.Package pkg, boolean restoreconNeeded) {
16756        if (DEBUG_APP_DATA) {
16757            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
16758                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
16759        }
16760
16761        final String packageName = pkg.packageName;
16762        final ApplicationInfo app = pkg.applicationInfo;
16763        final int appId = UserHandle.getAppId(app.uid);
16764
16765        Preconditions.checkNotNull(app.seinfo);
16766
16767        synchronized (mInstallLock) {
16768            try {
16769                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
16770                        appId, app.seinfo);
16771            } catch (InstallerException e) {
16772                if (app.isSystemApp()) {
16773                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
16774                            + ", but trying to recover: " + e);
16775                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
16776                    try {
16777                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
16778                                appId, app.seinfo);
16779                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
16780                    } catch (InstallerException e2) {
16781                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
16782                    }
16783                } else {
16784                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
16785                }
16786            }
16787
16788            if (restoreconNeeded) {
16789                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
16790            }
16791
16792            if ((flags & Installer.FLAG_CE_STORAGE) != 0) {
16793                // Create a native library symlink only if we have native libraries
16794                // and if the native libraries are 32 bit libraries. We do not provide
16795                // this symlink for 64 bit libraries.
16796                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
16797                    final String nativeLibPath = app.nativeLibraryDir;
16798                    try {
16799                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
16800                                nativeLibPath, userId);
16801                    } catch (InstallerException e) {
16802                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
16803                    }
16804                }
16805            }
16806        }
16807    }
16808
16809    private void unfreezePackage(String packageName) {
16810        synchronized (mPackages) {
16811            final PackageSetting ps = mSettings.mPackages.get(packageName);
16812            if (ps != null) {
16813                ps.frozen = false;
16814            }
16815        }
16816    }
16817
16818    @Override
16819    public int movePackage(final String packageName, final String volumeUuid) {
16820        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16821
16822        final int moveId = mNextMoveId.getAndIncrement();
16823        mHandler.post(new Runnable() {
16824            @Override
16825            public void run() {
16826                try {
16827                    movePackageInternal(packageName, volumeUuid, moveId);
16828                } catch (PackageManagerException e) {
16829                    Slog.w(TAG, "Failed to move " + packageName, e);
16830                    mMoveCallbacks.notifyStatusChanged(moveId,
16831                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16832                }
16833            }
16834        });
16835        return moveId;
16836    }
16837
16838    private void movePackageInternal(final String packageName, final String volumeUuid,
16839            final int moveId) throws PackageManagerException {
16840        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16841        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16842        final PackageManager pm = mContext.getPackageManager();
16843
16844        final boolean currentAsec;
16845        final String currentVolumeUuid;
16846        final File codeFile;
16847        final String installerPackageName;
16848        final String packageAbiOverride;
16849        final int appId;
16850        final String seinfo;
16851        final String label;
16852
16853        // reader
16854        synchronized (mPackages) {
16855            final PackageParser.Package pkg = mPackages.get(packageName);
16856            final PackageSetting ps = mSettings.mPackages.get(packageName);
16857            if (pkg == null || ps == null) {
16858                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16859            }
16860
16861            if (pkg.applicationInfo.isSystemApp()) {
16862                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16863                        "Cannot move system application");
16864            }
16865
16866            if (pkg.applicationInfo.isExternalAsec()) {
16867                currentAsec = true;
16868                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16869            } else if (pkg.applicationInfo.isForwardLocked()) {
16870                currentAsec = true;
16871                currentVolumeUuid = "forward_locked";
16872            } else {
16873                currentAsec = false;
16874                currentVolumeUuid = ps.volumeUuid;
16875
16876                final File probe = new File(pkg.codePath);
16877                final File probeOat = new File(probe, "oat");
16878                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16879                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16880                            "Move only supported for modern cluster style installs");
16881                }
16882            }
16883
16884            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16885                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16886                        "Package already moved to " + volumeUuid);
16887            }
16888
16889            if (ps.frozen) {
16890                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16891                        "Failed to move already frozen package");
16892            }
16893            ps.frozen = true;
16894
16895            codeFile = new File(pkg.codePath);
16896            installerPackageName = ps.installerPackageName;
16897            packageAbiOverride = ps.cpuAbiOverrideString;
16898            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16899            seinfo = pkg.applicationInfo.seinfo;
16900            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16901        }
16902
16903        // Now that we're guarded by frozen state, kill app during move
16904        final long token = Binder.clearCallingIdentity();
16905        try {
16906            killApplication(packageName, appId, "move pkg");
16907        } finally {
16908            Binder.restoreCallingIdentity(token);
16909        }
16910
16911        final Bundle extras = new Bundle();
16912        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16913        extras.putString(Intent.EXTRA_TITLE, label);
16914        mMoveCallbacks.notifyCreated(moveId, extras);
16915
16916        int installFlags;
16917        final boolean moveCompleteApp;
16918        final File measurePath;
16919
16920        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16921            installFlags = INSTALL_INTERNAL;
16922            moveCompleteApp = !currentAsec;
16923            measurePath = Environment.getDataAppDirectory(volumeUuid);
16924        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16925            installFlags = INSTALL_EXTERNAL;
16926            moveCompleteApp = false;
16927            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16928        } else {
16929            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16930            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16931                    || !volume.isMountedWritable()) {
16932                unfreezePackage(packageName);
16933                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16934                        "Move location not mounted private volume");
16935            }
16936
16937            Preconditions.checkState(!currentAsec);
16938
16939            installFlags = INSTALL_INTERNAL;
16940            moveCompleteApp = true;
16941            measurePath = Environment.getDataAppDirectory(volumeUuid);
16942        }
16943
16944        final PackageStats stats = new PackageStats(null, -1);
16945        synchronized (mInstaller) {
16946            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16947                unfreezePackage(packageName);
16948                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16949                        "Failed to measure package size");
16950            }
16951        }
16952
16953        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16954                + stats.dataSize);
16955
16956        final long startFreeBytes = measurePath.getFreeSpace();
16957        final long sizeBytes;
16958        if (moveCompleteApp) {
16959            sizeBytes = stats.codeSize + stats.dataSize;
16960        } else {
16961            sizeBytes = stats.codeSize;
16962        }
16963
16964        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16965            unfreezePackage(packageName);
16966            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16967                    "Not enough free space to move");
16968        }
16969
16970        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16971
16972        final CountDownLatch installedLatch = new CountDownLatch(1);
16973        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16974            @Override
16975            public void onUserActionRequired(Intent intent) throws RemoteException {
16976                throw new IllegalStateException();
16977            }
16978
16979            @Override
16980            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16981                    Bundle extras) throws RemoteException {
16982                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16983                        + PackageManager.installStatusToString(returnCode, msg));
16984
16985                installedLatch.countDown();
16986
16987                // Regardless of success or failure of the move operation,
16988                // always unfreeze the package
16989                unfreezePackage(packageName);
16990
16991                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16992                switch (status) {
16993                    case PackageInstaller.STATUS_SUCCESS:
16994                        mMoveCallbacks.notifyStatusChanged(moveId,
16995                                PackageManager.MOVE_SUCCEEDED);
16996                        break;
16997                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16998                        mMoveCallbacks.notifyStatusChanged(moveId,
16999                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
17000                        break;
17001                    default:
17002                        mMoveCallbacks.notifyStatusChanged(moveId,
17003                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
17004                        break;
17005                }
17006            }
17007        };
17008
17009        final MoveInfo move;
17010        if (moveCompleteApp) {
17011            // Kick off a thread to report progress estimates
17012            new Thread() {
17013                @Override
17014                public void run() {
17015                    while (true) {
17016                        try {
17017                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
17018                                break;
17019                            }
17020                        } catch (InterruptedException ignored) {
17021                        }
17022
17023                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
17024                        final int progress = 10 + (int) MathUtils.constrain(
17025                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
17026                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
17027                    }
17028                }
17029            }.start();
17030
17031            final String dataAppName = codeFile.getName();
17032            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
17033                    dataAppName, appId, seinfo);
17034        } else {
17035            move = null;
17036        }
17037
17038        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
17039
17040        final Message msg = mHandler.obtainMessage(INIT_COPY);
17041        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
17042        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
17043                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
17044        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
17045        msg.obj = params;
17046
17047        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
17048                System.identityHashCode(msg.obj));
17049        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
17050                System.identityHashCode(msg.obj));
17051
17052        mHandler.sendMessage(msg);
17053    }
17054
17055    @Override
17056    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
17057        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
17058
17059        final int realMoveId = mNextMoveId.getAndIncrement();
17060        final Bundle extras = new Bundle();
17061        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
17062        mMoveCallbacks.notifyCreated(realMoveId, extras);
17063
17064        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
17065            @Override
17066            public void onCreated(int moveId, Bundle extras) {
17067                // Ignored
17068            }
17069
17070            @Override
17071            public void onStatusChanged(int moveId, int status, long estMillis) {
17072                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
17073            }
17074        };
17075
17076        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17077        storage.setPrimaryStorageUuid(volumeUuid, callback);
17078        return realMoveId;
17079    }
17080
17081    @Override
17082    public int getMoveStatus(int moveId) {
17083        mContext.enforceCallingOrSelfPermission(
17084                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17085        return mMoveCallbacks.mLastStatus.get(moveId);
17086    }
17087
17088    @Override
17089    public void registerMoveCallback(IPackageMoveObserver callback) {
17090        mContext.enforceCallingOrSelfPermission(
17091                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17092        mMoveCallbacks.register(callback);
17093    }
17094
17095    @Override
17096    public void unregisterMoveCallback(IPackageMoveObserver callback) {
17097        mContext.enforceCallingOrSelfPermission(
17098                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
17099        mMoveCallbacks.unregister(callback);
17100    }
17101
17102    @Override
17103    public boolean setInstallLocation(int loc) {
17104        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
17105                null);
17106        if (getInstallLocation() == loc) {
17107            return true;
17108        }
17109        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
17110                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
17111            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
17112                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
17113            return true;
17114        }
17115        return false;
17116   }
17117
17118    @Override
17119    public int getInstallLocation() {
17120        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
17121                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
17122                PackageHelper.APP_INSTALL_AUTO);
17123    }
17124
17125    /** Called by UserManagerService */
17126    void cleanUpUser(UserManagerService userManager, int userHandle) {
17127        synchronized (mPackages) {
17128            mDirtyUsers.remove(userHandle);
17129            mUserNeedsBadging.delete(userHandle);
17130            mSettings.removeUserLPw(userHandle);
17131            mPendingBroadcasts.remove(userHandle);
17132            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17133        }
17134        synchronized (mInstallLock) {
17135            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17136            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17137                final String volumeUuid = vol.getFsUuid();
17138                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17139                try {
17140                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17141                } catch (InstallerException e) {
17142                    Slog.w(TAG, "Failed to remove user data", e);
17143                }
17144            }
17145            synchronized (mPackages) {
17146                removeUnusedPackagesLILPw(userManager, userHandle);
17147            }
17148        }
17149    }
17150
17151    /**
17152     * We're removing userHandle and would like to remove any downloaded packages
17153     * that are no longer in use by any other user.
17154     * @param userHandle the user being removed
17155     */
17156    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17157        final boolean DEBUG_CLEAN_APKS = false;
17158        int [] users = userManager.getUserIds();
17159        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17160        while (psit.hasNext()) {
17161            PackageSetting ps = psit.next();
17162            if (ps.pkg == null) {
17163                continue;
17164            }
17165            final String packageName = ps.pkg.packageName;
17166            // Skip over if system app
17167            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17168                continue;
17169            }
17170            if (DEBUG_CLEAN_APKS) {
17171                Slog.i(TAG, "Checking package " + packageName);
17172            }
17173            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17174            if (keep) {
17175                if (DEBUG_CLEAN_APKS) {
17176                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17177                }
17178            } else {
17179                for (int i = 0; i < users.length; i++) {
17180                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17181                        keep = true;
17182                        if (DEBUG_CLEAN_APKS) {
17183                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17184                                    + users[i]);
17185                        }
17186                        break;
17187                    }
17188                }
17189            }
17190            if (!keep) {
17191                if (DEBUG_CLEAN_APKS) {
17192                    Slog.i(TAG, "  Removing package " + packageName);
17193                }
17194                mHandler.post(new Runnable() {
17195                    public void run() {
17196                        deletePackageX(packageName, userHandle, 0);
17197                    } //end run
17198                });
17199            }
17200        }
17201    }
17202
17203    /** Called by UserManagerService */
17204    void createNewUser(int userHandle) {
17205        synchronized (mInstallLock) {
17206            try {
17207                mInstaller.createUserConfig(userHandle);
17208            } catch (InstallerException e) {
17209                Slog.w(TAG, "Failed to create user config", e);
17210            }
17211            mSettings.createNewUserLI(this, mInstaller, userHandle);
17212        }
17213        synchronized (mPackages) {
17214            applyFactoryDefaultBrowserLPw(userHandle);
17215            primeDomainVerificationsLPw(userHandle);
17216        }
17217    }
17218
17219    void newUserCreated(final int userHandle) {
17220        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17221        // If permission review for legacy apps is required, we represent
17222        // dagerous permissions for such apps as always granted runtime
17223        // permissions to keep per user flag state whether review is needed.
17224        // Hence, if a new user is added we have to propagate dangerous
17225        // permission grants for these legacy apps.
17226        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17227            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17228                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17229        }
17230    }
17231
17232    @Override
17233    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17234        mContext.enforceCallingOrSelfPermission(
17235                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17236                "Only package verification agents can read the verifier device identity");
17237
17238        synchronized (mPackages) {
17239            return mSettings.getVerifierDeviceIdentityLPw();
17240        }
17241    }
17242
17243    @Override
17244    public void setPermissionEnforced(String permission, boolean enforced) {
17245        // TODO: Now that we no longer change GID for storage, this should to away.
17246        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17247                "setPermissionEnforced");
17248        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17249            synchronized (mPackages) {
17250                if (mSettings.mReadExternalStorageEnforced == null
17251                        || mSettings.mReadExternalStorageEnforced != enforced) {
17252                    mSettings.mReadExternalStorageEnforced = enforced;
17253                    mSettings.writeLPr();
17254                }
17255            }
17256            // kill any non-foreground processes so we restart them and
17257            // grant/revoke the GID.
17258            final IActivityManager am = ActivityManagerNative.getDefault();
17259            if (am != null) {
17260                final long token = Binder.clearCallingIdentity();
17261                try {
17262                    am.killProcessesBelowForeground("setPermissionEnforcement");
17263                } catch (RemoteException e) {
17264                } finally {
17265                    Binder.restoreCallingIdentity(token);
17266                }
17267            }
17268        } else {
17269            throw new IllegalArgumentException("No selective enforcement for " + permission);
17270        }
17271    }
17272
17273    @Override
17274    @Deprecated
17275    public boolean isPermissionEnforced(String permission) {
17276        return true;
17277    }
17278
17279    @Override
17280    public boolean isStorageLow() {
17281        final long token = Binder.clearCallingIdentity();
17282        try {
17283            final DeviceStorageMonitorInternal
17284                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17285            if (dsm != null) {
17286                return dsm.isMemoryLow();
17287            } else {
17288                return false;
17289            }
17290        } finally {
17291            Binder.restoreCallingIdentity(token);
17292        }
17293    }
17294
17295    @Override
17296    public IPackageInstaller getPackageInstaller() {
17297        return mInstallerService;
17298    }
17299
17300    private boolean userNeedsBadging(int userId) {
17301        int index = mUserNeedsBadging.indexOfKey(userId);
17302        if (index < 0) {
17303            final UserInfo userInfo;
17304            final long token = Binder.clearCallingIdentity();
17305            try {
17306                userInfo = sUserManager.getUserInfo(userId);
17307            } finally {
17308                Binder.restoreCallingIdentity(token);
17309            }
17310            final boolean b;
17311            if (userInfo != null && userInfo.isManagedProfile()) {
17312                b = true;
17313            } else {
17314                b = false;
17315            }
17316            mUserNeedsBadging.put(userId, b);
17317            return b;
17318        }
17319        return mUserNeedsBadging.valueAt(index);
17320    }
17321
17322    @Override
17323    public KeySet getKeySetByAlias(String packageName, String alias) {
17324        if (packageName == null || alias == null) {
17325            return null;
17326        }
17327        synchronized(mPackages) {
17328            final PackageParser.Package pkg = mPackages.get(packageName);
17329            if (pkg == null) {
17330                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17331                throw new IllegalArgumentException("Unknown package: " + packageName);
17332            }
17333            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17334            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17335        }
17336    }
17337
17338    @Override
17339    public KeySet getSigningKeySet(String packageName) {
17340        if (packageName == null) {
17341            return null;
17342        }
17343        synchronized(mPackages) {
17344            final PackageParser.Package pkg = mPackages.get(packageName);
17345            if (pkg == null) {
17346                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17347                throw new IllegalArgumentException("Unknown package: " + packageName);
17348            }
17349            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17350                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17351                throw new SecurityException("May not access signing KeySet of other apps.");
17352            }
17353            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17354            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17355        }
17356    }
17357
17358    @Override
17359    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17360        if (packageName == null || ks == null) {
17361            return false;
17362        }
17363        synchronized(mPackages) {
17364            final PackageParser.Package pkg = mPackages.get(packageName);
17365            if (pkg == null) {
17366                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17367                throw new IllegalArgumentException("Unknown package: " + packageName);
17368            }
17369            IBinder ksh = ks.getToken();
17370            if (ksh instanceof KeySetHandle) {
17371                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17372                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17373            }
17374            return false;
17375        }
17376    }
17377
17378    @Override
17379    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17380        if (packageName == null || ks == null) {
17381            return false;
17382        }
17383        synchronized(mPackages) {
17384            final PackageParser.Package pkg = mPackages.get(packageName);
17385            if (pkg == null) {
17386                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17387                throw new IllegalArgumentException("Unknown package: " + packageName);
17388            }
17389            IBinder ksh = ks.getToken();
17390            if (ksh instanceof KeySetHandle) {
17391                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17392                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17393            }
17394            return false;
17395        }
17396    }
17397
17398    private void deletePackageIfUnusedLPr(final String packageName) {
17399        PackageSetting ps = mSettings.mPackages.get(packageName);
17400        if (ps == null) {
17401            return;
17402        }
17403        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17404            // TODO Implement atomic delete if package is unused
17405            // It is currently possible that the package will be deleted even if it is installed
17406            // after this method returns.
17407            mHandler.post(new Runnable() {
17408                public void run() {
17409                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17410                }
17411            });
17412        }
17413    }
17414
17415    /**
17416     * Check and throw if the given before/after packages would be considered a
17417     * downgrade.
17418     */
17419    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17420            throws PackageManagerException {
17421        if (after.versionCode < before.mVersionCode) {
17422            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17423                    "Update version code " + after.versionCode + " is older than current "
17424                    + before.mVersionCode);
17425        } else if (after.versionCode == before.mVersionCode) {
17426            if (after.baseRevisionCode < before.baseRevisionCode) {
17427                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17428                        "Update base revision code " + after.baseRevisionCode
17429                        + " is older than current " + before.baseRevisionCode);
17430            }
17431
17432            if (!ArrayUtils.isEmpty(after.splitNames)) {
17433                for (int i = 0; i < after.splitNames.length; i++) {
17434                    final String splitName = after.splitNames[i];
17435                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17436                    if (j != -1) {
17437                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17438                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17439                                    "Update split " + splitName + " revision code "
17440                                    + after.splitRevisionCodes[i] + " is older than current "
17441                                    + before.splitRevisionCodes[j]);
17442                        }
17443                    }
17444                }
17445            }
17446        }
17447    }
17448
17449    private static class MoveCallbacks extends Handler {
17450        private static final int MSG_CREATED = 1;
17451        private static final int MSG_STATUS_CHANGED = 2;
17452
17453        private final RemoteCallbackList<IPackageMoveObserver>
17454                mCallbacks = new RemoteCallbackList<>();
17455
17456        private final SparseIntArray mLastStatus = new SparseIntArray();
17457
17458        public MoveCallbacks(Looper looper) {
17459            super(looper);
17460        }
17461
17462        public void register(IPackageMoveObserver callback) {
17463            mCallbacks.register(callback);
17464        }
17465
17466        public void unregister(IPackageMoveObserver callback) {
17467            mCallbacks.unregister(callback);
17468        }
17469
17470        @Override
17471        public void handleMessage(Message msg) {
17472            final SomeArgs args = (SomeArgs) msg.obj;
17473            final int n = mCallbacks.beginBroadcast();
17474            for (int i = 0; i < n; i++) {
17475                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17476                try {
17477                    invokeCallback(callback, msg.what, args);
17478                } catch (RemoteException ignored) {
17479                }
17480            }
17481            mCallbacks.finishBroadcast();
17482            args.recycle();
17483        }
17484
17485        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17486                throws RemoteException {
17487            switch (what) {
17488                case MSG_CREATED: {
17489                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17490                    break;
17491                }
17492                case MSG_STATUS_CHANGED: {
17493                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17494                    break;
17495                }
17496            }
17497        }
17498
17499        private void notifyCreated(int moveId, Bundle extras) {
17500            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17501
17502            final SomeArgs args = SomeArgs.obtain();
17503            args.argi1 = moveId;
17504            args.arg2 = extras;
17505            obtainMessage(MSG_CREATED, args).sendToTarget();
17506        }
17507
17508        private void notifyStatusChanged(int moveId, int status) {
17509            notifyStatusChanged(moveId, status, -1);
17510        }
17511
17512        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17513            Slog.v(TAG, "Move " + moveId + " status " + status);
17514
17515            final SomeArgs args = SomeArgs.obtain();
17516            args.argi1 = moveId;
17517            args.argi2 = status;
17518            args.arg3 = estMillis;
17519            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17520
17521            synchronized (mLastStatus) {
17522                mLastStatus.put(moveId, status);
17523            }
17524        }
17525    }
17526
17527    private final static class OnPermissionChangeListeners extends Handler {
17528        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17529
17530        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17531                new RemoteCallbackList<>();
17532
17533        public OnPermissionChangeListeners(Looper looper) {
17534            super(looper);
17535        }
17536
17537        @Override
17538        public void handleMessage(Message msg) {
17539            switch (msg.what) {
17540                case MSG_ON_PERMISSIONS_CHANGED: {
17541                    final int uid = msg.arg1;
17542                    handleOnPermissionsChanged(uid);
17543                } break;
17544            }
17545        }
17546
17547        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17548            mPermissionListeners.register(listener);
17549
17550        }
17551
17552        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17553            mPermissionListeners.unregister(listener);
17554        }
17555
17556        public void onPermissionsChanged(int uid) {
17557            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17558                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17559            }
17560        }
17561
17562        private void handleOnPermissionsChanged(int uid) {
17563            final int count = mPermissionListeners.beginBroadcast();
17564            try {
17565                for (int i = 0; i < count; i++) {
17566                    IOnPermissionsChangeListener callback = mPermissionListeners
17567                            .getBroadcastItem(i);
17568                    try {
17569                        callback.onPermissionsChanged(uid);
17570                    } catch (RemoteException e) {
17571                        Log.e(TAG, "Permission listener is dead", e);
17572                    }
17573                }
17574            } finally {
17575                mPermissionListeners.finishBroadcast();
17576            }
17577        }
17578    }
17579
17580    private class PackageManagerInternalImpl extends PackageManagerInternal {
17581        @Override
17582        public void setLocationPackagesProvider(PackagesProvider provider) {
17583            synchronized (mPackages) {
17584                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17585            }
17586        }
17587
17588        @Override
17589        public void setImePackagesProvider(PackagesProvider provider) {
17590            synchronized (mPackages) {
17591                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17592            }
17593        }
17594
17595        @Override
17596        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17597            synchronized (mPackages) {
17598                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17599            }
17600        }
17601
17602        @Override
17603        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17604            synchronized (mPackages) {
17605                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17606            }
17607        }
17608
17609        @Override
17610        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17611            synchronized (mPackages) {
17612                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17613            }
17614        }
17615
17616        @Override
17617        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17618            synchronized (mPackages) {
17619                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17620            }
17621        }
17622
17623        @Override
17624        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17625            synchronized (mPackages) {
17626                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17627            }
17628        }
17629
17630        @Override
17631        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17632            synchronized (mPackages) {
17633                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17634                        packageName, userId);
17635            }
17636        }
17637
17638        @Override
17639        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17640            synchronized (mPackages) {
17641                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17642                        packageName, userId);
17643            }
17644        }
17645
17646        @Override
17647        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17648            synchronized (mPackages) {
17649                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17650                        packageName, userId);
17651            }
17652        }
17653
17654        @Override
17655        public void setKeepUninstalledPackages(final List<String> packageList) {
17656            Preconditions.checkNotNull(packageList);
17657            List<String> removedFromList = null;
17658            synchronized (mPackages) {
17659                if (mKeepUninstalledPackages != null) {
17660                    final int packagesCount = mKeepUninstalledPackages.size();
17661                    for (int i = 0; i < packagesCount; i++) {
17662                        String oldPackage = mKeepUninstalledPackages.get(i);
17663                        if (packageList != null && packageList.contains(oldPackage)) {
17664                            continue;
17665                        }
17666                        if (removedFromList == null) {
17667                            removedFromList = new ArrayList<>();
17668                        }
17669                        removedFromList.add(oldPackage);
17670                    }
17671                }
17672                mKeepUninstalledPackages = new ArrayList<>(packageList);
17673                if (removedFromList != null) {
17674                    final int removedCount = removedFromList.size();
17675                    for (int i = 0; i < removedCount; i++) {
17676                        deletePackageIfUnusedLPr(removedFromList.get(i));
17677                    }
17678                }
17679            }
17680        }
17681
17682        @Override
17683        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17684            synchronized (mPackages) {
17685                // If we do not support permission review, done.
17686                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17687                    return false;
17688                }
17689
17690                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17691                if (packageSetting == null) {
17692                    return false;
17693                }
17694
17695                // Permission review applies only to apps not supporting the new permission model.
17696                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17697                    return false;
17698                }
17699
17700                // Legacy apps have the permission and get user consent on launch.
17701                PermissionsState permissionsState = packageSetting.getPermissionsState();
17702                return permissionsState.isPermissionReviewRequired(userId);
17703            }
17704        }
17705    }
17706
17707    @Override
17708    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17709        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17710        synchronized (mPackages) {
17711            final long identity = Binder.clearCallingIdentity();
17712            try {
17713                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17714                        packageNames, userId);
17715            } finally {
17716                Binder.restoreCallingIdentity(identity);
17717            }
17718        }
17719    }
17720
17721    private static void enforceSystemOrPhoneCaller(String tag) {
17722        int callingUid = Binder.getCallingUid();
17723        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17724            throw new SecurityException(
17725                    "Cannot call " + tag + " from UID " + callingUid);
17726        }
17727    }
17728}
17729