PackageManagerService.java revision 6ac42aeed905181b484f97a53db57a17134ef7a8
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
63import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
64import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
65import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
66import static android.content.pm.PackageManager.PERMISSION_DENIED;
67import static android.content.pm.PackageManager.PERMISSION_GRANTED;
68import static android.content.pm.PackageParser.isApkFile;
69import static android.os.Process.PACKAGE_INFO_GID;
70import static android.os.Process.SYSTEM_UID;
71import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
72import static android.system.OsConstants.O_CREAT;
73import static android.system.OsConstants.O_RDWR;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
76import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
77import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
78import static com.android.internal.util.ArrayUtils.appendInt;
79import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
80import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
83import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
84import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
88
89import android.Manifest;
90import android.app.ActivityManager;
91import android.app.ActivityManagerNative;
92import android.app.AppGlobals;
93import android.app.IActivityManager;
94import android.app.admin.IDevicePolicyManager;
95import android.app.backup.IBackupManager;
96import android.content.BroadcastReceiver;
97import android.content.ComponentName;
98import android.content.Context;
99import android.content.IIntentReceiver;
100import android.content.Intent;
101import android.content.IntentFilter;
102import android.content.IntentSender;
103import android.content.IntentSender.SendIntentException;
104import android.content.ServiceConnection;
105import android.content.pm.ActivityInfo;
106import android.content.pm.ApplicationInfo;
107import android.content.pm.AppsQueryHelper;
108import android.content.pm.EphemeralApplicationInfo;
109import android.content.pm.FeatureInfo;
110import android.content.pm.IOnPermissionsChangeListener;
111import android.content.pm.IPackageDataObserver;
112import android.content.pm.IPackageDeleteObserver;
113import android.content.pm.IPackageDeleteObserver2;
114import android.content.pm.IPackageInstallObserver2;
115import android.content.pm.IPackageInstaller;
116import android.content.pm.IPackageManager;
117import android.content.pm.IPackageMoveObserver;
118import android.content.pm.IPackageStatsObserver;
119import android.content.pm.InstrumentationInfo;
120import android.content.pm.IntentFilterVerificationInfo;
121import android.content.pm.KeySet;
122import android.content.pm.ManifestDigest;
123import android.content.pm.PackageCleanItem;
124import android.content.pm.PackageInfo;
125import android.content.pm.PackageInfoLite;
126import android.content.pm.PackageInstaller;
127import android.content.pm.PackageManager;
128import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
129import android.content.pm.PackageManagerInternal;
130import android.content.pm.PackageParser;
131import android.content.pm.PackageParser.ActivityIntentInfo;
132import android.content.pm.PackageParser.PackageLite;
133import android.content.pm.PackageParser.PackageParserException;
134import android.content.pm.PackageStats;
135import android.content.pm.PackageUserState;
136import android.content.pm.ParceledListSlice;
137import android.content.pm.PermissionGroupInfo;
138import android.content.pm.PermissionInfo;
139import android.content.pm.ProviderInfo;
140import android.content.pm.ResolveInfo;
141import android.content.pm.ServiceInfo;
142import android.content.pm.Signature;
143import android.content.pm.UserInfo;
144import android.content.pm.VerificationParams;
145import android.content.pm.VerifierDeviceIdentity;
146import android.content.pm.VerifierInfo;
147import android.content.res.Resources;
148import android.graphics.Bitmap;
149import android.hardware.display.DisplayManager;
150import android.net.Uri;
151import android.os.Debug;
152import android.os.Binder;
153import android.os.Build;
154import android.os.Bundle;
155import android.os.Environment;
156import android.os.Environment.UserEnvironment;
157import android.os.FileUtils;
158import android.os.Handler;
159import android.os.IBinder;
160import android.os.Looper;
161import android.os.Message;
162import android.os.Parcel;
163import android.os.ParcelFileDescriptor;
164import android.os.Process;
165import android.os.RemoteCallbackList;
166import android.os.RemoteException;
167import android.os.ResultReceiver;
168import android.os.SELinux;
169import android.os.ServiceManager;
170import android.os.SystemClock;
171import android.os.SystemProperties;
172import android.os.Trace;
173import android.os.UserHandle;
174import android.os.UserManager;
175import android.os.storage.IMountService;
176import android.os.storage.MountServiceInternal;
177import android.os.storage.StorageEventListener;
178import android.os.storage.StorageManager;
179import android.os.storage.VolumeInfo;
180import android.os.storage.VolumeRecord;
181import android.security.KeyStore;
182import android.security.SystemKeyStore;
183import android.system.ErrnoException;
184import android.system.Os;
185import android.system.StructStat;
186import android.text.TextUtils;
187import android.text.format.DateUtils;
188import android.util.ArrayMap;
189import android.util.ArraySet;
190import android.util.AtomicFile;
191import android.util.DisplayMetrics;
192import android.util.EventLog;
193import android.util.ExceptionUtils;
194import android.util.Log;
195import android.util.LogPrinter;
196import android.util.MathUtils;
197import android.util.PrintStreamPrinter;
198import android.util.Slog;
199import android.util.SparseArray;
200import android.util.SparseBooleanArray;
201import android.util.SparseIntArray;
202import android.util.Xml;
203import android.view.Display;
204
205import com.android.internal.annotations.GuardedBy;
206import dalvik.system.DexFile;
207import dalvik.system.VMRuntime;
208
209import libcore.io.IoUtils;
210import libcore.util.EmptyArray;
211
212import com.android.internal.R;
213import com.android.internal.app.EphemeralResolveInfo;
214import com.android.internal.app.IMediaContainerService;
215import com.android.internal.app.ResolverActivity;
216import com.android.internal.content.NativeLibraryHelper;
217import com.android.internal.content.PackageHelper;
218import com.android.internal.os.IParcelFileDescriptorFactory;
219import com.android.internal.os.SomeArgs;
220import com.android.internal.os.Zygote;
221import com.android.internal.util.ArrayUtils;
222import com.android.internal.util.FastPrintWriter;
223import com.android.internal.util.FastXmlSerializer;
224import com.android.internal.util.IndentingPrintWriter;
225import com.android.internal.util.Preconditions;
226import com.android.server.EventLogTags;
227import com.android.server.FgThread;
228import com.android.server.IntentResolver;
229import com.android.server.LocalServices;
230import com.android.server.ServiceThread;
231import com.android.server.SystemConfig;
232import com.android.server.Watchdog;
233import com.android.server.pm.PermissionsState.PermissionState;
234import com.android.server.pm.Settings.DatabaseVersion;
235import com.android.server.pm.Settings.VersionInfo;
236import com.android.server.storage.DeviceStorageMonitorInternal;
237
238import org.xmlpull.v1.XmlPullParser;
239import org.xmlpull.v1.XmlPullParserException;
240import org.xmlpull.v1.XmlSerializer;
241
242import java.io.BufferedInputStream;
243import java.io.BufferedOutputStream;
244import java.io.BufferedReader;
245import java.io.ByteArrayInputStream;
246import java.io.ByteArrayOutputStream;
247import java.io.File;
248import java.io.FileDescriptor;
249import java.io.FileNotFoundException;
250import java.io.FileOutputStream;
251import java.io.FileReader;
252import java.io.FilenameFilter;
253import java.io.IOException;
254import java.io.InputStream;
255import java.io.PrintWriter;
256import java.nio.charset.StandardCharsets;
257import java.security.MessageDigest;
258import java.security.NoSuchAlgorithmException;
259import java.security.PublicKey;
260import java.security.cert.CertificateEncodingException;
261import java.security.cert.CertificateException;
262import java.text.SimpleDateFormat;
263import java.util.ArrayList;
264import java.util.Arrays;
265import java.util.Collection;
266import java.util.Collections;
267import java.util.Comparator;
268import java.util.Date;
269import java.util.Iterator;
270import java.util.List;
271import java.util.Map;
272import java.util.Objects;
273import java.util.Set;
274import java.util.concurrent.CountDownLatch;
275import java.util.concurrent.TimeUnit;
276import java.util.concurrent.atomic.AtomicBoolean;
277import java.util.concurrent.atomic.AtomicInteger;
278import java.util.concurrent.atomic.AtomicLong;
279
280/**
281 * Keep track of all those .apks everywhere.
282 *
283 * This is very central to the platform's security; please run the unit
284 * tests whenever making modifications here:
285 *
286runtest -c android.content.pm.PackageManagerTests frameworks-core
287 *
288 * {@hide}
289 */
290public class PackageManagerService extends IPackageManager.Stub {
291    static final String TAG = "PackageManager";
292    static final boolean DEBUG_SETTINGS = false;
293    static final boolean DEBUG_PREFERRED = false;
294    static final boolean DEBUG_UPGRADE = false;
295    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
296    private static final boolean DEBUG_BACKUP = false;
297    private static final boolean DEBUG_INSTALL = false;
298    private static final boolean DEBUG_REMOVE = false;
299    private static final boolean DEBUG_BROADCASTS = false;
300    private static final boolean DEBUG_SHOW_INFO = false;
301    private static final boolean DEBUG_PACKAGE_INFO = false;
302    private static final boolean DEBUG_INTENT_MATCHING = false;
303    private static final boolean DEBUG_PACKAGE_SCANNING = false;
304    private static final boolean DEBUG_VERIFY = false;
305    private static final boolean DEBUG_DEXOPT = false;
306    private static final boolean DEBUG_ABI_SELECTION = false;
307    private static final boolean DEBUG_EPHEMERAL = false;
308
309    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
310
311    private static final int RADIO_UID = Process.PHONE_UID;
312    private static final int LOG_UID = Process.LOG_UID;
313    private static final int NFC_UID = Process.NFC_UID;
314    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
315    private static final int SHELL_UID = Process.SHELL_UID;
316
317    // Cap the size of permission trees that 3rd party apps can define
318    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
319
320    // Suffix used during package installation when copying/moving
321    // package apks to install directory.
322    private static final String INSTALL_PACKAGE_SUFFIX = "-";
323
324    static final int SCAN_NO_DEX = 1<<1;
325    static final int SCAN_FORCE_DEX = 1<<2;
326    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
327    static final int SCAN_NEW_INSTALL = 1<<4;
328    static final int SCAN_NO_PATHS = 1<<5;
329    static final int SCAN_UPDATE_TIME = 1<<6;
330    static final int SCAN_DEFER_DEX = 1<<7;
331    static final int SCAN_BOOTING = 1<<8;
332    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
333    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
334    static final int SCAN_REPLACING = 1<<11;
335    static final int SCAN_REQUIRE_KNOWN = 1<<12;
336    static final int SCAN_MOVE = 1<<13;
337    static final int SCAN_INITIAL = 1<<14;
338
339    static final int REMOVE_CHATTY = 1<<16;
340
341    private static final int[] EMPTY_INT_ARRAY = new int[0];
342
343    /**
344     * Timeout (in milliseconds) after which the watchdog should declare that
345     * our handler thread is wedged.  The usual default for such things is one
346     * minute but we sometimes do very lengthy I/O operations on this thread,
347     * such as installing multi-gigabyte applications, so ours needs to be longer.
348     */
349    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
350
351    /**
352     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
353     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
354     * settings entry if available, otherwise we use the hardcoded default.  If it's been
355     * more than this long since the last fstrim, we force one during the boot sequence.
356     *
357     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
358     * one gets run at the next available charging+idle time.  This final mandatory
359     * no-fstrim check kicks in only of the other scheduling criteria is never met.
360     */
361    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
362
363    /**
364     * Whether verification is enabled by default.
365     */
366    private static final boolean DEFAULT_VERIFY_ENABLE = true;
367
368    /**
369     * The default maximum time to wait for the verification agent to return in
370     * milliseconds.
371     */
372    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
373
374    /**
375     * The default response for package verification timeout.
376     *
377     * This can be either PackageManager.VERIFICATION_ALLOW or
378     * PackageManager.VERIFICATION_REJECT.
379     */
380    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
381
382    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
383
384    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
385            DEFAULT_CONTAINER_PACKAGE,
386            "com.android.defcontainer.DefaultContainerService");
387
388    private static final String KILL_APP_REASON_GIDS_CHANGED =
389            "permission grant or revoke changed gids";
390
391    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
392            "permissions revoked";
393
394    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
395
396    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
397
398    /** Permission grant: not grant the permission. */
399    private static final int GRANT_DENIED = 1;
400
401    /** Permission grant: grant the permission as an install permission. */
402    private static final int GRANT_INSTALL = 2;
403
404    /** Permission grant: grant the permission as a runtime one. */
405    private static final int GRANT_RUNTIME = 3;
406
407    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
408    private static final int GRANT_UPGRADE = 4;
409
410    /** Canonical intent used to identify what counts as a "web browser" app */
411    private static final Intent sBrowserIntent;
412    static {
413        sBrowserIntent = new Intent();
414        sBrowserIntent.setAction(Intent.ACTION_VIEW);
415        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
416        sBrowserIntent.setData(Uri.parse("http:"));
417    }
418
419    final ServiceThread mHandlerThread;
420
421    final PackageHandler mHandler;
422
423    /**
424     * Messages for {@link #mHandler} that need to wait for system ready before
425     * being dispatched.
426     */
427    private ArrayList<Message> mPostSystemReadyMessages;
428
429    final int mSdkVersion = Build.VERSION.SDK_INT;
430
431    final Context mContext;
432    final boolean mFactoryTest;
433    final boolean mOnlyCore;
434    final DisplayMetrics mMetrics;
435    final int mDefParseFlags;
436    final String[] mSeparateProcesses;
437    final boolean mIsUpgrade;
438
439    // This is where all application persistent data goes.
440    final File mAppDataDir;
441
442    // This is where all application persistent data goes for secondary users.
443    final File mUserAppDataDir;
444
445    /** The location for ASEC container files on internal storage. */
446    final String mAsecInternalPath;
447
448    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
449    // LOCK HELD.  Can be called with mInstallLock held.
450    @GuardedBy("mInstallLock")
451    final Installer mInstaller;
452
453    /** Directory where installed third-party apps stored */
454    final File mAppInstallDir;
455    final File mEphemeralInstallDir;
456
457    /**
458     * Directory to which applications installed internally have their
459     * 32 bit native libraries copied.
460     */
461    private File mAppLib32InstallDir;
462
463    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
464    // apps.
465    final File mDrmAppPrivateInstallDir;
466
467    // ----------------------------------------------------------------
468
469    // Lock for state used when installing and doing other long running
470    // operations.  Methods that must be called with this lock held have
471    // the suffix "LI".
472    final Object mInstallLock = new Object();
473
474    // ----------------------------------------------------------------
475
476    // Keys are String (package name), values are Package.  This also serves
477    // as the lock for the global state.  Methods that must be called with
478    // this lock held have the prefix "LP".
479    @GuardedBy("mPackages")
480    final ArrayMap<String, PackageParser.Package> mPackages =
481            new ArrayMap<String, PackageParser.Package>();
482
483    // Tracks available target package names -> overlay package paths.
484    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
485        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
486
487    /**
488     * Tracks new system packages [received in an OTA] that we expect to
489     * find updated user-installed versions. Keys are package name, values
490     * are package location.
491     */
492    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
493
494    /**
495     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
496     */
497    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
498    /**
499     * Whether or not system app permissions should be promoted from install to runtime.
500     */
501    boolean mPromoteSystemApps;
502
503    final Settings mSettings;
504    boolean mRestoredSettings;
505
506    // System configuration read by SystemConfig.
507    final int[] mGlobalGids;
508    final SparseArray<ArraySet<String>> mSystemPermissions;
509    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
510
511    // If mac_permissions.xml was found for seinfo labeling.
512    boolean mFoundPolicyFile;
513
514    // If a recursive restorecon of /data/data/<pkg> is needed.
515    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
516
517    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
518
519    public static final class SharedLibraryEntry {
520        public final String path;
521        public final String apk;
522
523        SharedLibraryEntry(String _path, String _apk) {
524            path = _path;
525            apk = _apk;
526        }
527    }
528
529    // Currently known shared libraries.
530    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
531            new ArrayMap<String, SharedLibraryEntry>();
532
533    // All available activities, for your resolving pleasure.
534    final ActivityIntentResolver mActivities =
535            new ActivityIntentResolver();
536
537    // All available receivers, for your resolving pleasure.
538    final ActivityIntentResolver mReceivers =
539            new ActivityIntentResolver();
540
541    // All available services, for your resolving pleasure.
542    final ServiceIntentResolver mServices = new ServiceIntentResolver();
543
544    // All available providers, for your resolving pleasure.
545    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
546
547    // Mapping from provider base names (first directory in content URI codePath)
548    // to the provider information.
549    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
550            new ArrayMap<String, PackageParser.Provider>();
551
552    // Mapping from instrumentation class names to info about them.
553    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
554            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
555
556    // Mapping from permission names to info about them.
557    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
558            new ArrayMap<String, PackageParser.PermissionGroup>();
559
560    // Packages whose data we have transfered into another package, thus
561    // should no longer exist.
562    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
563
564    // Broadcast actions that are only available to the system.
565    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
566
567    /** List of packages waiting for verification. */
568    final SparseArray<PackageVerificationState> mPendingVerification
569            = new SparseArray<PackageVerificationState>();
570
571    /** Set of packages associated with each app op permission. */
572    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
573
574    final PackageInstallerService mInstallerService;
575
576    private final PackageDexOptimizer mPackageDexOptimizer;
577
578    private AtomicInteger mNextMoveId = new AtomicInteger();
579    private final MoveCallbacks mMoveCallbacks;
580
581    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
582
583    // Cache of users who need badging.
584    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
585
586    /** Token for keys in mPendingVerification. */
587    private int mPendingVerificationToken = 0;
588
589    volatile boolean mSystemReady;
590    volatile boolean mSafeMode;
591    volatile boolean mHasSystemUidErrors;
592
593    ApplicationInfo mAndroidApplication;
594    final ActivityInfo mResolveActivity = new ActivityInfo();
595    final ResolveInfo mResolveInfo = new ResolveInfo();
596    ComponentName mResolveComponentName;
597    PackageParser.Package mPlatformPackage;
598    ComponentName mCustomResolverComponentName;
599
600    boolean mResolverReplaced = false;
601
602    private final ComponentName mIntentFilterVerifierComponent;
603    private int mIntentFilterVerificationToken = 0;
604
605    /** Component that knows whether or not an ephemeral application exists */
606    final ComponentName mEphemeralResolverComponent;
607    /** The service connection to the ephemeral resolver */
608    final EphemeralResolverConnection mEphemeralResolverConnection;
609
610    /** Component used to install ephemeral applications */
611    final ComponentName mEphemeralInstallerComponent;
612    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
613    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
614
615    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
616            = new SparseArray<IntentFilterVerificationState>();
617
618    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
619            new DefaultPermissionGrantPolicy(this);
620
621    // List of packages names to keep cached, even if they are uninstalled for all users
622    private List<String> mKeepUninstalledPackages;
623
624    private static class IFVerificationParams {
625        PackageParser.Package pkg;
626        boolean replacing;
627        int userId;
628        int verifierUid;
629
630        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
631                int _userId, int _verifierUid) {
632            pkg = _pkg;
633            replacing = _replacing;
634            userId = _userId;
635            replacing = _replacing;
636            verifierUid = _verifierUid;
637        }
638    }
639
640    private interface IntentFilterVerifier<T extends IntentFilter> {
641        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
642                                               T filter, String packageName);
643        void startVerifications(int userId);
644        void receiveVerificationResponse(int verificationId);
645    }
646
647    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
648        private Context mContext;
649        private ComponentName mIntentFilterVerifierComponent;
650        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
651
652        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
653            mContext = context;
654            mIntentFilterVerifierComponent = verifierComponent;
655        }
656
657        private String getDefaultScheme() {
658            return IntentFilter.SCHEME_HTTPS;
659        }
660
661        @Override
662        public void startVerifications(int userId) {
663            // Launch verifications requests
664            int count = mCurrentIntentFilterVerifications.size();
665            for (int n=0; n<count; n++) {
666                int verificationId = mCurrentIntentFilterVerifications.get(n);
667                final IntentFilterVerificationState ivs =
668                        mIntentFilterVerificationStates.get(verificationId);
669
670                String packageName = ivs.getPackageName();
671
672                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
673                final int filterCount = filters.size();
674                ArraySet<String> domainsSet = new ArraySet<>();
675                for (int m=0; m<filterCount; m++) {
676                    PackageParser.ActivityIntentInfo filter = filters.get(m);
677                    domainsSet.addAll(filter.getHostsList());
678                }
679                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
680                synchronized (mPackages) {
681                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
682                            packageName, domainsList) != null) {
683                        scheduleWriteSettingsLocked();
684                    }
685                }
686                sendVerificationRequest(userId, verificationId, ivs);
687            }
688            mCurrentIntentFilterVerifications.clear();
689        }
690
691        private void sendVerificationRequest(int userId, int verificationId,
692                IntentFilterVerificationState ivs) {
693
694            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
695            verificationIntent.putExtra(
696                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
697                    verificationId);
698            verificationIntent.putExtra(
699                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
700                    getDefaultScheme());
701            verificationIntent.putExtra(
702                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
703                    ivs.getHostsString());
704            verificationIntent.putExtra(
705                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
706                    ivs.getPackageName());
707            verificationIntent.setComponent(mIntentFilterVerifierComponent);
708            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
709
710            UserHandle user = new UserHandle(userId);
711            mContext.sendBroadcastAsUser(verificationIntent, user);
712            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
713                    "Sending IntentFilter verification broadcast");
714        }
715
716        public void receiveVerificationResponse(int verificationId) {
717            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
718
719            final boolean verified = ivs.isVerified();
720
721            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
722            final int count = filters.size();
723            if (DEBUG_DOMAIN_VERIFICATION) {
724                Slog.i(TAG, "Received verification response " + verificationId
725                        + " for " + count + " filters, verified=" + verified);
726            }
727            for (int n=0; n<count; n++) {
728                PackageParser.ActivityIntentInfo filter = filters.get(n);
729                filter.setVerified(verified);
730
731                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
732                        + " verified with result:" + verified + " and hosts:"
733                        + ivs.getHostsString());
734            }
735
736            mIntentFilterVerificationStates.remove(verificationId);
737
738            final String packageName = ivs.getPackageName();
739            IntentFilterVerificationInfo ivi = null;
740
741            synchronized (mPackages) {
742                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
743            }
744            if (ivi == null) {
745                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
746                        + verificationId + " packageName:" + packageName);
747                return;
748            }
749            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
750                    "Updating IntentFilterVerificationInfo for package " + packageName
751                            +" verificationId:" + verificationId);
752
753            synchronized (mPackages) {
754                if (verified) {
755                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
756                } else {
757                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
758                }
759                scheduleWriteSettingsLocked();
760
761                final int userId = ivs.getUserId();
762                if (userId != UserHandle.USER_ALL) {
763                    final int userStatus =
764                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
765
766                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
767                    boolean needUpdate = false;
768
769                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
770                    // already been set by the User thru the Disambiguation dialog
771                    switch (userStatus) {
772                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
773                            if (verified) {
774                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
775                            } else {
776                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
777                            }
778                            needUpdate = true;
779                            break;
780
781                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
782                            if (verified) {
783                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
784                                needUpdate = true;
785                            }
786                            break;
787
788                        default:
789                            // Nothing to do
790                    }
791
792                    if (needUpdate) {
793                        mSettings.updateIntentFilterVerificationStatusLPw(
794                                packageName, updatedStatus, userId);
795                        scheduleWritePackageRestrictionsLocked(userId);
796                    }
797                }
798            }
799        }
800
801        @Override
802        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
803                    ActivityIntentInfo filter, String packageName) {
804            if (!hasValidDomains(filter)) {
805                return false;
806            }
807            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
808            if (ivs == null) {
809                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
810                        packageName);
811            }
812            if (DEBUG_DOMAIN_VERIFICATION) {
813                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
814            }
815            ivs.addFilter(filter);
816            return true;
817        }
818
819        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
820                int userId, int verificationId, String packageName) {
821            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
822                    verifierUid, userId, packageName);
823            ivs.setPendingState();
824            synchronized (mPackages) {
825                mIntentFilterVerificationStates.append(verificationId, ivs);
826                mCurrentIntentFilterVerifications.add(verificationId);
827            }
828            return ivs;
829        }
830    }
831
832    private static boolean hasValidDomains(ActivityIntentInfo filter) {
833        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
834                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
835                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
836    }
837
838    private IntentFilterVerifier mIntentFilterVerifier;
839
840    // Set of pending broadcasts for aggregating enable/disable of components.
841    static class PendingPackageBroadcasts {
842        // for each user id, a map of <package name -> components within that package>
843        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
844
845        public PendingPackageBroadcasts() {
846            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
847        }
848
849        public ArrayList<String> get(int userId, String packageName) {
850            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
851            return packages.get(packageName);
852        }
853
854        public void put(int userId, String packageName, ArrayList<String> components) {
855            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
856            packages.put(packageName, components);
857        }
858
859        public void remove(int userId, String packageName) {
860            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
861            if (packages != null) {
862                packages.remove(packageName);
863            }
864        }
865
866        public void remove(int userId) {
867            mUidMap.remove(userId);
868        }
869
870        public int userIdCount() {
871            return mUidMap.size();
872        }
873
874        public int userIdAt(int n) {
875            return mUidMap.keyAt(n);
876        }
877
878        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
879            return mUidMap.get(userId);
880        }
881
882        public int size() {
883            // total number of pending broadcast entries across all userIds
884            int num = 0;
885            for (int i = 0; i< mUidMap.size(); i++) {
886                num += mUidMap.valueAt(i).size();
887            }
888            return num;
889        }
890
891        public void clear() {
892            mUidMap.clear();
893        }
894
895        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
896            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
897            if (map == null) {
898                map = new ArrayMap<String, ArrayList<String>>();
899                mUidMap.put(userId, map);
900            }
901            return map;
902        }
903    }
904    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
905
906    // Service Connection to remote media container service to copy
907    // package uri's from external media onto secure containers
908    // or internal storage.
909    private IMediaContainerService mContainerService = null;
910
911    static final int SEND_PENDING_BROADCAST = 1;
912    static final int MCS_BOUND = 3;
913    static final int END_COPY = 4;
914    static final int INIT_COPY = 5;
915    static final int MCS_UNBIND = 6;
916    static final int START_CLEANING_PACKAGE = 7;
917    static final int FIND_INSTALL_LOC = 8;
918    static final int POST_INSTALL = 9;
919    static final int MCS_RECONNECT = 10;
920    static final int MCS_GIVE_UP = 11;
921    static final int UPDATED_MEDIA_STATUS = 12;
922    static final int WRITE_SETTINGS = 13;
923    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
924    static final int PACKAGE_VERIFIED = 15;
925    static final int CHECK_PENDING_VERIFICATION = 16;
926    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
927    static final int INTENT_FILTER_VERIFIED = 18;
928
929    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
930
931    // Delay time in millisecs
932    static final int BROADCAST_DELAY = 10 * 1000;
933
934    static UserManagerService sUserManager;
935
936    // Stores a list of users whose package restrictions file needs to be updated
937    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
938
939    final private DefaultContainerConnection mDefContainerConn =
940            new DefaultContainerConnection();
941    class DefaultContainerConnection implements ServiceConnection {
942        public void onServiceConnected(ComponentName name, IBinder service) {
943            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
944            IMediaContainerService imcs =
945                IMediaContainerService.Stub.asInterface(service);
946            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
947        }
948
949        public void onServiceDisconnected(ComponentName name) {
950            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
951        }
952    }
953
954    // Recordkeeping of restore-after-install operations that are currently in flight
955    // between the Package Manager and the Backup Manager
956    class PostInstallData {
957        public InstallArgs args;
958        public PackageInstalledInfo res;
959
960        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
961            args = _a;
962            res = _r;
963        }
964    }
965
966    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
967    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
968
969    // XML tags for backup/restore of various bits of state
970    private static final String TAG_PREFERRED_BACKUP = "pa";
971    private static final String TAG_DEFAULT_APPS = "da";
972    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
973
974    final String mRequiredVerifierPackage;
975    final String mRequiredInstallerPackage;
976
977    private final PackageUsage mPackageUsage = new PackageUsage();
978
979    private class PackageUsage {
980        private static final int WRITE_INTERVAL
981            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
982
983        private final Object mFileLock = new Object();
984        private final AtomicLong mLastWritten = new AtomicLong(0);
985        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
986
987        private boolean mIsHistoricalPackageUsageAvailable = true;
988
989        boolean isHistoricalPackageUsageAvailable() {
990            return mIsHistoricalPackageUsageAvailable;
991        }
992
993        void write(boolean force) {
994            if (force) {
995                writeInternal();
996                return;
997            }
998            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
999                && !DEBUG_DEXOPT) {
1000                return;
1001            }
1002            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1003                new Thread("PackageUsage_DiskWriter") {
1004                    @Override
1005                    public void run() {
1006                        try {
1007                            writeInternal();
1008                        } finally {
1009                            mBackgroundWriteRunning.set(false);
1010                        }
1011                    }
1012                }.start();
1013            }
1014        }
1015
1016        private void writeInternal() {
1017            synchronized (mPackages) {
1018                synchronized (mFileLock) {
1019                    AtomicFile file = getFile();
1020                    FileOutputStream f = null;
1021                    try {
1022                        f = file.startWrite();
1023                        BufferedOutputStream out = new BufferedOutputStream(f);
1024                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1025                        StringBuilder sb = new StringBuilder();
1026                        for (PackageParser.Package pkg : mPackages.values()) {
1027                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1028                                continue;
1029                            }
1030                            sb.setLength(0);
1031                            sb.append(pkg.packageName);
1032                            sb.append(' ');
1033                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1034                            sb.append('\n');
1035                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1036                        }
1037                        out.flush();
1038                        file.finishWrite(f);
1039                    } catch (IOException e) {
1040                        if (f != null) {
1041                            file.failWrite(f);
1042                        }
1043                        Log.e(TAG, "Failed to write package usage times", e);
1044                    }
1045                }
1046            }
1047            mLastWritten.set(SystemClock.elapsedRealtime());
1048        }
1049
1050        void readLP() {
1051            synchronized (mFileLock) {
1052                AtomicFile file = getFile();
1053                BufferedInputStream in = null;
1054                try {
1055                    in = new BufferedInputStream(file.openRead());
1056                    StringBuffer sb = new StringBuffer();
1057                    while (true) {
1058                        String packageName = readToken(in, sb, ' ');
1059                        if (packageName == null) {
1060                            break;
1061                        }
1062                        String timeInMillisString = readToken(in, sb, '\n');
1063                        if (timeInMillisString == null) {
1064                            throw new IOException("Failed to find last usage time for package "
1065                                                  + packageName);
1066                        }
1067                        PackageParser.Package pkg = mPackages.get(packageName);
1068                        if (pkg == null) {
1069                            continue;
1070                        }
1071                        long timeInMillis;
1072                        try {
1073                            timeInMillis = Long.parseLong(timeInMillisString.toString());
1074                        } catch (NumberFormatException e) {
1075                            throw new IOException("Failed to parse " + timeInMillisString
1076                                                  + " as a long.", e);
1077                        }
1078                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1079                    }
1080                } catch (FileNotFoundException expected) {
1081                    mIsHistoricalPackageUsageAvailable = false;
1082                } catch (IOException e) {
1083                    Log.w(TAG, "Failed to read package usage times", e);
1084                } finally {
1085                    IoUtils.closeQuietly(in);
1086                }
1087            }
1088            mLastWritten.set(SystemClock.elapsedRealtime());
1089        }
1090
1091        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1092                throws IOException {
1093            sb.setLength(0);
1094            while (true) {
1095                int ch = in.read();
1096                if (ch == -1) {
1097                    if (sb.length() == 0) {
1098                        return null;
1099                    }
1100                    throw new IOException("Unexpected EOF");
1101                }
1102                if (ch == endOfToken) {
1103                    return sb.toString();
1104                }
1105                sb.append((char)ch);
1106            }
1107        }
1108
1109        private AtomicFile getFile() {
1110            File dataDir = Environment.getDataDirectory();
1111            File systemDir = new File(dataDir, "system");
1112            File fname = new File(systemDir, "package-usage.list");
1113            return new AtomicFile(fname);
1114        }
1115    }
1116
1117    class PackageHandler extends Handler {
1118        private boolean mBound = false;
1119        final ArrayList<HandlerParams> mPendingInstalls =
1120            new ArrayList<HandlerParams>();
1121
1122        private boolean connectToService() {
1123            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1124                    " DefaultContainerService");
1125            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1126            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1127            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1128                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1129                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1130                mBound = true;
1131                return true;
1132            }
1133            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1134            return false;
1135        }
1136
1137        private void disconnectService() {
1138            mContainerService = null;
1139            mBound = false;
1140            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1141            mContext.unbindService(mDefContainerConn);
1142            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1143        }
1144
1145        PackageHandler(Looper looper) {
1146            super(looper);
1147        }
1148
1149        public void handleMessage(Message msg) {
1150            try {
1151                doHandleMessage(msg);
1152            } finally {
1153                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1154            }
1155        }
1156
1157        void doHandleMessage(Message msg) {
1158            switch (msg.what) {
1159                case INIT_COPY: {
1160                    HandlerParams params = (HandlerParams) msg.obj;
1161                    int idx = mPendingInstalls.size();
1162                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1163                    // If a bind was already initiated we dont really
1164                    // need to do anything. The pending install
1165                    // will be processed later on.
1166                    if (!mBound) {
1167                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1168                                System.identityHashCode(mHandler));
1169                        // If this is the only one pending we might
1170                        // have to bind to the service again.
1171                        if (!connectToService()) {
1172                            Slog.e(TAG, "Failed to bind to media container service");
1173                            params.serviceError();
1174                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1175                                    System.identityHashCode(mHandler));
1176                            if (params.traceMethod != null) {
1177                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1178                                        params.traceCookie);
1179                            }
1180                            return;
1181                        } else {
1182                            // Once we bind to the service, the first
1183                            // pending request will be processed.
1184                            mPendingInstalls.add(idx, params);
1185                        }
1186                    } else {
1187                        mPendingInstalls.add(idx, params);
1188                        // Already bound to the service. Just make
1189                        // sure we trigger off processing the first request.
1190                        if (idx == 0) {
1191                            mHandler.sendEmptyMessage(MCS_BOUND);
1192                        }
1193                    }
1194                    break;
1195                }
1196                case MCS_BOUND: {
1197                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1198                    if (msg.obj != null) {
1199                        mContainerService = (IMediaContainerService) msg.obj;
1200                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1201                                System.identityHashCode(mHandler));
1202                    }
1203                    if (mContainerService == null) {
1204                        if (!mBound) {
1205                            // Something seriously wrong since we are not bound and we are not
1206                            // waiting for connection. Bail out.
1207                            Slog.e(TAG, "Cannot bind to media container service");
1208                            for (HandlerParams params : mPendingInstalls) {
1209                                // Indicate service bind error
1210                                params.serviceError();
1211                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1212                                        System.identityHashCode(params));
1213                                if (params.traceMethod != null) {
1214                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1215                                            params.traceMethod, params.traceCookie);
1216                                }
1217                                return;
1218                            }
1219                            mPendingInstalls.clear();
1220                        } else {
1221                            Slog.w(TAG, "Waiting to connect to media container service");
1222                        }
1223                    } else if (mPendingInstalls.size() > 0) {
1224                        HandlerParams params = mPendingInstalls.get(0);
1225                        if (params != null) {
1226                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1227                                    System.identityHashCode(params));
1228                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1229                            if (params.startCopy()) {
1230                                // We are done...  look for more work or to
1231                                // go idle.
1232                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1233                                        "Checking for more work or unbind...");
1234                                // Delete pending install
1235                                if (mPendingInstalls.size() > 0) {
1236                                    mPendingInstalls.remove(0);
1237                                }
1238                                if (mPendingInstalls.size() == 0) {
1239                                    if (mBound) {
1240                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1241                                                "Posting delayed MCS_UNBIND");
1242                                        removeMessages(MCS_UNBIND);
1243                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1244                                        // Unbind after a little delay, to avoid
1245                                        // continual thrashing.
1246                                        sendMessageDelayed(ubmsg, 10000);
1247                                    }
1248                                } else {
1249                                    // There are more pending requests in queue.
1250                                    // Just post MCS_BOUND message to trigger processing
1251                                    // of next pending install.
1252                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1253                                            "Posting MCS_BOUND for next work");
1254                                    mHandler.sendEmptyMessage(MCS_BOUND);
1255                                }
1256                            }
1257                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1258                        }
1259                    } else {
1260                        // Should never happen ideally.
1261                        Slog.w(TAG, "Empty queue");
1262                    }
1263                    break;
1264                }
1265                case MCS_RECONNECT: {
1266                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1267                    if (mPendingInstalls.size() > 0) {
1268                        if (mBound) {
1269                            disconnectService();
1270                        }
1271                        if (!connectToService()) {
1272                            Slog.e(TAG, "Failed to bind to media container service");
1273                            for (HandlerParams params : mPendingInstalls) {
1274                                // Indicate service bind error
1275                                params.serviceError();
1276                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1277                                        System.identityHashCode(params));
1278                            }
1279                            mPendingInstalls.clear();
1280                        }
1281                    }
1282                    break;
1283                }
1284                case MCS_UNBIND: {
1285                    // If there is no actual work left, then time to unbind.
1286                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1287
1288                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1289                        if (mBound) {
1290                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1291
1292                            disconnectService();
1293                        }
1294                    } else if (mPendingInstalls.size() > 0) {
1295                        // There are more pending requests in queue.
1296                        // Just post MCS_BOUND message to trigger processing
1297                        // of next pending install.
1298                        mHandler.sendEmptyMessage(MCS_BOUND);
1299                    }
1300
1301                    break;
1302                }
1303                case MCS_GIVE_UP: {
1304                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1305                    HandlerParams params = mPendingInstalls.remove(0);
1306                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1307                            System.identityHashCode(params));
1308                    break;
1309                }
1310                case SEND_PENDING_BROADCAST: {
1311                    String packages[];
1312                    ArrayList<String> components[];
1313                    int size = 0;
1314                    int uids[];
1315                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1316                    synchronized (mPackages) {
1317                        if (mPendingBroadcasts == null) {
1318                            return;
1319                        }
1320                        size = mPendingBroadcasts.size();
1321                        if (size <= 0) {
1322                            // Nothing to be done. Just return
1323                            return;
1324                        }
1325                        packages = new String[size];
1326                        components = new ArrayList[size];
1327                        uids = new int[size];
1328                        int i = 0;  // filling out the above arrays
1329
1330                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1331                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1332                            Iterator<Map.Entry<String, ArrayList<String>>> it
1333                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1334                                            .entrySet().iterator();
1335                            while (it.hasNext() && i < size) {
1336                                Map.Entry<String, ArrayList<String>> ent = it.next();
1337                                packages[i] = ent.getKey();
1338                                components[i] = ent.getValue();
1339                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1340                                uids[i] = (ps != null)
1341                                        ? UserHandle.getUid(packageUserId, ps.appId)
1342                                        : -1;
1343                                i++;
1344                            }
1345                        }
1346                        size = i;
1347                        mPendingBroadcasts.clear();
1348                    }
1349                    // Send broadcasts
1350                    for (int i = 0; i < size; i++) {
1351                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1352                    }
1353                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1354                    break;
1355                }
1356                case START_CLEANING_PACKAGE: {
1357                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1358                    final String packageName = (String)msg.obj;
1359                    final int userId = msg.arg1;
1360                    final boolean andCode = msg.arg2 != 0;
1361                    synchronized (mPackages) {
1362                        if (userId == UserHandle.USER_ALL) {
1363                            int[] users = sUserManager.getUserIds();
1364                            for (int user : users) {
1365                                mSettings.addPackageToCleanLPw(
1366                                        new PackageCleanItem(user, packageName, andCode));
1367                            }
1368                        } else {
1369                            mSettings.addPackageToCleanLPw(
1370                                    new PackageCleanItem(userId, packageName, andCode));
1371                        }
1372                    }
1373                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1374                    startCleaningPackages();
1375                } break;
1376                case POST_INSTALL: {
1377                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1378
1379                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1380                    mRunningInstalls.delete(msg.arg1);
1381                    boolean deleteOld = false;
1382
1383                    if (data != null) {
1384                        InstallArgs args = data.args;
1385                        PackageInstalledInfo res = data.res;
1386
1387                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1388                            final String packageName = res.pkg.applicationInfo.packageName;
1389                            res.removedInfo.sendBroadcast(false, true, false);
1390                            Bundle extras = new Bundle(1);
1391                            extras.putInt(Intent.EXTRA_UID, res.uid);
1392
1393                            // Now that we successfully installed the package, grant runtime
1394                            // permissions if requested before broadcasting the install.
1395                            if ((args.installFlags
1396                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1397                                    && res.pkg.applicationInfo.targetSdkVersion
1398                                            >= Build.VERSION_CODES.M) {
1399                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1400                                        args.installGrantPermissions);
1401                            }
1402
1403                            synchronized (mPackages) {
1404                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1405                            }
1406
1407                            // Determine the set of users who are adding this
1408                            // package for the first time vs. those who are seeing
1409                            // an update.
1410                            int[] firstUsers;
1411                            int[] updateUsers = new int[0];
1412                            if (res.origUsers == null || res.origUsers.length == 0) {
1413                                firstUsers = res.newUsers;
1414                            } else {
1415                                firstUsers = new int[0];
1416                                for (int i=0; i<res.newUsers.length; i++) {
1417                                    int user = res.newUsers[i];
1418                                    boolean isNew = true;
1419                                    for (int j=0; j<res.origUsers.length; j++) {
1420                                        if (res.origUsers[j] == user) {
1421                                            isNew = false;
1422                                            break;
1423                                        }
1424                                    }
1425                                    if (isNew) {
1426                                        int[] newFirst = new int[firstUsers.length+1];
1427                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1428                                                firstUsers.length);
1429                                        newFirst[firstUsers.length] = user;
1430                                        firstUsers = newFirst;
1431                                    } else {
1432                                        int[] newUpdate = new int[updateUsers.length+1];
1433                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1434                                                updateUsers.length);
1435                                        newUpdate[updateUsers.length] = user;
1436                                        updateUsers = newUpdate;
1437                                    }
1438                                }
1439                            }
1440                            // don't broadcast for ephemeral installs/updates
1441                            final boolean isEphemeral = isEphemeral(res.pkg);
1442                            if (!isEphemeral) {
1443                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1444                                        extras, 0 /*flags*/, null /*targetPackage*/,
1445                                        null /*finishedReceiver*/, firstUsers);
1446                            }
1447                            final boolean update = res.removedInfo.removedPackage != null;
1448                            if (update) {
1449                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1450                            }
1451                            if (!isEphemeral) {
1452                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1453                                        extras, 0 /*flags*/, null /*targetPackage*/,
1454                                        null /*finishedReceiver*/, updateUsers);
1455                            }
1456                            if (update) {
1457                                if (!isEphemeral) {
1458                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1459                                            packageName, extras, 0 /*flags*/,
1460                                            null /*targetPackage*/, null /*finishedReceiver*/,
1461                                            updateUsers);
1462                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1463                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1464                                            packageName /*targetPackage*/,
1465                                            null /*finishedReceiver*/, updateUsers);
1466                                }
1467
1468                                // treat asec-hosted packages like removable media on upgrade
1469                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1470                                    if (DEBUG_INSTALL) {
1471                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1472                                                + " is ASEC-hosted -> AVAILABLE");
1473                                    }
1474                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1475                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1476                                    pkgList.add(packageName);
1477                                    sendResourcesChangedBroadcast(true, true,
1478                                            pkgList,uidArray, null);
1479                                }
1480                            }
1481                            if (res.removedInfo.args != null) {
1482                                // Remove the replaced package's older resources safely now
1483                                deleteOld = true;
1484                            }
1485
1486                            // If this app is a browser and it's newly-installed for some
1487                            // users, clear any default-browser state in those users
1488                            if (firstUsers.length > 0) {
1489                                // the app's nature doesn't depend on the user, so we can just
1490                                // check its browser nature in any user and generalize.
1491                                if (packageIsBrowser(packageName, firstUsers[0])) {
1492                                    synchronized (mPackages) {
1493                                        for (int userId : firstUsers) {
1494                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1495                                        }
1496                                    }
1497                                }
1498                            }
1499                            // Log current value of "unknown sources" setting
1500                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1501                                getUnknownSourcesSettings());
1502                        }
1503                        // Force a gc to clear up things
1504                        Runtime.getRuntime().gc();
1505                        // We delete after a gc for applications  on sdcard.
1506                        if (deleteOld) {
1507                            synchronized (mInstallLock) {
1508                                res.removedInfo.args.doPostDeleteLI(true);
1509                            }
1510                        }
1511                        if (args.observer != null) {
1512                            try {
1513                                Bundle extras = extrasForInstallResult(res);
1514                                args.observer.onPackageInstalled(res.name, res.returnCode,
1515                                        res.returnMsg, extras);
1516                            } catch (RemoteException e) {
1517                                Slog.i(TAG, "Observer no longer exists.");
1518                            }
1519                        }
1520                        if (args.traceMethod != null) {
1521                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1522                                    args.traceCookie);
1523                        }
1524                        return;
1525                    } else {
1526                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1527                    }
1528
1529                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1530                } break;
1531                case UPDATED_MEDIA_STATUS: {
1532                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1533                    boolean reportStatus = msg.arg1 == 1;
1534                    boolean doGc = msg.arg2 == 1;
1535                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1536                    if (doGc) {
1537                        // Force a gc to clear up stale containers.
1538                        Runtime.getRuntime().gc();
1539                    }
1540                    if (msg.obj != null) {
1541                        @SuppressWarnings("unchecked")
1542                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1543                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1544                        // Unload containers
1545                        unloadAllContainers(args);
1546                    }
1547                    if (reportStatus) {
1548                        try {
1549                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1550                            PackageHelper.getMountService().finishMediaUpdate();
1551                        } catch (RemoteException e) {
1552                            Log.e(TAG, "MountService not running?");
1553                        }
1554                    }
1555                } break;
1556                case WRITE_SETTINGS: {
1557                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1558                    synchronized (mPackages) {
1559                        removeMessages(WRITE_SETTINGS);
1560                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1561                        mSettings.writeLPr();
1562                        mDirtyUsers.clear();
1563                    }
1564                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1565                } break;
1566                case WRITE_PACKAGE_RESTRICTIONS: {
1567                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1568                    synchronized (mPackages) {
1569                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1570                        for (int userId : mDirtyUsers) {
1571                            mSettings.writePackageRestrictionsLPr(userId);
1572                        }
1573                        mDirtyUsers.clear();
1574                    }
1575                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1576                } break;
1577                case CHECK_PENDING_VERIFICATION: {
1578                    final int verificationId = msg.arg1;
1579                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1580
1581                    if ((state != null) && !state.timeoutExtended()) {
1582                        final InstallArgs args = state.getInstallArgs();
1583                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1584
1585                        Slog.i(TAG, "Verification timed out for " + originUri);
1586                        mPendingVerification.remove(verificationId);
1587
1588                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1589
1590                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1591                            Slog.i(TAG, "Continuing with installation of " + originUri);
1592                            state.setVerifierResponse(Binder.getCallingUid(),
1593                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1594                            broadcastPackageVerified(verificationId, originUri,
1595                                    PackageManager.VERIFICATION_ALLOW,
1596                                    state.getInstallArgs().getUser());
1597                            try {
1598                                ret = args.copyApk(mContainerService, true);
1599                            } catch (RemoteException e) {
1600                                Slog.e(TAG, "Could not contact the ContainerService");
1601                            }
1602                        } else {
1603                            broadcastPackageVerified(verificationId, originUri,
1604                                    PackageManager.VERIFICATION_REJECT,
1605                                    state.getInstallArgs().getUser());
1606                        }
1607
1608                        Trace.asyncTraceEnd(
1609                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1610
1611                        processPendingInstall(args, ret);
1612                        mHandler.sendEmptyMessage(MCS_UNBIND);
1613                    }
1614                    break;
1615                }
1616                case PACKAGE_VERIFIED: {
1617                    final int verificationId = msg.arg1;
1618
1619                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1620                    if (state == null) {
1621                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1622                        break;
1623                    }
1624
1625                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1626
1627                    state.setVerifierResponse(response.callerUid, response.code);
1628
1629                    if (state.isVerificationComplete()) {
1630                        mPendingVerification.remove(verificationId);
1631
1632                        final InstallArgs args = state.getInstallArgs();
1633                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1634
1635                        int ret;
1636                        if (state.isInstallAllowed()) {
1637                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1638                            broadcastPackageVerified(verificationId, originUri,
1639                                    response.code, state.getInstallArgs().getUser());
1640                            try {
1641                                ret = args.copyApk(mContainerService, true);
1642                            } catch (RemoteException e) {
1643                                Slog.e(TAG, "Could not contact the ContainerService");
1644                            }
1645                        } else {
1646                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1647                        }
1648
1649                        Trace.asyncTraceEnd(
1650                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1651
1652                        processPendingInstall(args, ret);
1653                        mHandler.sendEmptyMessage(MCS_UNBIND);
1654                    }
1655
1656                    break;
1657                }
1658                case START_INTENT_FILTER_VERIFICATIONS: {
1659                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1660                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1661                            params.replacing, params.pkg);
1662                    break;
1663                }
1664                case INTENT_FILTER_VERIFIED: {
1665                    final int verificationId = msg.arg1;
1666
1667                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1668                            verificationId);
1669                    if (state == null) {
1670                        Slog.w(TAG, "Invalid IntentFilter verification token "
1671                                + verificationId + " received");
1672                        break;
1673                    }
1674
1675                    final int userId = state.getUserId();
1676
1677                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1678                            "Processing IntentFilter verification with token:"
1679                            + verificationId + " and userId:" + userId);
1680
1681                    final IntentFilterVerificationResponse response =
1682                            (IntentFilterVerificationResponse) msg.obj;
1683
1684                    state.setVerifierResponse(response.callerUid, response.code);
1685
1686                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1687                            "IntentFilter verification with token:" + verificationId
1688                            + " and userId:" + userId
1689                            + " is settings verifier response with response code:"
1690                            + response.code);
1691
1692                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1693                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1694                                + response.getFailedDomainsString());
1695                    }
1696
1697                    if (state.isVerificationComplete()) {
1698                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1699                    } else {
1700                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1701                                "IntentFilter verification with token:" + verificationId
1702                                + " was not said to be complete");
1703                    }
1704
1705                    break;
1706                }
1707            }
1708        }
1709    }
1710
1711    private StorageEventListener mStorageListener = new StorageEventListener() {
1712        @Override
1713        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1714            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1715                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1716                    final String volumeUuid = vol.getFsUuid();
1717
1718                    // Clean up any users or apps that were removed or recreated
1719                    // while this volume was missing
1720                    reconcileUsers(volumeUuid);
1721                    reconcileApps(volumeUuid);
1722
1723                    // Clean up any install sessions that expired or were
1724                    // cancelled while this volume was missing
1725                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1726
1727                    loadPrivatePackages(vol);
1728
1729                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1730                    unloadPrivatePackages(vol);
1731                }
1732            }
1733
1734            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1735                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1736                    updateExternalMediaStatus(true, false);
1737                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1738                    updateExternalMediaStatus(false, false);
1739                }
1740            }
1741        }
1742
1743        @Override
1744        public void onVolumeForgotten(String fsUuid) {
1745            if (TextUtils.isEmpty(fsUuid)) {
1746                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1747                return;
1748            }
1749
1750            // Remove any apps installed on the forgotten volume
1751            synchronized (mPackages) {
1752                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1753                for (PackageSetting ps : packages) {
1754                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1755                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1756                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1757                }
1758
1759                mSettings.onVolumeForgotten(fsUuid);
1760                mSettings.writeLPr();
1761            }
1762        }
1763    };
1764
1765    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1766            String[] grantedPermissions) {
1767        if (userId >= UserHandle.USER_SYSTEM) {
1768            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1769        } else if (userId == UserHandle.USER_ALL) {
1770            final int[] userIds;
1771            synchronized (mPackages) {
1772                userIds = UserManagerService.getInstance().getUserIds();
1773            }
1774            for (int someUserId : userIds) {
1775                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1776            }
1777        }
1778
1779        // We could have touched GID membership, so flush out packages.list
1780        synchronized (mPackages) {
1781            mSettings.writePackageListLPr();
1782        }
1783    }
1784
1785    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1786            String[] grantedPermissions) {
1787        SettingBase sb = (SettingBase) pkg.mExtras;
1788        if (sb == null) {
1789            return;
1790        }
1791
1792        PermissionsState permissionsState = sb.getPermissionsState();
1793
1794        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1795                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1796
1797        synchronized (mPackages) {
1798            for (String permission : pkg.requestedPermissions) {
1799                BasePermission bp = mSettings.mPermissions.get(permission);
1800                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1801                        && (grantedPermissions == null
1802                               || ArrayUtils.contains(grantedPermissions, permission))) {
1803                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1804                    // Installer cannot change immutable permissions.
1805                    if ((flags & immutableFlags) == 0) {
1806                        grantRuntimePermission(pkg.packageName, permission, userId);
1807                    }
1808                }
1809            }
1810        }
1811    }
1812
1813    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1814        Bundle extras = null;
1815        switch (res.returnCode) {
1816            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1817                extras = new Bundle();
1818                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1819                        res.origPermission);
1820                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1821                        res.origPackage);
1822                break;
1823            }
1824            case PackageManager.INSTALL_SUCCEEDED: {
1825                extras = new Bundle();
1826                extras.putBoolean(Intent.EXTRA_REPLACING,
1827                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1828                break;
1829            }
1830        }
1831        return extras;
1832    }
1833
1834    void scheduleWriteSettingsLocked() {
1835        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1836            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1837        }
1838    }
1839
1840    void scheduleWritePackageRestrictionsLocked(int userId) {
1841        if (!sUserManager.exists(userId)) return;
1842        mDirtyUsers.add(userId);
1843        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1844            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1845        }
1846    }
1847
1848    public static PackageManagerService main(Context context, Installer installer,
1849            boolean factoryTest, boolean onlyCore) {
1850        PackageManagerService m = new PackageManagerService(context, installer,
1851                factoryTest, onlyCore);
1852        m.enableSystemUserApps();
1853        ServiceManager.addService("package", m);
1854        return m;
1855    }
1856
1857    private void enableSystemUserApps() {
1858        if (!UserManager.isSplitSystemUser()) {
1859            return;
1860        }
1861        // For system user, enable apps based on the following conditions:
1862        // - app is whitelisted or belong to one of these groups:
1863        //   -- system app which has no launcher icons
1864        //   -- system app which has INTERACT_ACROSS_USERS permission
1865        //   -- system IME app
1866        // - app is not in the blacklist
1867        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1868        Set<String> enableApps = new ArraySet<>();
1869        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1870                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1871                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1872        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1873        enableApps.addAll(wlApps);
1874        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1875        enableApps.removeAll(blApps);
1876
1877        List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true,
1878                UserHandle.SYSTEM);
1879        final int systemAppsSize = systemApps.size();
1880        synchronized (mPackages) {
1881            for (int i = 0; i < systemAppsSize; i++) {
1882                String pName = systemApps.get(i);
1883                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1884                // Should not happen, but we shouldn't be failing if it does
1885                if (pkgSetting == null) {
1886                    continue;
1887                }
1888                boolean installed = enableApps.contains(pName);
1889                pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM);
1890            }
1891        }
1892    }
1893
1894    static String[] splitString(String str, char sep) {
1895        int count = 1;
1896        int i = 0;
1897        while ((i=str.indexOf(sep, i)) >= 0) {
1898            count++;
1899            i++;
1900        }
1901
1902        String[] res = new String[count];
1903        i=0;
1904        count = 0;
1905        int lastI=0;
1906        while ((i=str.indexOf(sep, i)) >= 0) {
1907            res[count] = str.substring(lastI, i);
1908            count++;
1909            i++;
1910            lastI = i;
1911        }
1912        res[count] = str.substring(lastI, str.length());
1913        return res;
1914    }
1915
1916    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1917        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1918                Context.DISPLAY_SERVICE);
1919        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1920    }
1921
1922    public PackageManagerService(Context context, Installer installer,
1923            boolean factoryTest, boolean onlyCore) {
1924        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1925                SystemClock.uptimeMillis());
1926
1927        if (mSdkVersion <= 0) {
1928            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1929        }
1930
1931        mContext = context;
1932        mFactoryTest = factoryTest;
1933        mOnlyCore = onlyCore;
1934        mMetrics = new DisplayMetrics();
1935        mSettings = new Settings(mPackages);
1936        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1937                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1938        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1939                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1940        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1941                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1942        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1943                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1944        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1945                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1946        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1947                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1948
1949        String separateProcesses = SystemProperties.get("debug.separate_processes");
1950        if (separateProcesses != null && separateProcesses.length() > 0) {
1951            if ("*".equals(separateProcesses)) {
1952                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1953                mSeparateProcesses = null;
1954                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1955            } else {
1956                mDefParseFlags = 0;
1957                mSeparateProcesses = separateProcesses.split(",");
1958                Slog.w(TAG, "Running with debug.separate_processes: "
1959                        + separateProcesses);
1960            }
1961        } else {
1962            mDefParseFlags = 0;
1963            mSeparateProcesses = null;
1964        }
1965
1966        mInstaller = installer;
1967        mPackageDexOptimizer = new PackageDexOptimizer(this);
1968        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1969
1970        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1971                FgThread.get().getLooper());
1972
1973        getDefaultDisplayMetrics(context, mMetrics);
1974
1975        SystemConfig systemConfig = SystemConfig.getInstance();
1976        mGlobalGids = systemConfig.getGlobalGids();
1977        mSystemPermissions = systemConfig.getSystemPermissions();
1978        mAvailableFeatures = systemConfig.getAvailableFeatures();
1979
1980        synchronized (mInstallLock) {
1981        // writer
1982        synchronized (mPackages) {
1983            mHandlerThread = new ServiceThread(TAG,
1984                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1985            mHandlerThread.start();
1986            mHandler = new PackageHandler(mHandlerThread.getLooper());
1987            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1988
1989            File dataDir = Environment.getDataDirectory();
1990            mAppDataDir = new File(dataDir, "data");
1991            mAppInstallDir = new File(dataDir, "app");
1992            mAppLib32InstallDir = new File(dataDir, "app-lib");
1993            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1994            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1995            mUserAppDataDir = new File(dataDir, "user");
1996            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1997
1998            sUserManager = new UserManagerService(context, this, mPackages);
1999
2000            // Propagate permission configuration in to package manager.
2001            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2002                    = systemConfig.getPermissions();
2003            for (int i=0; i<permConfig.size(); i++) {
2004                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2005                BasePermission bp = mSettings.mPermissions.get(perm.name);
2006                if (bp == null) {
2007                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2008                    mSettings.mPermissions.put(perm.name, bp);
2009                }
2010                if (perm.gids != null) {
2011                    bp.setGids(perm.gids, perm.perUser);
2012                }
2013            }
2014
2015            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2016            for (int i=0; i<libConfig.size(); i++) {
2017                mSharedLibraries.put(libConfig.keyAt(i),
2018                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2019            }
2020
2021            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2022
2023            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2024
2025            String customResolverActivity = Resources.getSystem().getString(
2026                    R.string.config_customResolverActivity);
2027            if (TextUtils.isEmpty(customResolverActivity)) {
2028                customResolverActivity = null;
2029            } else {
2030                mCustomResolverComponentName = ComponentName.unflattenFromString(
2031                        customResolverActivity);
2032            }
2033
2034            long startTime = SystemClock.uptimeMillis();
2035
2036            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2037                    startTime);
2038
2039            // Set flag to monitor and not change apk file paths when
2040            // scanning install directories.
2041            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2042
2043            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2044            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2045
2046            if (bootClassPath == null) {
2047                Slog.w(TAG, "No BOOTCLASSPATH found!");
2048            }
2049
2050            if (systemServerClassPath == null) {
2051                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2052            }
2053
2054            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2055            final String[] dexCodeInstructionSets =
2056                    getDexCodeInstructionSets(
2057                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2058
2059            /**
2060             * Ensure all external libraries have had dexopt run on them.
2061             */
2062            if (mSharedLibraries.size() > 0) {
2063                // NOTE: For now, we're compiling these system "shared libraries"
2064                // (and framework jars) into all available architectures. It's possible
2065                // to compile them only when we come across an app that uses them (there's
2066                // already logic for that in scanPackageLI) but that adds some complexity.
2067                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2068                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2069                        final String lib = libEntry.path;
2070                        if (lib == null) {
2071                            continue;
2072                        }
2073
2074                        try {
2075                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2076                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2077                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2078                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2079                            }
2080                        } catch (FileNotFoundException e) {
2081                            Slog.w(TAG, "Library not found: " + lib);
2082                        } catch (IOException e) {
2083                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2084                                    + e.getMessage());
2085                        }
2086                    }
2087                }
2088            }
2089
2090            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2091
2092            final VersionInfo ver = mSettings.getInternalVersion();
2093            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2094            // when upgrading from pre-M, promote system app permissions from install to runtime
2095            mPromoteSystemApps =
2096                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2097
2098            // save off the names of pre-existing system packages prior to scanning; we don't
2099            // want to automatically grant runtime permissions for new system apps
2100            if (mPromoteSystemApps) {
2101                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2102                while (pkgSettingIter.hasNext()) {
2103                    PackageSetting ps = pkgSettingIter.next();
2104                    if (isSystemApp(ps)) {
2105                        mExistingSystemPackages.add(ps.name);
2106                    }
2107                }
2108            }
2109
2110            // Collect vendor overlay packages.
2111            // (Do this before scanning any apps.)
2112            // For security and version matching reason, only consider
2113            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2114            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2115            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2116                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2117
2118            // Find base frameworks (resource packages without code).
2119            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2120                    | PackageParser.PARSE_IS_SYSTEM_DIR
2121                    | PackageParser.PARSE_IS_PRIVILEGED,
2122                    scanFlags | SCAN_NO_DEX, 0);
2123
2124            // Collected privileged system packages.
2125            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2126            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2127                    | PackageParser.PARSE_IS_SYSTEM_DIR
2128                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2129
2130            // Collect ordinary system packages.
2131            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2132            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2133                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2134
2135            // Collect all vendor packages.
2136            File vendorAppDir = new File("/vendor/app");
2137            try {
2138                vendorAppDir = vendorAppDir.getCanonicalFile();
2139            } catch (IOException e) {
2140                // failed to look up canonical path, continue with original one
2141            }
2142            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2143                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2144
2145            // Collect all OEM packages.
2146            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2147            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2148                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2149
2150            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2151            mInstaller.moveFiles();
2152
2153            // Prune any system packages that no longer exist.
2154            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2155            if (!mOnlyCore) {
2156                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2157                while (psit.hasNext()) {
2158                    PackageSetting ps = psit.next();
2159
2160                    /*
2161                     * If this is not a system app, it can't be a
2162                     * disable system app.
2163                     */
2164                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2165                        continue;
2166                    }
2167
2168                    /*
2169                     * If the package is scanned, it's not erased.
2170                     */
2171                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2172                    if (scannedPkg != null) {
2173                        /*
2174                         * If the system app is both scanned and in the
2175                         * disabled packages list, then it must have been
2176                         * added via OTA. Remove it from the currently
2177                         * scanned package so the previously user-installed
2178                         * application can be scanned.
2179                         */
2180                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2181                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2182                                    + ps.name + "; removing system app.  Last known codePath="
2183                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2184                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2185                                    + scannedPkg.mVersionCode);
2186                            removePackageLI(ps, true);
2187                            mExpectingBetter.put(ps.name, ps.codePath);
2188                        }
2189
2190                        continue;
2191                    }
2192
2193                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2194                        psit.remove();
2195                        logCriticalInfo(Log.WARN, "System package " + ps.name
2196                                + " no longer exists; wiping its data");
2197                        removeDataDirsLI(null, ps.name);
2198                    } else {
2199                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2200                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2201                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2202                        }
2203                    }
2204                }
2205            }
2206
2207            //look for any incomplete package installations
2208            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2209            //clean up list
2210            for(int i = 0; i < deletePkgsList.size(); i++) {
2211                //clean up here
2212                cleanupInstallFailedPackage(deletePkgsList.get(i));
2213            }
2214            //delete tmp files
2215            deleteTempPackageFiles();
2216
2217            // Remove any shared userIDs that have no associated packages
2218            mSettings.pruneSharedUsersLPw();
2219
2220            if (!mOnlyCore) {
2221                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2222                        SystemClock.uptimeMillis());
2223                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2224
2225                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2226                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2227
2228                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2229                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2230
2231                /**
2232                 * Remove disable package settings for any updated system
2233                 * apps that were removed via an OTA. If they're not a
2234                 * previously-updated app, remove them completely.
2235                 * Otherwise, just revoke their system-level permissions.
2236                 */
2237                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2238                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2239                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2240
2241                    String msg;
2242                    if (deletedPkg == null) {
2243                        msg = "Updated system package " + deletedAppName
2244                                + " no longer exists; wiping its data";
2245                        removeDataDirsLI(null, deletedAppName);
2246                    } else {
2247                        msg = "Updated system app + " + deletedAppName
2248                                + " no longer present; removing system privileges for "
2249                                + deletedAppName;
2250
2251                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2252
2253                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2254                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2255                    }
2256                    logCriticalInfo(Log.WARN, msg);
2257                }
2258
2259                /**
2260                 * Make sure all system apps that we expected to appear on
2261                 * the userdata partition actually showed up. If they never
2262                 * appeared, crawl back and revive the system version.
2263                 */
2264                for (int i = 0; i < mExpectingBetter.size(); i++) {
2265                    final String packageName = mExpectingBetter.keyAt(i);
2266                    if (!mPackages.containsKey(packageName)) {
2267                        final File scanFile = mExpectingBetter.valueAt(i);
2268
2269                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2270                                + " but never showed up; reverting to system");
2271
2272                        final int reparseFlags;
2273                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2274                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2275                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2276                                    | PackageParser.PARSE_IS_PRIVILEGED;
2277                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2278                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2279                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2280                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2281                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2282                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2283                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2284                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2285                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2286                        } else {
2287                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2288                            continue;
2289                        }
2290
2291                        mSettings.enableSystemPackageLPw(packageName);
2292
2293                        try {
2294                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2295                        } catch (PackageManagerException e) {
2296                            Slog.e(TAG, "Failed to parse original system package: "
2297                                    + e.getMessage());
2298                        }
2299                    }
2300                }
2301            }
2302            mExpectingBetter.clear();
2303
2304            // Now that we know all of the shared libraries, update all clients to have
2305            // the correct library paths.
2306            updateAllSharedLibrariesLPw();
2307
2308            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2309                // NOTE: We ignore potential failures here during a system scan (like
2310                // the rest of the commands above) because there's precious little we
2311                // can do about it. A settings error is reported, though.
2312                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2313                        false /* boot complete */);
2314            }
2315
2316            // Now that we know all the packages we are keeping,
2317            // read and update their last usage times.
2318            mPackageUsage.readLP();
2319
2320            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2321                    SystemClock.uptimeMillis());
2322            Slog.i(TAG, "Time to scan packages: "
2323                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2324                    + " seconds");
2325
2326            // If the platform SDK has changed since the last time we booted,
2327            // we need to re-grant app permission to catch any new ones that
2328            // appear.  This is really a hack, and means that apps can in some
2329            // cases get permissions that the user didn't initially explicitly
2330            // allow...  it would be nice to have some better way to handle
2331            // this situation.
2332            int updateFlags = UPDATE_PERMISSIONS_ALL;
2333            if (ver.sdkVersion != mSdkVersion) {
2334                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2335                        + mSdkVersion + "; regranting permissions for internal storage");
2336                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2337            }
2338            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2339            ver.sdkVersion = mSdkVersion;
2340
2341            // If this is the first boot or an update from pre-M, and it is a normal
2342            // boot, then we need to initialize the default preferred apps across
2343            // all defined users.
2344            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2345                for (UserInfo user : sUserManager.getUsers(true)) {
2346                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2347                    applyFactoryDefaultBrowserLPw(user.id);
2348                    primeDomainVerificationsLPw(user.id);
2349                }
2350            }
2351
2352            // If this is first boot after an OTA, and a normal boot, then
2353            // we need to clear code cache directories.
2354            if (mIsUpgrade && !onlyCore) {
2355                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2356                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2357                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2358                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2359                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2360                    }
2361                }
2362                ver.fingerprint = Build.FINGERPRINT;
2363            }
2364
2365            checkDefaultBrowser();
2366
2367            // clear only after permissions and other defaults have been updated
2368            mExistingSystemPackages.clear();
2369            mPromoteSystemApps = false;
2370
2371            // All the changes are done during package scanning.
2372            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2373
2374            // can downgrade to reader
2375            mSettings.writeLPr();
2376
2377            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2378                    SystemClock.uptimeMillis());
2379
2380            mRequiredVerifierPackage = getRequiredVerifierLPr();
2381            mRequiredInstallerPackage = getRequiredInstallerLPr();
2382
2383            mInstallerService = new PackageInstallerService(context, this);
2384
2385            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2386            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2387                    mIntentFilterVerifierComponent);
2388
2389            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2390            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2391            // both the installer and resolver must be present to enable ephemeral
2392            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2393                if (DEBUG_EPHEMERAL) {
2394                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2395                            + " installer:" + ephemeralInstallerComponent);
2396                }
2397                mEphemeralResolverComponent = ephemeralResolverComponent;
2398                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2399                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2400                mEphemeralResolverConnection =
2401                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2402            } else {
2403                if (DEBUG_EPHEMERAL) {
2404                    final String missingComponent =
2405                            (ephemeralResolverComponent == null)
2406                            ? (ephemeralInstallerComponent == null)
2407                                    ? "resolver and installer"
2408                                    : "resolver"
2409                            : "installer";
2410                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2411                }
2412                mEphemeralResolverComponent = null;
2413                mEphemeralInstallerComponent = null;
2414                mEphemeralResolverConnection = null;
2415            }
2416
2417            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2418        } // synchronized (mPackages)
2419        } // synchronized (mInstallLock)
2420
2421        // Now after opening every single application zip, make sure they
2422        // are all flushed.  Not really needed, but keeps things nice and
2423        // tidy.
2424        Runtime.getRuntime().gc();
2425
2426        // The initial scanning above does many calls into installd while
2427        // holding the mPackages lock, but we're mostly interested in yelling
2428        // once we have a booted system.
2429        mInstaller.setWarnIfHeld(mPackages);
2430
2431        // Expose private service for system components to use.
2432        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2433    }
2434
2435    @Override
2436    public boolean isFirstBoot() {
2437        return !mRestoredSettings;
2438    }
2439
2440    @Override
2441    public boolean isOnlyCoreApps() {
2442        return mOnlyCore;
2443    }
2444
2445    @Override
2446    public boolean isUpgrade() {
2447        return mIsUpgrade;
2448    }
2449
2450    private String getRequiredVerifierLPr() {
2451        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2452        // We only care about verifier that's installed under system user.
2453        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2454                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2455
2456        String requiredVerifier = null;
2457
2458        final int N = receivers.size();
2459        for (int i = 0; i < N; i++) {
2460            final ResolveInfo info = receivers.get(i);
2461
2462            if (info.activityInfo == null) {
2463                continue;
2464            }
2465
2466            final String packageName = info.activityInfo.packageName;
2467
2468            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2469                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2470                continue;
2471            }
2472
2473            if (requiredVerifier != null) {
2474                throw new RuntimeException("There can be only one required verifier");
2475            }
2476
2477            requiredVerifier = packageName;
2478        }
2479
2480        return requiredVerifier;
2481    }
2482
2483    private String getRequiredInstallerLPr() {
2484        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2485        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2486        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2487
2488        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2489                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2490
2491        String requiredInstaller = null;
2492
2493        final int N = installers.size();
2494        for (int i = 0; i < N; i++) {
2495            final ResolveInfo info = installers.get(i);
2496            final String packageName = info.activityInfo.packageName;
2497
2498            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2499                continue;
2500            }
2501
2502            if (requiredInstaller != null) {
2503                throw new RuntimeException("There must be one required installer");
2504            }
2505
2506            requiredInstaller = packageName;
2507        }
2508
2509        if (requiredInstaller == null) {
2510            throw new RuntimeException("There must be one required installer");
2511        }
2512
2513        return requiredInstaller;
2514    }
2515
2516    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2517        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2518        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2519                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2520
2521        ComponentName verifierComponentName = null;
2522
2523        int priority = -1000;
2524        final int N = receivers.size();
2525        for (int i = 0; i < N; i++) {
2526            final ResolveInfo info = receivers.get(i);
2527
2528            if (info.activityInfo == null) {
2529                continue;
2530            }
2531
2532            final String packageName = info.activityInfo.packageName;
2533
2534            final PackageSetting ps = mSettings.mPackages.get(packageName);
2535            if (ps == null) {
2536                continue;
2537            }
2538
2539            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2540                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2541                continue;
2542            }
2543
2544            // Select the IntentFilterVerifier with the highest priority
2545            if (priority < info.priority) {
2546                priority = info.priority;
2547                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2548                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2549                        + verifierComponentName + " with priority: " + info.priority);
2550            }
2551        }
2552
2553        return verifierComponentName;
2554    }
2555
2556    private ComponentName getEphemeralResolverLPr() {
2557        final String[] packageArray =
2558                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2559        if (packageArray.length == 0) {
2560            if (DEBUG_EPHEMERAL) {
2561                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2562            }
2563            return null;
2564        }
2565
2566        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2567        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2568                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2569
2570        final int N = resolvers.size();
2571        if (N == 0) {
2572            if (DEBUG_EPHEMERAL) {
2573                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2574            }
2575            return null;
2576        }
2577
2578        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2579        for (int i = 0; i < N; i++) {
2580            final ResolveInfo info = resolvers.get(i);
2581
2582            if (info.serviceInfo == null) {
2583                continue;
2584            }
2585
2586            final String packageName = info.serviceInfo.packageName;
2587            if (!possiblePackages.contains(packageName)) {
2588                if (DEBUG_EPHEMERAL) {
2589                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2590                            + " pkg: " + packageName + ", info:" + info);
2591                }
2592                continue;
2593            }
2594
2595            if (DEBUG_EPHEMERAL) {
2596                Slog.v(TAG, "Ephemeral resolver found;"
2597                        + " pkg: " + packageName + ", info:" + info);
2598            }
2599            return new ComponentName(packageName, info.serviceInfo.name);
2600        }
2601        if (DEBUG_EPHEMERAL) {
2602            Slog.v(TAG, "Ephemeral resolver NOT found");
2603        }
2604        return null;
2605    }
2606
2607    private ComponentName getEphemeralInstallerLPr() {
2608        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2609        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2610        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2611        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2612                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2613
2614        ComponentName ephemeralInstaller = null;
2615
2616        final int N = installers.size();
2617        for (int i = 0; i < N; i++) {
2618            final ResolveInfo info = installers.get(i);
2619            final String packageName = info.activityInfo.packageName;
2620
2621            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2622                if (DEBUG_EPHEMERAL) {
2623                    Slog.d(TAG, "Ephemeral installer is not system app;"
2624                            + " pkg: " + packageName + ", info:" + info);
2625                }
2626                continue;
2627            }
2628
2629            if (ephemeralInstaller != null) {
2630                throw new RuntimeException("There must only be one ephemeral installer");
2631            }
2632
2633            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2634        }
2635
2636        return ephemeralInstaller;
2637    }
2638
2639    private void primeDomainVerificationsLPw(int userId) {
2640        if (DEBUG_DOMAIN_VERIFICATION) {
2641            Slog.d(TAG, "Priming domain verifications in user " + userId);
2642        }
2643
2644        SystemConfig systemConfig = SystemConfig.getInstance();
2645        ArraySet<String> packages = systemConfig.getLinkedApps();
2646        ArraySet<String> domains = new ArraySet<String>();
2647
2648        for (String packageName : packages) {
2649            PackageParser.Package pkg = mPackages.get(packageName);
2650            if (pkg != null) {
2651                if (!pkg.isSystemApp()) {
2652                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2653                    continue;
2654                }
2655
2656                domains.clear();
2657                for (PackageParser.Activity a : pkg.activities) {
2658                    for (ActivityIntentInfo filter : a.intents) {
2659                        if (hasValidDomains(filter)) {
2660                            domains.addAll(filter.getHostsList());
2661                        }
2662                    }
2663                }
2664
2665                if (domains.size() > 0) {
2666                    if (DEBUG_DOMAIN_VERIFICATION) {
2667                        Slog.v(TAG, "      + " + packageName);
2668                    }
2669                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2670                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2671                    // and then 'always' in the per-user state actually used for intent resolution.
2672                    final IntentFilterVerificationInfo ivi;
2673                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2674                            new ArrayList<String>(domains));
2675                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2676                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2677                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2678                } else {
2679                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2680                            + "' does not handle web links");
2681                }
2682            } else {
2683                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2684            }
2685        }
2686
2687        scheduleWritePackageRestrictionsLocked(userId);
2688        scheduleWriteSettingsLocked();
2689    }
2690
2691    private void applyFactoryDefaultBrowserLPw(int userId) {
2692        // The default browser app's package name is stored in a string resource,
2693        // with a product-specific overlay used for vendor customization.
2694        String browserPkg = mContext.getResources().getString(
2695                com.android.internal.R.string.default_browser);
2696        if (!TextUtils.isEmpty(browserPkg)) {
2697            // non-empty string => required to be a known package
2698            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2699            if (ps == null) {
2700                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2701                browserPkg = null;
2702            } else {
2703                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2704            }
2705        }
2706
2707        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2708        // default.  If there's more than one, just leave everything alone.
2709        if (browserPkg == null) {
2710            calculateDefaultBrowserLPw(userId);
2711        }
2712    }
2713
2714    private void calculateDefaultBrowserLPw(int userId) {
2715        List<String> allBrowsers = resolveAllBrowserApps(userId);
2716        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2717        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2718    }
2719
2720    private List<String> resolveAllBrowserApps(int userId) {
2721        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2722        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2723                PackageManager.MATCH_ALL, userId);
2724
2725        final int count = list.size();
2726        List<String> result = new ArrayList<String>(count);
2727        for (int i=0; i<count; i++) {
2728            ResolveInfo info = list.get(i);
2729            if (info.activityInfo == null
2730                    || !info.handleAllWebDataURI
2731                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2732                    || result.contains(info.activityInfo.packageName)) {
2733                continue;
2734            }
2735            result.add(info.activityInfo.packageName);
2736        }
2737
2738        return result;
2739    }
2740
2741    private boolean packageIsBrowser(String packageName, int userId) {
2742        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2743                PackageManager.MATCH_ALL, userId);
2744        final int N = list.size();
2745        for (int i = 0; i < N; i++) {
2746            ResolveInfo info = list.get(i);
2747            if (packageName.equals(info.activityInfo.packageName)) {
2748                return true;
2749            }
2750        }
2751        return false;
2752    }
2753
2754    private void checkDefaultBrowser() {
2755        final int myUserId = UserHandle.myUserId();
2756        final String packageName = getDefaultBrowserPackageName(myUserId);
2757        if (packageName != null) {
2758            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2759            if (info == null) {
2760                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2761                synchronized (mPackages) {
2762                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2763                }
2764            }
2765        }
2766    }
2767
2768    @Override
2769    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2770            throws RemoteException {
2771        try {
2772            return super.onTransact(code, data, reply, flags);
2773        } catch (RuntimeException e) {
2774            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2775                Slog.wtf(TAG, "Package Manager Crash", e);
2776            }
2777            throw e;
2778        }
2779    }
2780
2781    void cleanupInstallFailedPackage(PackageSetting ps) {
2782        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2783
2784        removeDataDirsLI(ps.volumeUuid, ps.name);
2785        if (ps.codePath != null) {
2786            if (ps.codePath.isDirectory()) {
2787                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2788            } else {
2789                ps.codePath.delete();
2790            }
2791        }
2792        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2793            if (ps.resourcePath.isDirectory()) {
2794                FileUtils.deleteContents(ps.resourcePath);
2795            }
2796            ps.resourcePath.delete();
2797        }
2798        mSettings.removePackageLPw(ps.name);
2799    }
2800
2801    static int[] appendInts(int[] cur, int[] add) {
2802        if (add == null) return cur;
2803        if (cur == null) return add;
2804        final int N = add.length;
2805        for (int i=0; i<N; i++) {
2806            cur = appendInt(cur, add[i]);
2807        }
2808        return cur;
2809    }
2810
2811    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2812        if (!sUserManager.exists(userId)) return null;
2813        final PackageSetting ps = (PackageSetting) p.mExtras;
2814        if (ps == null) {
2815            return null;
2816        }
2817
2818        final PermissionsState permissionsState = ps.getPermissionsState();
2819
2820        final int[] gids = permissionsState.computeGids(userId);
2821        final Set<String> permissions = permissionsState.getPermissions(userId);
2822        final PackageUserState state = ps.readUserState(userId);
2823
2824        return PackageParser.generatePackageInfo(p, gids, flags,
2825                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2826    }
2827
2828    @Override
2829    public void checkPackageStartable(String packageName, int userId) {
2830        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2831
2832        synchronized (mPackages) {
2833            final PackageSetting ps = mSettings.mPackages.get(packageName);
2834            if (ps == null) {
2835                throw new SecurityException("Package " + packageName + " was not found!");
2836            }
2837
2838            if (ps.frozen) {
2839                throw new SecurityException("Package " + packageName + " is currently frozen!");
2840            }
2841
2842            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2843                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2844                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2845            }
2846        }
2847    }
2848
2849    @Override
2850    public boolean isPackageAvailable(String packageName, int userId) {
2851        if (!sUserManager.exists(userId)) return false;
2852        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2853        synchronized (mPackages) {
2854            PackageParser.Package p = mPackages.get(packageName);
2855            if (p != null) {
2856                final PackageSetting ps = (PackageSetting) p.mExtras;
2857                if (ps != null) {
2858                    final PackageUserState state = ps.readUserState(userId);
2859                    if (state != null) {
2860                        return PackageParser.isAvailable(state);
2861                    }
2862                }
2863            }
2864        }
2865        return false;
2866    }
2867
2868    @Override
2869    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2870        if (!sUserManager.exists(userId)) return null;
2871        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2872        // reader
2873        synchronized (mPackages) {
2874            PackageParser.Package p = mPackages.get(packageName);
2875            if (DEBUG_PACKAGE_INFO)
2876                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2877            if (p != null) {
2878                return generatePackageInfo(p, flags, userId);
2879            }
2880            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2881                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2882            }
2883        }
2884        return null;
2885    }
2886
2887    @Override
2888    public String[] currentToCanonicalPackageNames(String[] names) {
2889        String[] out = new String[names.length];
2890        // reader
2891        synchronized (mPackages) {
2892            for (int i=names.length-1; i>=0; i--) {
2893                PackageSetting ps = mSettings.mPackages.get(names[i]);
2894                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2895            }
2896        }
2897        return out;
2898    }
2899
2900    @Override
2901    public String[] canonicalToCurrentPackageNames(String[] names) {
2902        String[] out = new String[names.length];
2903        // reader
2904        synchronized (mPackages) {
2905            for (int i=names.length-1; i>=0; i--) {
2906                String cur = mSettings.mRenamedPackages.get(names[i]);
2907                out[i] = cur != null ? cur : names[i];
2908            }
2909        }
2910        return out;
2911    }
2912
2913    @Override
2914    public int getPackageUid(String packageName, int userId) {
2915        return getPackageUidEtc(packageName, 0, userId);
2916    }
2917
2918    @Override
2919    public int getPackageUidEtc(String packageName, int flags, int userId) {
2920        if (!sUserManager.exists(userId)) return -1;
2921        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2922
2923        // reader
2924        synchronized (mPackages) {
2925            final PackageParser.Package p = mPackages.get(packageName);
2926            if (p != null) {
2927                return UserHandle.getUid(userId, p.applicationInfo.uid);
2928            }
2929            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2930                final PackageSetting ps = mSettings.mPackages.get(packageName);
2931                if (ps != null) {
2932                    return UserHandle.getUid(userId, ps.appId);
2933                }
2934            }
2935        }
2936
2937        return -1;
2938    }
2939
2940    @Override
2941    public int[] getPackageGids(String packageName, int userId) {
2942        return getPackageGidsEtc(packageName, 0, userId);
2943    }
2944
2945    @Override
2946    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2947        if (!sUserManager.exists(userId)) {
2948            return null;
2949        }
2950
2951        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2952                "getPackageGids");
2953
2954        // reader
2955        synchronized (mPackages) {
2956            final PackageParser.Package p = mPackages.get(packageName);
2957            if (p != null) {
2958                PackageSetting ps = (PackageSetting) p.mExtras;
2959                return ps.getPermissionsState().computeGids(userId);
2960            }
2961            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2962                final PackageSetting ps = mSettings.mPackages.get(packageName);
2963                if (ps != null) {
2964                    return ps.getPermissionsState().computeGids(userId);
2965                }
2966            }
2967        }
2968
2969        return null;
2970    }
2971
2972    static PermissionInfo generatePermissionInfo(
2973            BasePermission bp, int flags) {
2974        if (bp.perm != null) {
2975            return PackageParser.generatePermissionInfo(bp.perm, flags);
2976        }
2977        PermissionInfo pi = new PermissionInfo();
2978        pi.name = bp.name;
2979        pi.packageName = bp.sourcePackage;
2980        pi.nonLocalizedLabel = bp.name;
2981        pi.protectionLevel = bp.protectionLevel;
2982        return pi;
2983    }
2984
2985    @Override
2986    public PermissionInfo getPermissionInfo(String name, int flags) {
2987        // reader
2988        synchronized (mPackages) {
2989            final BasePermission p = mSettings.mPermissions.get(name);
2990            if (p != null) {
2991                return generatePermissionInfo(p, flags);
2992            }
2993            return null;
2994        }
2995    }
2996
2997    @Override
2998    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2999        // reader
3000        synchronized (mPackages) {
3001            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3002            for (BasePermission p : mSettings.mPermissions.values()) {
3003                if (group == null) {
3004                    if (p.perm == null || p.perm.info.group == null) {
3005                        out.add(generatePermissionInfo(p, flags));
3006                    }
3007                } else {
3008                    if (p.perm != null && group.equals(p.perm.info.group)) {
3009                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3010                    }
3011                }
3012            }
3013
3014            if (out.size() > 0) {
3015                return out;
3016            }
3017            return mPermissionGroups.containsKey(group) ? out : null;
3018        }
3019    }
3020
3021    @Override
3022    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3023        // reader
3024        synchronized (mPackages) {
3025            return PackageParser.generatePermissionGroupInfo(
3026                    mPermissionGroups.get(name), flags);
3027        }
3028    }
3029
3030    @Override
3031    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3032        // reader
3033        synchronized (mPackages) {
3034            final int N = mPermissionGroups.size();
3035            ArrayList<PermissionGroupInfo> out
3036                    = new ArrayList<PermissionGroupInfo>(N);
3037            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3038                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3039            }
3040            return out;
3041        }
3042    }
3043
3044    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3045            int userId) {
3046        if (!sUserManager.exists(userId)) return null;
3047        PackageSetting ps = mSettings.mPackages.get(packageName);
3048        if (ps != null) {
3049            if (ps.pkg == null) {
3050                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3051                        flags, userId);
3052                if (pInfo != null) {
3053                    return pInfo.applicationInfo;
3054                }
3055                return null;
3056            }
3057            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3058                    ps.readUserState(userId), userId);
3059        }
3060        return null;
3061    }
3062
3063    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3064            int userId) {
3065        if (!sUserManager.exists(userId)) return null;
3066        PackageSetting ps = mSettings.mPackages.get(packageName);
3067        if (ps != null) {
3068            PackageParser.Package pkg = ps.pkg;
3069            if (pkg == null) {
3070                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3071                    return null;
3072                }
3073                // Only data remains, so we aren't worried about code paths
3074                pkg = new PackageParser.Package(packageName);
3075                pkg.applicationInfo.packageName = packageName;
3076                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3077                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3078                pkg.applicationInfo.uid = ps.appId;
3079                pkg.applicationInfo.initForUser(userId);
3080                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3081                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3082            }
3083            return generatePackageInfo(pkg, flags, userId);
3084        }
3085        return null;
3086    }
3087
3088    @Override
3089    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3090        if (!sUserManager.exists(userId)) return null;
3091        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3092        // writer
3093        synchronized (mPackages) {
3094            PackageParser.Package p = mPackages.get(packageName);
3095            if (DEBUG_PACKAGE_INFO) Log.v(
3096                    TAG, "getApplicationInfo " + packageName
3097                    + ": " + p);
3098            if (p != null) {
3099                PackageSetting ps = mSettings.mPackages.get(packageName);
3100                if (ps == null) return null;
3101                // Note: isEnabledLP() does not apply here - always return info
3102                return PackageParser.generateApplicationInfo(
3103                        p, flags, ps.readUserState(userId), userId);
3104            }
3105            if ("android".equals(packageName)||"system".equals(packageName)) {
3106                return mAndroidApplication;
3107            }
3108            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3109                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3110            }
3111        }
3112        return null;
3113    }
3114
3115    @Override
3116    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3117            final IPackageDataObserver observer) {
3118        mContext.enforceCallingOrSelfPermission(
3119                android.Manifest.permission.CLEAR_APP_CACHE, null);
3120        // Queue up an async operation since clearing cache may take a little while.
3121        mHandler.post(new Runnable() {
3122            public void run() {
3123                mHandler.removeCallbacks(this);
3124                int retCode = -1;
3125                synchronized (mInstallLock) {
3126                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3127                    if (retCode < 0) {
3128                        Slog.w(TAG, "Couldn't clear application caches");
3129                    }
3130                }
3131                if (observer != null) {
3132                    try {
3133                        observer.onRemoveCompleted(null, (retCode >= 0));
3134                    } catch (RemoteException e) {
3135                        Slog.w(TAG, "RemoveException when invoking call back");
3136                    }
3137                }
3138            }
3139        });
3140    }
3141
3142    @Override
3143    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3144            final IntentSender pi) {
3145        mContext.enforceCallingOrSelfPermission(
3146                android.Manifest.permission.CLEAR_APP_CACHE, null);
3147        // Queue up an async operation since clearing cache may take a little while.
3148        mHandler.post(new Runnable() {
3149            public void run() {
3150                mHandler.removeCallbacks(this);
3151                int retCode = -1;
3152                synchronized (mInstallLock) {
3153                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3154                    if (retCode < 0) {
3155                        Slog.w(TAG, "Couldn't clear application caches");
3156                    }
3157                }
3158                if(pi != null) {
3159                    try {
3160                        // Callback via pending intent
3161                        int code = (retCode >= 0) ? 1 : 0;
3162                        pi.sendIntent(null, code, null,
3163                                null, null);
3164                    } catch (SendIntentException e1) {
3165                        Slog.i(TAG, "Failed to send pending intent");
3166                    }
3167                }
3168            }
3169        });
3170    }
3171
3172    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3173        synchronized (mInstallLock) {
3174            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3175                throw new IOException("Failed to free enough space");
3176            }
3177        }
3178    }
3179
3180    /**
3181     * Return if the user key is currently unlocked.
3182     */
3183    private boolean isUserKeyUnlocked(int userId) {
3184        if (StorageManager.isFileBasedEncryptionEnabled()) {
3185            final IMountService mount = IMountService.Stub
3186                    .asInterface(ServiceManager.getService("mount"));
3187            if (mount == null) {
3188                Slog.w(TAG, "Early during boot, assuming locked");
3189                return false;
3190            }
3191            final long token = Binder.clearCallingIdentity();
3192            try {
3193                return mount.isUserKeyUnlocked(userId);
3194            } catch (RemoteException e) {
3195                throw e.rethrowAsRuntimeException();
3196            } finally {
3197                Binder.restoreCallingIdentity(token);
3198            }
3199        } else {
3200            return true;
3201        }
3202    }
3203
3204    /**
3205     * Augment the given flags depending on current user running state. This is
3206     * purposefully done before acquiring {@link #mPackages} lock.
3207     */
3208    private int augmentFlagsForUser(int flags, int userId) {
3209        if (!isUserKeyUnlocked(userId)) {
3210            flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3211        }
3212        return flags;
3213    }
3214
3215    @Override
3216    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3217        if (!sUserManager.exists(userId)) return null;
3218        flags = augmentFlagsForUser(flags, userId);
3219        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3220        synchronized (mPackages) {
3221            PackageParser.Activity a = mActivities.mActivities.get(component);
3222
3223            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3224            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3225                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3226                if (ps == null) return null;
3227                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3228                        userId);
3229            }
3230            if (mResolveComponentName.equals(component)) {
3231                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3232                        new PackageUserState(), userId);
3233            }
3234        }
3235        return null;
3236    }
3237
3238    @Override
3239    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3240            String resolvedType) {
3241        synchronized (mPackages) {
3242            if (component.equals(mResolveComponentName)) {
3243                // The resolver supports EVERYTHING!
3244                return true;
3245            }
3246            PackageParser.Activity a = mActivities.mActivities.get(component);
3247            if (a == null) {
3248                return false;
3249            }
3250            for (int i=0; i<a.intents.size(); i++) {
3251                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3252                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3253                    return true;
3254                }
3255            }
3256            return false;
3257        }
3258    }
3259
3260    @Override
3261    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3262        if (!sUserManager.exists(userId)) return null;
3263        flags = augmentFlagsForUser(flags, userId);
3264        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3265        synchronized (mPackages) {
3266            PackageParser.Activity a = mReceivers.mActivities.get(component);
3267            if (DEBUG_PACKAGE_INFO) Log.v(
3268                TAG, "getReceiverInfo " + component + ": " + a);
3269            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3270                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3271                if (ps == null) return null;
3272                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3273                        userId);
3274            }
3275        }
3276        return null;
3277    }
3278
3279    @Override
3280    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3281        if (!sUserManager.exists(userId)) return null;
3282        flags = augmentFlagsForUser(flags, userId);
3283        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3284        synchronized (mPackages) {
3285            PackageParser.Service s = mServices.mServices.get(component);
3286            if (DEBUG_PACKAGE_INFO) Log.v(
3287                TAG, "getServiceInfo " + component + ": " + s);
3288            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3289                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3290                if (ps == null) return null;
3291                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3292                        userId);
3293            }
3294        }
3295        return null;
3296    }
3297
3298    @Override
3299    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3300        if (!sUserManager.exists(userId)) return null;
3301        flags = augmentFlagsForUser(flags, userId);
3302        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3303        synchronized (mPackages) {
3304            PackageParser.Provider p = mProviders.mProviders.get(component);
3305            if (DEBUG_PACKAGE_INFO) Log.v(
3306                TAG, "getProviderInfo " + component + ": " + p);
3307            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3308                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3309                if (ps == null) return null;
3310                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3311                        userId);
3312            }
3313        }
3314        return null;
3315    }
3316
3317    @Override
3318    public String[] getSystemSharedLibraryNames() {
3319        Set<String> libSet;
3320        synchronized (mPackages) {
3321            libSet = mSharedLibraries.keySet();
3322            int size = libSet.size();
3323            if (size > 0) {
3324                String[] libs = new String[size];
3325                libSet.toArray(libs);
3326                return libs;
3327            }
3328        }
3329        return null;
3330    }
3331
3332    /**
3333     * @hide
3334     */
3335    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3336        synchronized (mPackages) {
3337            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3338            if (lib != null && lib.apk != null) {
3339                return mPackages.get(lib.apk);
3340            }
3341        }
3342        return null;
3343    }
3344
3345    @Override
3346    public FeatureInfo[] getSystemAvailableFeatures() {
3347        Collection<FeatureInfo> featSet;
3348        synchronized (mPackages) {
3349            featSet = mAvailableFeatures.values();
3350            int size = featSet.size();
3351            if (size > 0) {
3352                FeatureInfo[] features = new FeatureInfo[size+1];
3353                featSet.toArray(features);
3354                FeatureInfo fi = new FeatureInfo();
3355                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3356                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3357                features[size] = fi;
3358                return features;
3359            }
3360        }
3361        return null;
3362    }
3363
3364    @Override
3365    public boolean hasSystemFeature(String name) {
3366        synchronized (mPackages) {
3367            return mAvailableFeatures.containsKey(name);
3368        }
3369    }
3370
3371    private void checkValidCaller(int uid, int userId) {
3372        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3373            return;
3374
3375        throw new SecurityException("Caller uid=" + uid
3376                + " is not privileged to communicate with user=" + userId);
3377    }
3378
3379    @Override
3380    public int checkPermission(String permName, String pkgName, int userId) {
3381        if (!sUserManager.exists(userId)) {
3382            return PackageManager.PERMISSION_DENIED;
3383        }
3384
3385        synchronized (mPackages) {
3386            final PackageParser.Package p = mPackages.get(pkgName);
3387            if (p != null && p.mExtras != null) {
3388                final PackageSetting ps = (PackageSetting) p.mExtras;
3389                final PermissionsState permissionsState = ps.getPermissionsState();
3390                if (permissionsState.hasPermission(permName, userId)) {
3391                    return PackageManager.PERMISSION_GRANTED;
3392                }
3393                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3394                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3395                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3396                    return PackageManager.PERMISSION_GRANTED;
3397                }
3398            }
3399        }
3400
3401        return PackageManager.PERMISSION_DENIED;
3402    }
3403
3404    @Override
3405    public int checkUidPermission(String permName, int uid) {
3406        final int userId = UserHandle.getUserId(uid);
3407
3408        if (!sUserManager.exists(userId)) {
3409            return PackageManager.PERMISSION_DENIED;
3410        }
3411
3412        synchronized (mPackages) {
3413            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3414            if (obj != null) {
3415                final SettingBase ps = (SettingBase) obj;
3416                final PermissionsState permissionsState = ps.getPermissionsState();
3417                if (permissionsState.hasPermission(permName, userId)) {
3418                    return PackageManager.PERMISSION_GRANTED;
3419                }
3420                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3421                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3422                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3423                    return PackageManager.PERMISSION_GRANTED;
3424                }
3425            } else {
3426                ArraySet<String> perms = mSystemPermissions.get(uid);
3427                if (perms != null) {
3428                    if (perms.contains(permName)) {
3429                        return PackageManager.PERMISSION_GRANTED;
3430                    }
3431                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3432                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3433                        return PackageManager.PERMISSION_GRANTED;
3434                    }
3435                }
3436            }
3437        }
3438
3439        return PackageManager.PERMISSION_DENIED;
3440    }
3441
3442    @Override
3443    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3444        if (UserHandle.getCallingUserId() != userId) {
3445            mContext.enforceCallingPermission(
3446                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3447                    "isPermissionRevokedByPolicy for user " + userId);
3448        }
3449
3450        if (checkPermission(permission, packageName, userId)
3451                == PackageManager.PERMISSION_GRANTED) {
3452            return false;
3453        }
3454
3455        final long identity = Binder.clearCallingIdentity();
3456        try {
3457            final int flags = getPermissionFlags(permission, packageName, userId);
3458            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3459        } finally {
3460            Binder.restoreCallingIdentity(identity);
3461        }
3462    }
3463
3464    @Override
3465    public String getPermissionControllerPackageName() {
3466        synchronized (mPackages) {
3467            return mRequiredInstallerPackage;
3468        }
3469    }
3470
3471    /**
3472     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3473     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3474     * @param checkShell TODO(yamasani):
3475     * @param message the message to log on security exception
3476     */
3477    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3478            boolean checkShell, String message) {
3479        if (userId < 0) {
3480            throw new IllegalArgumentException("Invalid userId " + userId);
3481        }
3482        if (checkShell) {
3483            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3484        }
3485        if (userId == UserHandle.getUserId(callingUid)) return;
3486        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3487            if (requireFullPermission) {
3488                mContext.enforceCallingOrSelfPermission(
3489                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3490            } else {
3491                try {
3492                    mContext.enforceCallingOrSelfPermission(
3493                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3494                } catch (SecurityException se) {
3495                    mContext.enforceCallingOrSelfPermission(
3496                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3497                }
3498            }
3499        }
3500    }
3501
3502    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3503        if (callingUid == Process.SHELL_UID) {
3504            if (userHandle >= 0
3505                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3506                throw new SecurityException("Shell does not have permission to access user "
3507                        + userHandle);
3508            } else if (userHandle < 0) {
3509                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3510                        + Debug.getCallers(3));
3511            }
3512        }
3513    }
3514
3515    private BasePermission findPermissionTreeLP(String permName) {
3516        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3517            if (permName.startsWith(bp.name) &&
3518                    permName.length() > bp.name.length() &&
3519                    permName.charAt(bp.name.length()) == '.') {
3520                return bp;
3521            }
3522        }
3523        return null;
3524    }
3525
3526    private BasePermission checkPermissionTreeLP(String permName) {
3527        if (permName != null) {
3528            BasePermission bp = findPermissionTreeLP(permName);
3529            if (bp != null) {
3530                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3531                    return bp;
3532                }
3533                throw new SecurityException("Calling uid "
3534                        + Binder.getCallingUid()
3535                        + " is not allowed to add to permission tree "
3536                        + bp.name + " owned by uid " + bp.uid);
3537            }
3538        }
3539        throw new SecurityException("No permission tree found for " + permName);
3540    }
3541
3542    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3543        if (s1 == null) {
3544            return s2 == null;
3545        }
3546        if (s2 == null) {
3547            return false;
3548        }
3549        if (s1.getClass() != s2.getClass()) {
3550            return false;
3551        }
3552        return s1.equals(s2);
3553    }
3554
3555    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3556        if (pi1.icon != pi2.icon) return false;
3557        if (pi1.logo != pi2.logo) return false;
3558        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3559        if (!compareStrings(pi1.name, pi2.name)) return false;
3560        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3561        // We'll take care of setting this one.
3562        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3563        // These are not currently stored in settings.
3564        //if (!compareStrings(pi1.group, pi2.group)) return false;
3565        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3566        //if (pi1.labelRes != pi2.labelRes) return false;
3567        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3568        return true;
3569    }
3570
3571    int permissionInfoFootprint(PermissionInfo info) {
3572        int size = info.name.length();
3573        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3574        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3575        return size;
3576    }
3577
3578    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3579        int size = 0;
3580        for (BasePermission perm : mSettings.mPermissions.values()) {
3581            if (perm.uid == tree.uid) {
3582                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3583            }
3584        }
3585        return size;
3586    }
3587
3588    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3589        // We calculate the max size of permissions defined by this uid and throw
3590        // if that plus the size of 'info' would exceed our stated maximum.
3591        if (tree.uid != Process.SYSTEM_UID) {
3592            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3593            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3594                throw new SecurityException("Permission tree size cap exceeded");
3595            }
3596        }
3597    }
3598
3599    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3600        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3601            throw new SecurityException("Label must be specified in permission");
3602        }
3603        BasePermission tree = checkPermissionTreeLP(info.name);
3604        BasePermission bp = mSettings.mPermissions.get(info.name);
3605        boolean added = bp == null;
3606        boolean changed = true;
3607        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3608        if (added) {
3609            enforcePermissionCapLocked(info, tree);
3610            bp = new BasePermission(info.name, tree.sourcePackage,
3611                    BasePermission.TYPE_DYNAMIC);
3612        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3613            throw new SecurityException(
3614                    "Not allowed to modify non-dynamic permission "
3615                    + info.name);
3616        } else {
3617            if (bp.protectionLevel == fixedLevel
3618                    && bp.perm.owner.equals(tree.perm.owner)
3619                    && bp.uid == tree.uid
3620                    && comparePermissionInfos(bp.perm.info, info)) {
3621                changed = false;
3622            }
3623        }
3624        bp.protectionLevel = fixedLevel;
3625        info = new PermissionInfo(info);
3626        info.protectionLevel = fixedLevel;
3627        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3628        bp.perm.info.packageName = tree.perm.info.packageName;
3629        bp.uid = tree.uid;
3630        if (added) {
3631            mSettings.mPermissions.put(info.name, bp);
3632        }
3633        if (changed) {
3634            if (!async) {
3635                mSettings.writeLPr();
3636            } else {
3637                scheduleWriteSettingsLocked();
3638            }
3639        }
3640        return added;
3641    }
3642
3643    @Override
3644    public boolean addPermission(PermissionInfo info) {
3645        synchronized (mPackages) {
3646            return addPermissionLocked(info, false);
3647        }
3648    }
3649
3650    @Override
3651    public boolean addPermissionAsync(PermissionInfo info) {
3652        synchronized (mPackages) {
3653            return addPermissionLocked(info, true);
3654        }
3655    }
3656
3657    @Override
3658    public void removePermission(String name) {
3659        synchronized (mPackages) {
3660            checkPermissionTreeLP(name);
3661            BasePermission bp = mSettings.mPermissions.get(name);
3662            if (bp != null) {
3663                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3664                    throw new SecurityException(
3665                            "Not allowed to modify non-dynamic permission "
3666                            + name);
3667                }
3668                mSettings.mPermissions.remove(name);
3669                mSettings.writeLPr();
3670            }
3671        }
3672    }
3673
3674    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3675            BasePermission bp) {
3676        int index = pkg.requestedPermissions.indexOf(bp.name);
3677        if (index == -1) {
3678            throw new SecurityException("Package " + pkg.packageName
3679                    + " has not requested permission " + bp.name);
3680        }
3681        if (!bp.isRuntime() && !bp.isDevelopment()) {
3682            throw new SecurityException("Permission " + bp.name
3683                    + " is not a changeable permission type");
3684        }
3685    }
3686
3687    @Override
3688    public void grantRuntimePermission(String packageName, String name, final int userId) {
3689        if (!sUserManager.exists(userId)) {
3690            Log.e(TAG, "No such user:" + userId);
3691            return;
3692        }
3693
3694        mContext.enforceCallingOrSelfPermission(
3695                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3696                "grantRuntimePermission");
3697
3698        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3699                "grantRuntimePermission");
3700
3701        final int uid;
3702        final SettingBase sb;
3703
3704        synchronized (mPackages) {
3705            final PackageParser.Package pkg = mPackages.get(packageName);
3706            if (pkg == null) {
3707                throw new IllegalArgumentException("Unknown package: " + packageName);
3708            }
3709
3710            final BasePermission bp = mSettings.mPermissions.get(name);
3711            if (bp == null) {
3712                throw new IllegalArgumentException("Unknown permission: " + name);
3713            }
3714
3715            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3716
3717            // If a permission review is required for legacy apps we represent
3718            // their permissions as always granted runtime ones since we need
3719            // to keep the review required permission flag per user while an
3720            // install permission's state is shared across all users.
3721            if (Build.PERMISSIONS_REVIEW_REQUIRED
3722                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3723                    && bp.isRuntime()) {
3724                return;
3725            }
3726
3727            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3728            sb = (SettingBase) pkg.mExtras;
3729            if (sb == null) {
3730                throw new IllegalArgumentException("Unknown package: " + packageName);
3731            }
3732
3733            final PermissionsState permissionsState = sb.getPermissionsState();
3734
3735            final int flags = permissionsState.getPermissionFlags(name, userId);
3736            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3737                throw new SecurityException("Cannot grant system fixed permission: "
3738                        + name + " for package: " + packageName);
3739            }
3740
3741            if (bp.isDevelopment()) {
3742                // Development permissions must be handled specially, since they are not
3743                // normal runtime permissions.  For now they apply to all users.
3744                if (permissionsState.grantInstallPermission(bp) !=
3745                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3746                    scheduleWriteSettingsLocked();
3747                }
3748                return;
3749            }
3750
3751            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3752                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3753                return;
3754            }
3755
3756            final int result = permissionsState.grantRuntimePermission(bp, userId);
3757            switch (result) {
3758                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3759                    return;
3760                }
3761
3762                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3763                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3764                    mHandler.post(new Runnable() {
3765                        @Override
3766                        public void run() {
3767                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3768                        }
3769                    });
3770                }
3771                break;
3772            }
3773
3774            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3775
3776            // Not critical if that is lost - app has to request again.
3777            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3778        }
3779
3780        // Only need to do this if user is initialized. Otherwise it's a new user
3781        // and there are no processes running as the user yet and there's no need
3782        // to make an expensive call to remount processes for the changed permissions.
3783        if (READ_EXTERNAL_STORAGE.equals(name)
3784                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3785            final long token = Binder.clearCallingIdentity();
3786            try {
3787                if (sUserManager.isInitialized(userId)) {
3788                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3789                            MountServiceInternal.class);
3790                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3791                }
3792            } finally {
3793                Binder.restoreCallingIdentity(token);
3794            }
3795        }
3796    }
3797
3798    @Override
3799    public void revokeRuntimePermission(String packageName, String name, int userId) {
3800        if (!sUserManager.exists(userId)) {
3801            Log.e(TAG, "No such user:" + userId);
3802            return;
3803        }
3804
3805        mContext.enforceCallingOrSelfPermission(
3806                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3807                "revokeRuntimePermission");
3808
3809        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3810                "revokeRuntimePermission");
3811
3812        final int appId;
3813
3814        synchronized (mPackages) {
3815            final PackageParser.Package pkg = mPackages.get(packageName);
3816            if (pkg == null) {
3817                throw new IllegalArgumentException("Unknown package: " + packageName);
3818            }
3819
3820            final BasePermission bp = mSettings.mPermissions.get(name);
3821            if (bp == null) {
3822                throw new IllegalArgumentException("Unknown permission: " + name);
3823            }
3824
3825            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3826
3827            // If a permission review is required for legacy apps we represent
3828            // their permissions as always granted runtime ones since we need
3829            // to keep the review required permission flag per user while an
3830            // install permission's state is shared across all users.
3831            if (Build.PERMISSIONS_REVIEW_REQUIRED
3832                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3833                    && bp.isRuntime()) {
3834                return;
3835            }
3836
3837            SettingBase sb = (SettingBase) pkg.mExtras;
3838            if (sb == null) {
3839                throw new IllegalArgumentException("Unknown package: " + packageName);
3840            }
3841
3842            final PermissionsState permissionsState = sb.getPermissionsState();
3843
3844            final int flags = permissionsState.getPermissionFlags(name, userId);
3845            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3846                throw new SecurityException("Cannot revoke system fixed permission: "
3847                        + name + " for package: " + packageName);
3848            }
3849
3850            if (bp.isDevelopment()) {
3851                // Development permissions must be handled specially, since they are not
3852                // normal runtime permissions.  For now they apply to all users.
3853                if (permissionsState.revokeInstallPermission(bp) !=
3854                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3855                    scheduleWriteSettingsLocked();
3856                }
3857                return;
3858            }
3859
3860            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3861                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3862                return;
3863            }
3864
3865            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3866
3867            // Critical, after this call app should never have the permission.
3868            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3869
3870            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3871        }
3872
3873        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3874    }
3875
3876    @Override
3877    public void resetRuntimePermissions() {
3878        mContext.enforceCallingOrSelfPermission(
3879                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3880                "revokeRuntimePermission");
3881
3882        int callingUid = Binder.getCallingUid();
3883        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3884            mContext.enforceCallingOrSelfPermission(
3885                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3886                    "resetRuntimePermissions");
3887        }
3888
3889        synchronized (mPackages) {
3890            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3891            for (int userId : UserManagerService.getInstance().getUserIds()) {
3892                final int packageCount = mPackages.size();
3893                for (int i = 0; i < packageCount; i++) {
3894                    PackageParser.Package pkg = mPackages.valueAt(i);
3895                    if (!(pkg.mExtras instanceof PackageSetting)) {
3896                        continue;
3897                    }
3898                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3899                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3900                }
3901            }
3902        }
3903    }
3904
3905    @Override
3906    public int getPermissionFlags(String name, String packageName, int userId) {
3907        if (!sUserManager.exists(userId)) {
3908            return 0;
3909        }
3910
3911        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3912
3913        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3914                "getPermissionFlags");
3915
3916        synchronized (mPackages) {
3917            final PackageParser.Package pkg = mPackages.get(packageName);
3918            if (pkg == null) {
3919                throw new IllegalArgumentException("Unknown package: " + packageName);
3920            }
3921
3922            final BasePermission bp = mSettings.mPermissions.get(name);
3923            if (bp == null) {
3924                throw new IllegalArgumentException("Unknown permission: " + name);
3925            }
3926
3927            SettingBase sb = (SettingBase) pkg.mExtras;
3928            if (sb == null) {
3929                throw new IllegalArgumentException("Unknown package: " + packageName);
3930            }
3931
3932            PermissionsState permissionsState = sb.getPermissionsState();
3933            return permissionsState.getPermissionFlags(name, userId);
3934        }
3935    }
3936
3937    @Override
3938    public void updatePermissionFlags(String name, String packageName, int flagMask,
3939            int flagValues, int userId) {
3940        if (!sUserManager.exists(userId)) {
3941            return;
3942        }
3943
3944        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3945
3946        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3947                "updatePermissionFlags");
3948
3949        // Only the system can change these flags and nothing else.
3950        if (getCallingUid() != Process.SYSTEM_UID) {
3951            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3952            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3953            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3954            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3955            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3956        }
3957
3958        synchronized (mPackages) {
3959            final PackageParser.Package pkg = mPackages.get(packageName);
3960            if (pkg == null) {
3961                throw new IllegalArgumentException("Unknown package: " + packageName);
3962            }
3963
3964            final BasePermission bp = mSettings.mPermissions.get(name);
3965            if (bp == null) {
3966                throw new IllegalArgumentException("Unknown permission: " + name);
3967            }
3968
3969            SettingBase sb = (SettingBase) pkg.mExtras;
3970            if (sb == null) {
3971                throw new IllegalArgumentException("Unknown package: " + packageName);
3972            }
3973
3974            PermissionsState permissionsState = sb.getPermissionsState();
3975
3976            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3977
3978            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3979                // Install and runtime permissions are stored in different places,
3980                // so figure out what permission changed and persist the change.
3981                if (permissionsState.getInstallPermissionState(name) != null) {
3982                    scheduleWriteSettingsLocked();
3983                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3984                        || hadState) {
3985                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3986                }
3987            }
3988        }
3989    }
3990
3991    /**
3992     * Update the permission flags for all packages and runtime permissions of a user in order
3993     * to allow device or profile owner to remove POLICY_FIXED.
3994     */
3995    @Override
3996    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3997        if (!sUserManager.exists(userId)) {
3998            return;
3999        }
4000
4001        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4002
4003        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4004                "updatePermissionFlagsForAllApps");
4005
4006        // Only the system can change system fixed flags.
4007        if (getCallingUid() != Process.SYSTEM_UID) {
4008            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4009            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4010        }
4011
4012        synchronized (mPackages) {
4013            boolean changed = false;
4014            final int packageCount = mPackages.size();
4015            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4016                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4017                SettingBase sb = (SettingBase) pkg.mExtras;
4018                if (sb == null) {
4019                    continue;
4020                }
4021                PermissionsState permissionsState = sb.getPermissionsState();
4022                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4023                        userId, flagMask, flagValues);
4024            }
4025            if (changed) {
4026                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4027            }
4028        }
4029    }
4030
4031    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4032        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4033                != PackageManager.PERMISSION_GRANTED
4034            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4035                != PackageManager.PERMISSION_GRANTED) {
4036            throw new SecurityException(message + " requires "
4037                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4038                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4039        }
4040    }
4041
4042    @Override
4043    public boolean shouldShowRequestPermissionRationale(String permissionName,
4044            String packageName, int userId) {
4045        if (UserHandle.getCallingUserId() != userId) {
4046            mContext.enforceCallingPermission(
4047                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4048                    "canShowRequestPermissionRationale for user " + userId);
4049        }
4050
4051        final int uid = getPackageUid(packageName, userId);
4052        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4053            return false;
4054        }
4055
4056        if (checkPermission(permissionName, packageName, userId)
4057                == PackageManager.PERMISSION_GRANTED) {
4058            return false;
4059        }
4060
4061        final int flags;
4062
4063        final long identity = Binder.clearCallingIdentity();
4064        try {
4065            flags = getPermissionFlags(permissionName,
4066                    packageName, userId);
4067        } finally {
4068            Binder.restoreCallingIdentity(identity);
4069        }
4070
4071        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4072                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4073                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4074
4075        if ((flags & fixedFlags) != 0) {
4076            return false;
4077        }
4078
4079        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4080    }
4081
4082    @Override
4083    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4084        mContext.enforceCallingOrSelfPermission(
4085                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4086                "addOnPermissionsChangeListener");
4087
4088        synchronized (mPackages) {
4089            mOnPermissionChangeListeners.addListenerLocked(listener);
4090        }
4091    }
4092
4093    @Override
4094    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4095        synchronized (mPackages) {
4096            mOnPermissionChangeListeners.removeListenerLocked(listener);
4097        }
4098    }
4099
4100    @Override
4101    public boolean isProtectedBroadcast(String actionName) {
4102        synchronized (mPackages) {
4103            if (mProtectedBroadcasts.contains(actionName)) {
4104                return true;
4105            } else if (actionName != null
4106                    && actionName.startsWith("android.net.netmon.lingerExpired")) {
4107                // TODO: remove this terrible hack
4108                return true;
4109            }
4110        }
4111        return false;
4112    }
4113
4114    @Override
4115    public int checkSignatures(String pkg1, String pkg2) {
4116        synchronized (mPackages) {
4117            final PackageParser.Package p1 = mPackages.get(pkg1);
4118            final PackageParser.Package p2 = mPackages.get(pkg2);
4119            if (p1 == null || p1.mExtras == null
4120                    || p2 == null || p2.mExtras == null) {
4121                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4122            }
4123            return compareSignatures(p1.mSignatures, p2.mSignatures);
4124        }
4125    }
4126
4127    @Override
4128    public int checkUidSignatures(int uid1, int uid2) {
4129        // Map to base uids.
4130        uid1 = UserHandle.getAppId(uid1);
4131        uid2 = UserHandle.getAppId(uid2);
4132        // reader
4133        synchronized (mPackages) {
4134            Signature[] s1;
4135            Signature[] s2;
4136            Object obj = mSettings.getUserIdLPr(uid1);
4137            if (obj != null) {
4138                if (obj instanceof SharedUserSetting) {
4139                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4140                } else if (obj instanceof PackageSetting) {
4141                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4142                } else {
4143                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4144                }
4145            } else {
4146                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4147            }
4148            obj = mSettings.getUserIdLPr(uid2);
4149            if (obj != null) {
4150                if (obj instanceof SharedUserSetting) {
4151                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4152                } else if (obj instanceof PackageSetting) {
4153                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4154                } else {
4155                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4156                }
4157            } else {
4158                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4159            }
4160            return compareSignatures(s1, s2);
4161        }
4162    }
4163
4164    private void killUid(int appId, int userId, String reason) {
4165        final long identity = Binder.clearCallingIdentity();
4166        try {
4167            IActivityManager am = ActivityManagerNative.getDefault();
4168            if (am != null) {
4169                try {
4170                    am.killUid(appId, userId, reason);
4171                } catch (RemoteException e) {
4172                    /* ignore - same process */
4173                }
4174            }
4175        } finally {
4176            Binder.restoreCallingIdentity(identity);
4177        }
4178    }
4179
4180    /**
4181     * Compares two sets of signatures. Returns:
4182     * <br />
4183     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4184     * <br />
4185     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4186     * <br />
4187     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4188     * <br />
4189     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4190     * <br />
4191     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4192     */
4193    static int compareSignatures(Signature[] s1, Signature[] s2) {
4194        if (s1 == null) {
4195            return s2 == null
4196                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4197                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4198        }
4199
4200        if (s2 == null) {
4201            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4202        }
4203
4204        if (s1.length != s2.length) {
4205            return PackageManager.SIGNATURE_NO_MATCH;
4206        }
4207
4208        // Since both signature sets are of size 1, we can compare without HashSets.
4209        if (s1.length == 1) {
4210            return s1[0].equals(s2[0]) ?
4211                    PackageManager.SIGNATURE_MATCH :
4212                    PackageManager.SIGNATURE_NO_MATCH;
4213        }
4214
4215        ArraySet<Signature> set1 = new ArraySet<Signature>();
4216        for (Signature sig : s1) {
4217            set1.add(sig);
4218        }
4219        ArraySet<Signature> set2 = new ArraySet<Signature>();
4220        for (Signature sig : s2) {
4221            set2.add(sig);
4222        }
4223        // Make sure s2 contains all signatures in s1.
4224        if (set1.equals(set2)) {
4225            return PackageManager.SIGNATURE_MATCH;
4226        }
4227        return PackageManager.SIGNATURE_NO_MATCH;
4228    }
4229
4230    /**
4231     * If the database version for this type of package (internal storage or
4232     * external storage) is less than the version where package signatures
4233     * were updated, return true.
4234     */
4235    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4236        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4237        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4238    }
4239
4240    /**
4241     * Used for backward compatibility to make sure any packages with
4242     * certificate chains get upgraded to the new style. {@code existingSigs}
4243     * will be in the old format (since they were stored on disk from before the
4244     * system upgrade) and {@code scannedSigs} will be in the newer format.
4245     */
4246    private int compareSignaturesCompat(PackageSignatures existingSigs,
4247            PackageParser.Package scannedPkg) {
4248        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4249            return PackageManager.SIGNATURE_NO_MATCH;
4250        }
4251
4252        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4253        for (Signature sig : existingSigs.mSignatures) {
4254            existingSet.add(sig);
4255        }
4256        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4257        for (Signature sig : scannedPkg.mSignatures) {
4258            try {
4259                Signature[] chainSignatures = sig.getChainSignatures();
4260                for (Signature chainSig : chainSignatures) {
4261                    scannedCompatSet.add(chainSig);
4262                }
4263            } catch (CertificateEncodingException e) {
4264                scannedCompatSet.add(sig);
4265            }
4266        }
4267        /*
4268         * Make sure the expanded scanned set contains all signatures in the
4269         * existing one.
4270         */
4271        if (scannedCompatSet.equals(existingSet)) {
4272            // Migrate the old signatures to the new scheme.
4273            existingSigs.assignSignatures(scannedPkg.mSignatures);
4274            // The new KeySets will be re-added later in the scanning process.
4275            synchronized (mPackages) {
4276                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4277            }
4278            return PackageManager.SIGNATURE_MATCH;
4279        }
4280        return PackageManager.SIGNATURE_NO_MATCH;
4281    }
4282
4283    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4284        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4285        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4286    }
4287
4288    private int compareSignaturesRecover(PackageSignatures existingSigs,
4289            PackageParser.Package scannedPkg) {
4290        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4291            return PackageManager.SIGNATURE_NO_MATCH;
4292        }
4293
4294        String msg = null;
4295        try {
4296            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4297                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4298                        + scannedPkg.packageName);
4299                return PackageManager.SIGNATURE_MATCH;
4300            }
4301        } catch (CertificateException e) {
4302            msg = e.getMessage();
4303        }
4304
4305        logCriticalInfo(Log.INFO,
4306                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4307        return PackageManager.SIGNATURE_NO_MATCH;
4308    }
4309
4310    @Override
4311    public String[] getPackagesForUid(int uid) {
4312        uid = UserHandle.getAppId(uid);
4313        // reader
4314        synchronized (mPackages) {
4315            Object obj = mSettings.getUserIdLPr(uid);
4316            if (obj instanceof SharedUserSetting) {
4317                final SharedUserSetting sus = (SharedUserSetting) obj;
4318                final int N = sus.packages.size();
4319                final String[] res = new String[N];
4320                final Iterator<PackageSetting> it = sus.packages.iterator();
4321                int i = 0;
4322                while (it.hasNext()) {
4323                    res[i++] = it.next().name;
4324                }
4325                return res;
4326            } else if (obj instanceof PackageSetting) {
4327                final PackageSetting ps = (PackageSetting) obj;
4328                return new String[] { ps.name };
4329            }
4330        }
4331        return null;
4332    }
4333
4334    @Override
4335    public String getNameForUid(int uid) {
4336        // reader
4337        synchronized (mPackages) {
4338            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4339            if (obj instanceof SharedUserSetting) {
4340                final SharedUserSetting sus = (SharedUserSetting) obj;
4341                return sus.name + ":" + sus.userId;
4342            } else if (obj instanceof PackageSetting) {
4343                final PackageSetting ps = (PackageSetting) obj;
4344                return ps.name;
4345            }
4346        }
4347        return null;
4348    }
4349
4350    @Override
4351    public int getUidForSharedUser(String sharedUserName) {
4352        if(sharedUserName == null) {
4353            return -1;
4354        }
4355        // reader
4356        synchronized (mPackages) {
4357            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4358            if (suid == null) {
4359                return -1;
4360            }
4361            return suid.userId;
4362        }
4363    }
4364
4365    @Override
4366    public int getFlagsForUid(int uid) {
4367        synchronized (mPackages) {
4368            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4369            if (obj instanceof SharedUserSetting) {
4370                final SharedUserSetting sus = (SharedUserSetting) obj;
4371                return sus.pkgFlags;
4372            } else if (obj instanceof PackageSetting) {
4373                final PackageSetting ps = (PackageSetting) obj;
4374                return ps.pkgFlags;
4375            }
4376        }
4377        return 0;
4378    }
4379
4380    @Override
4381    public int getPrivateFlagsForUid(int uid) {
4382        synchronized (mPackages) {
4383            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4384            if (obj instanceof SharedUserSetting) {
4385                final SharedUserSetting sus = (SharedUserSetting) obj;
4386                return sus.pkgPrivateFlags;
4387            } else if (obj instanceof PackageSetting) {
4388                final PackageSetting ps = (PackageSetting) obj;
4389                return ps.pkgPrivateFlags;
4390            }
4391        }
4392        return 0;
4393    }
4394
4395    @Override
4396    public boolean isUidPrivileged(int uid) {
4397        uid = UserHandle.getAppId(uid);
4398        // reader
4399        synchronized (mPackages) {
4400            Object obj = mSettings.getUserIdLPr(uid);
4401            if (obj instanceof SharedUserSetting) {
4402                final SharedUserSetting sus = (SharedUserSetting) obj;
4403                final Iterator<PackageSetting> it = sus.packages.iterator();
4404                while (it.hasNext()) {
4405                    if (it.next().isPrivileged()) {
4406                        return true;
4407                    }
4408                }
4409            } else if (obj instanceof PackageSetting) {
4410                final PackageSetting ps = (PackageSetting) obj;
4411                return ps.isPrivileged();
4412            }
4413        }
4414        return false;
4415    }
4416
4417    @Override
4418    public String[] getAppOpPermissionPackages(String permissionName) {
4419        synchronized (mPackages) {
4420            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4421            if (pkgs == null) {
4422                return null;
4423            }
4424            return pkgs.toArray(new String[pkgs.size()]);
4425        }
4426    }
4427
4428    @Override
4429    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4430            int flags, int userId) {
4431        if (!sUserManager.exists(userId)) return null;
4432        flags = augmentFlagsForUser(flags, userId);
4433        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4434        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4435        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4436    }
4437
4438    @Override
4439    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4440            IntentFilter filter, int match, ComponentName activity) {
4441        final int userId = UserHandle.getCallingUserId();
4442        if (DEBUG_PREFERRED) {
4443            Log.v(TAG, "setLastChosenActivity intent=" + intent
4444                + " resolvedType=" + resolvedType
4445                + " flags=" + flags
4446                + " filter=" + filter
4447                + " match=" + match
4448                + " activity=" + activity);
4449            filter.dump(new PrintStreamPrinter(System.out), "    ");
4450        }
4451        intent.setComponent(null);
4452        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4453        // Find any earlier preferred or last chosen entries and nuke them
4454        findPreferredActivity(intent, resolvedType,
4455                flags, query, 0, false, true, false, userId);
4456        // Add the new activity as the last chosen for this filter
4457        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4458                "Setting last chosen");
4459    }
4460
4461    @Override
4462    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4463        final int userId = UserHandle.getCallingUserId();
4464        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4465        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4466        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4467                false, false, false, userId);
4468    }
4469
4470    private boolean isEphemeralAvailable(Intent intent, String resolvedType, int userId) {
4471        MessageDigest digest = null;
4472        try {
4473            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4474        } catch (NoSuchAlgorithmException e) {
4475            // If we can't create a digest, ignore ephemeral apps.
4476            return false;
4477        }
4478
4479        final byte[] hostBytes = intent.getData().getHost().getBytes();
4480        final byte[] digestBytes = digest.digest(hostBytes);
4481        int shaPrefix =
4482                digestBytes[0] << 24
4483                | digestBytes[1] << 16
4484                | digestBytes[2] << 8
4485                | digestBytes[3] << 0;
4486        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4487                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4488        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4489            // No hash prefix match; there are no ephemeral apps for this domain.
4490            return false;
4491        }
4492        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4493            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4494            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4495                continue;
4496            }
4497            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4498            // No filters; this should never happen.
4499            if (filters.isEmpty()) {
4500                continue;
4501            }
4502            // We have a domain match; resolve the filters to see if anything matches.
4503            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4504            for (int j = filters.size() - 1; j >= 0; --j) {
4505                ephemeralResolver.addFilter(filters.get(j));
4506            }
4507            List<ResolveInfo> ephemeralResolveList = ephemeralResolver.queryIntent(
4508                    intent, resolvedType, false /*defaultOnly*/, userId);
4509            return !ephemeralResolveList.isEmpty();
4510        }
4511        // Hash or filter mis-match; no ephemeral apps for this domain.
4512        return false;
4513    }
4514
4515    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4516            int flags, List<ResolveInfo> query, int userId) {
4517        final boolean isWebUri = hasWebURI(intent);
4518        // Check whether or not an ephemeral app exists to handle the URI.
4519        if (isWebUri && mEphemeralResolverConnection != null) {
4520            // Deny ephemeral apps if the user choose _ALWAYS or _ALWAYS_ASK for intent resolution.
4521            boolean hasAlwaysHandler = false;
4522            synchronized (mPackages) {
4523                final int count = query.size();
4524                for (int n=0; n<count; n++) {
4525                    ResolveInfo info = query.get(n);
4526                    String packageName = info.activityInfo.packageName;
4527                    PackageSetting ps = mSettings.mPackages.get(packageName);
4528                    if (ps != null) {
4529                        // Try to get the status from User settings first
4530                        long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4531                        int status = (int) (packedStatus >> 32);
4532                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4533                                || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4534                            hasAlwaysHandler = true;
4535                            break;
4536                        }
4537                    }
4538                }
4539            }
4540
4541            // Only consider installing an ephemeral app if there isn't already a verified handler.
4542            // We've determined that there's an ephemeral app available for the URI, ignore any
4543            // ResolveInfo's and just return the ephemeral installer
4544            if (!hasAlwaysHandler && isEphemeralAvailable(intent, resolvedType, userId)) {
4545                if (DEBUG_EPHEMERAL) {
4546                    Slog.v(TAG, "Resolving to the ephemeral installer");
4547                }
4548                // ditch the result and return a ResolveInfo to launch the ephemeral installer
4549                ResolveInfo ri = new ResolveInfo(mEphemeralInstallerInfo);
4550                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4551                // make a deep copy of the applicationInfo
4552                ri.activityInfo.applicationInfo = new ApplicationInfo(
4553                        ri.activityInfo.applicationInfo);
4554                if (userId != 0) {
4555                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4556                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4557                }
4558                return ri;
4559            }
4560        }
4561        if (query != null) {
4562            final int N = query.size();
4563            if (N == 1) {
4564                return query.get(0);
4565            } else if (N > 1) {
4566                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4567                // If there is more than one activity with the same priority,
4568                // then let the user decide between them.
4569                ResolveInfo r0 = query.get(0);
4570                ResolveInfo r1 = query.get(1);
4571                if (DEBUG_INTENT_MATCHING || debug) {
4572                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4573                            + r1.activityInfo.name + "=" + r1.priority);
4574                }
4575                // If the first activity has a higher priority, or a different
4576                // default, then it is always desireable to pick it.
4577                if (r0.priority != r1.priority
4578                        || r0.preferredOrder != r1.preferredOrder
4579                        || r0.isDefault != r1.isDefault) {
4580                    return query.get(0);
4581                }
4582                // If we have saved a preference for a preferred activity for
4583                // this Intent, use that.
4584                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4585                        flags, query, r0.priority, true, false, debug, userId);
4586                if (ri != null) {
4587                    return ri;
4588                }
4589                ri = new ResolveInfo(mResolveInfo);
4590                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4591                ri.activityInfo.applicationInfo = new ApplicationInfo(
4592                        ri.activityInfo.applicationInfo);
4593                if (userId != 0) {
4594                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4595                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4596                }
4597                // Make sure that the resolver is displayable in car mode
4598                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4599                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4600                return ri;
4601            }
4602        }
4603        return null;
4604    }
4605
4606    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4607            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4608        final int N = query.size();
4609        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4610                .get(userId);
4611        // Get the list of persistent preferred activities that handle the intent
4612        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4613        List<PersistentPreferredActivity> pprefs = ppir != null
4614                ? ppir.queryIntent(intent, resolvedType,
4615                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4616                : null;
4617        if (pprefs != null && pprefs.size() > 0) {
4618            final int M = pprefs.size();
4619            for (int i=0; i<M; i++) {
4620                final PersistentPreferredActivity ppa = pprefs.get(i);
4621                if (DEBUG_PREFERRED || debug) {
4622                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4623                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4624                            + "\n  component=" + ppa.mComponent);
4625                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4626                }
4627                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4628                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4629                if (DEBUG_PREFERRED || debug) {
4630                    Slog.v(TAG, "Found persistent preferred activity:");
4631                    if (ai != null) {
4632                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4633                    } else {
4634                        Slog.v(TAG, "  null");
4635                    }
4636                }
4637                if (ai == null) {
4638                    // This previously registered persistent preferred activity
4639                    // component is no longer known. Ignore it and do NOT remove it.
4640                    continue;
4641                }
4642                for (int j=0; j<N; j++) {
4643                    final ResolveInfo ri = query.get(j);
4644                    if (!ri.activityInfo.applicationInfo.packageName
4645                            .equals(ai.applicationInfo.packageName)) {
4646                        continue;
4647                    }
4648                    if (!ri.activityInfo.name.equals(ai.name)) {
4649                        continue;
4650                    }
4651                    //  Found a persistent preference that can handle the intent.
4652                    if (DEBUG_PREFERRED || debug) {
4653                        Slog.v(TAG, "Returning persistent preferred activity: " +
4654                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4655                    }
4656                    return ri;
4657                }
4658            }
4659        }
4660        return null;
4661    }
4662
4663    // TODO: handle preferred activities missing while user has amnesia
4664    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4665            List<ResolveInfo> query, int priority, boolean always,
4666            boolean removeMatches, boolean debug, int userId) {
4667        if (!sUserManager.exists(userId)) return null;
4668        flags = augmentFlagsForUser(flags, userId);
4669        // writer
4670        synchronized (mPackages) {
4671            if (intent.getSelector() != null) {
4672                intent = intent.getSelector();
4673            }
4674            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4675
4676            // Try to find a matching persistent preferred activity.
4677            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4678                    debug, userId);
4679
4680            // If a persistent preferred activity matched, use it.
4681            if (pri != null) {
4682                return pri;
4683            }
4684
4685            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4686            // Get the list of preferred activities that handle the intent
4687            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4688            List<PreferredActivity> prefs = pir != null
4689                    ? pir.queryIntent(intent, resolvedType,
4690                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4691                    : null;
4692            if (prefs != null && prefs.size() > 0) {
4693                boolean changed = false;
4694                try {
4695                    // First figure out how good the original match set is.
4696                    // We will only allow preferred activities that came
4697                    // from the same match quality.
4698                    int match = 0;
4699
4700                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4701
4702                    final int N = query.size();
4703                    for (int j=0; j<N; j++) {
4704                        final ResolveInfo ri = query.get(j);
4705                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4706                                + ": 0x" + Integer.toHexString(match));
4707                        if (ri.match > match) {
4708                            match = ri.match;
4709                        }
4710                    }
4711
4712                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4713                            + Integer.toHexString(match));
4714
4715                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4716                    final int M = prefs.size();
4717                    for (int i=0; i<M; i++) {
4718                        final PreferredActivity pa = prefs.get(i);
4719                        if (DEBUG_PREFERRED || debug) {
4720                            Slog.v(TAG, "Checking PreferredActivity ds="
4721                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4722                                    + "\n  component=" + pa.mPref.mComponent);
4723                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4724                        }
4725                        if (pa.mPref.mMatch != match) {
4726                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4727                                    + Integer.toHexString(pa.mPref.mMatch));
4728                            continue;
4729                        }
4730                        // If it's not an "always" type preferred activity and that's what we're
4731                        // looking for, skip it.
4732                        if (always && !pa.mPref.mAlways) {
4733                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4734                            continue;
4735                        }
4736                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4737                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4738                        if (DEBUG_PREFERRED || debug) {
4739                            Slog.v(TAG, "Found preferred activity:");
4740                            if (ai != null) {
4741                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4742                            } else {
4743                                Slog.v(TAG, "  null");
4744                            }
4745                        }
4746                        if (ai == null) {
4747                            // This previously registered preferred activity
4748                            // component is no longer known.  Most likely an update
4749                            // to the app was installed and in the new version this
4750                            // component no longer exists.  Clean it up by removing
4751                            // it from the preferred activities list, and skip it.
4752                            Slog.w(TAG, "Removing dangling preferred activity: "
4753                                    + pa.mPref.mComponent);
4754                            pir.removeFilter(pa);
4755                            changed = true;
4756                            continue;
4757                        }
4758                        for (int j=0; j<N; j++) {
4759                            final ResolveInfo ri = query.get(j);
4760                            if (!ri.activityInfo.applicationInfo.packageName
4761                                    .equals(ai.applicationInfo.packageName)) {
4762                                continue;
4763                            }
4764                            if (!ri.activityInfo.name.equals(ai.name)) {
4765                                continue;
4766                            }
4767
4768                            if (removeMatches) {
4769                                pir.removeFilter(pa);
4770                                changed = true;
4771                                if (DEBUG_PREFERRED) {
4772                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4773                                }
4774                                break;
4775                            }
4776
4777                            // Okay we found a previously set preferred or last chosen app.
4778                            // If the result set is different from when this
4779                            // was created, we need to clear it and re-ask the
4780                            // user their preference, if we're looking for an "always" type entry.
4781                            if (always && !pa.mPref.sameSet(query)) {
4782                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4783                                        + intent + " type " + resolvedType);
4784                                if (DEBUG_PREFERRED) {
4785                                    Slog.v(TAG, "Removing preferred activity since set changed "
4786                                            + pa.mPref.mComponent);
4787                                }
4788                                pir.removeFilter(pa);
4789                                // Re-add the filter as a "last chosen" entry (!always)
4790                                PreferredActivity lastChosen = new PreferredActivity(
4791                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4792                                pir.addFilter(lastChosen);
4793                                changed = true;
4794                                return null;
4795                            }
4796
4797                            // Yay! Either the set matched or we're looking for the last chosen
4798                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4799                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4800                            return ri;
4801                        }
4802                    }
4803                } finally {
4804                    if (changed) {
4805                        if (DEBUG_PREFERRED) {
4806                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4807                        }
4808                        scheduleWritePackageRestrictionsLocked(userId);
4809                    }
4810                }
4811            }
4812        }
4813        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4814        return null;
4815    }
4816
4817    /*
4818     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4819     */
4820    @Override
4821    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4822            int targetUserId) {
4823        mContext.enforceCallingOrSelfPermission(
4824                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4825        List<CrossProfileIntentFilter> matches =
4826                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4827        if (matches != null) {
4828            int size = matches.size();
4829            for (int i = 0; i < size; i++) {
4830                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4831            }
4832        }
4833        if (hasWebURI(intent)) {
4834            // cross-profile app linking works only towards the parent.
4835            final UserInfo parent = getProfileParent(sourceUserId);
4836            synchronized(mPackages) {
4837                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4838                        intent, resolvedType, 0, sourceUserId, parent.id);
4839                return xpDomainInfo != null;
4840            }
4841        }
4842        return false;
4843    }
4844
4845    private UserInfo getProfileParent(int userId) {
4846        final long identity = Binder.clearCallingIdentity();
4847        try {
4848            return sUserManager.getProfileParent(userId);
4849        } finally {
4850            Binder.restoreCallingIdentity(identity);
4851        }
4852    }
4853
4854    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4855            String resolvedType, int userId) {
4856        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4857        if (resolver != null) {
4858            return resolver.queryIntent(intent, resolvedType, false, userId);
4859        }
4860        return null;
4861    }
4862
4863    @Override
4864    public List<ResolveInfo> queryIntentActivities(Intent intent,
4865            String resolvedType, int flags, int userId) {
4866        if (!sUserManager.exists(userId)) return Collections.emptyList();
4867        flags = augmentFlagsForUser(flags, userId);
4868        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4869        ComponentName comp = intent.getComponent();
4870        if (comp == null) {
4871            if (intent.getSelector() != null) {
4872                intent = intent.getSelector();
4873                comp = intent.getComponent();
4874            }
4875        }
4876
4877        if (comp != null) {
4878            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4879            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4880            if (ai != null) {
4881                final ResolveInfo ri = new ResolveInfo();
4882                ri.activityInfo = ai;
4883                list.add(ri);
4884            }
4885            return list;
4886        }
4887
4888        // reader
4889        synchronized (mPackages) {
4890            final String pkgName = intent.getPackage();
4891            if (pkgName == null) {
4892                List<CrossProfileIntentFilter> matchingFilters =
4893                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4894                // Check for results that need to skip the current profile.
4895                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4896                        resolvedType, flags, userId);
4897                if (xpResolveInfo != null) {
4898                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4899                    result.add(xpResolveInfo);
4900                    return filterIfNotSystemUser(result, userId);
4901                }
4902
4903                // Check for results in the current profile.
4904                List<ResolveInfo> result = mActivities.queryIntent(
4905                        intent, resolvedType, flags, userId);
4906                result = filterIfNotSystemUser(result, userId);
4907
4908                // Check for cross profile results.
4909                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4910                xpResolveInfo = queryCrossProfileIntents(
4911                        matchingFilters, intent, resolvedType, flags, userId,
4912                        hasNonNegativePriorityResult);
4913                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4914                    boolean isVisibleToUser = filterIfNotSystemUser(
4915                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4916                    if (isVisibleToUser) {
4917                        result.add(xpResolveInfo);
4918                        Collections.sort(result, mResolvePrioritySorter);
4919                    }
4920                }
4921                if (hasWebURI(intent)) {
4922                    CrossProfileDomainInfo xpDomainInfo = null;
4923                    final UserInfo parent = getProfileParent(userId);
4924                    if (parent != null) {
4925                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4926                                flags, userId, parent.id);
4927                    }
4928                    if (xpDomainInfo != null) {
4929                        if (xpResolveInfo != null) {
4930                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4931                            // in the result.
4932                            result.remove(xpResolveInfo);
4933                        }
4934                        if (result.size() == 0) {
4935                            result.add(xpDomainInfo.resolveInfo);
4936                            return result;
4937                        }
4938                    } else if (result.size() <= 1) {
4939                        return result;
4940                    }
4941                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4942                            xpDomainInfo, userId);
4943                    Collections.sort(result, mResolvePrioritySorter);
4944                }
4945                return result;
4946            }
4947            final PackageParser.Package pkg = mPackages.get(pkgName);
4948            if (pkg != null) {
4949                return filterIfNotSystemUser(
4950                        mActivities.queryIntentForPackage(
4951                                intent, resolvedType, flags, pkg.activities, userId),
4952                        userId);
4953            }
4954            return new ArrayList<ResolveInfo>();
4955        }
4956    }
4957
4958    private static class CrossProfileDomainInfo {
4959        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4960        ResolveInfo resolveInfo;
4961        /* Best domain verification status of the activities found in the other profile */
4962        int bestDomainVerificationStatus;
4963    }
4964
4965    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4966            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4967        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4968                sourceUserId)) {
4969            return null;
4970        }
4971        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4972                resolvedType, flags, parentUserId);
4973
4974        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4975            return null;
4976        }
4977        CrossProfileDomainInfo result = null;
4978        int size = resultTargetUser.size();
4979        for (int i = 0; i < size; i++) {
4980            ResolveInfo riTargetUser = resultTargetUser.get(i);
4981            // Intent filter verification is only for filters that specify a host. So don't return
4982            // those that handle all web uris.
4983            if (riTargetUser.handleAllWebDataURI) {
4984                continue;
4985            }
4986            String packageName = riTargetUser.activityInfo.packageName;
4987            PackageSetting ps = mSettings.mPackages.get(packageName);
4988            if (ps == null) {
4989                continue;
4990            }
4991            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4992            int status = (int)(verificationState >> 32);
4993            if (result == null) {
4994                result = new CrossProfileDomainInfo();
4995                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4996                        sourceUserId, parentUserId);
4997                result.bestDomainVerificationStatus = status;
4998            } else {
4999                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5000                        result.bestDomainVerificationStatus);
5001            }
5002        }
5003        // Don't consider matches with status NEVER across profiles.
5004        if (result != null && result.bestDomainVerificationStatus
5005                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5006            return null;
5007        }
5008        return result;
5009    }
5010
5011    /**
5012     * Verification statuses are ordered from the worse to the best, except for
5013     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5014     */
5015    private int bestDomainVerificationStatus(int status1, int status2) {
5016        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5017            return status2;
5018        }
5019        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5020            return status1;
5021        }
5022        return (int) MathUtils.max(status1, status2);
5023    }
5024
5025    private boolean isUserEnabled(int userId) {
5026        long callingId = Binder.clearCallingIdentity();
5027        try {
5028            UserInfo userInfo = sUserManager.getUserInfo(userId);
5029            return userInfo != null && userInfo.isEnabled();
5030        } finally {
5031            Binder.restoreCallingIdentity(callingId);
5032        }
5033    }
5034
5035    /**
5036     * Filter out activities with systemUserOnly flag set, when current user is not System.
5037     *
5038     * @return filtered list
5039     */
5040    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5041        if (userId == UserHandle.USER_SYSTEM) {
5042            return resolveInfos;
5043        }
5044        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5045            ResolveInfo info = resolveInfos.get(i);
5046            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5047                resolveInfos.remove(i);
5048            }
5049        }
5050        return resolveInfos;
5051    }
5052
5053    /**
5054     * @param resolveInfos list of resolve infos in descending priority order
5055     * @return if the list contains a resolve info with non-negative priority
5056     */
5057    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5058        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5059    }
5060
5061    private static boolean hasWebURI(Intent intent) {
5062        if (intent.getData() == null) {
5063            return false;
5064        }
5065        final String scheme = intent.getScheme();
5066        if (TextUtils.isEmpty(scheme)) {
5067            return false;
5068        }
5069        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5070    }
5071
5072    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5073            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5074            int userId) {
5075        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5076
5077        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5078            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5079                    candidates.size());
5080        }
5081
5082        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5083        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5084        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5085        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5086        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5087        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5088
5089        synchronized (mPackages) {
5090            final int count = candidates.size();
5091            // First, try to use linked apps. Partition the candidates into four lists:
5092            // one for the final results, one for the "do not use ever", one for "undefined status"
5093            // and finally one for "browser app type".
5094            for (int n=0; n<count; n++) {
5095                ResolveInfo info = candidates.get(n);
5096                String packageName = info.activityInfo.packageName;
5097                PackageSetting ps = mSettings.mPackages.get(packageName);
5098                if (ps != null) {
5099                    // Add to the special match all list (Browser use case)
5100                    if (info.handleAllWebDataURI) {
5101                        matchAllList.add(info);
5102                        continue;
5103                    }
5104                    // Try to get the status from User settings first
5105                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5106                    int status = (int)(packedStatus >> 32);
5107                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5108                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5109                        if (DEBUG_DOMAIN_VERIFICATION) {
5110                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5111                                    + " : linkgen=" + linkGeneration);
5112                        }
5113                        // Use link-enabled generation as preferredOrder, i.e.
5114                        // prefer newly-enabled over earlier-enabled.
5115                        info.preferredOrder = linkGeneration;
5116                        alwaysList.add(info);
5117                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5118                        if (DEBUG_DOMAIN_VERIFICATION) {
5119                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5120                        }
5121                        neverList.add(info);
5122                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5123                        if (DEBUG_DOMAIN_VERIFICATION) {
5124                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5125                        }
5126                        alwaysAskList.add(info);
5127                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5128                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5129                        if (DEBUG_DOMAIN_VERIFICATION) {
5130                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5131                        }
5132                        undefinedList.add(info);
5133                    }
5134                }
5135            }
5136
5137            // We'll want to include browser possibilities in a few cases
5138            boolean includeBrowser = false;
5139
5140            // First try to add the "always" resolution(s) for the current user, if any
5141            if (alwaysList.size() > 0) {
5142                result.addAll(alwaysList);
5143            } else {
5144                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5145                result.addAll(undefinedList);
5146                // Maybe add one for the other profile.
5147                if (xpDomainInfo != null && (
5148                        xpDomainInfo.bestDomainVerificationStatus
5149                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5150                    result.add(xpDomainInfo.resolveInfo);
5151                }
5152                includeBrowser = true;
5153            }
5154
5155            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5156            // If there were 'always' entries their preferred order has been set, so we also
5157            // back that off to make the alternatives equivalent
5158            if (alwaysAskList.size() > 0) {
5159                for (ResolveInfo i : result) {
5160                    i.preferredOrder = 0;
5161                }
5162                result.addAll(alwaysAskList);
5163                includeBrowser = true;
5164            }
5165
5166            if (includeBrowser) {
5167                // Also add browsers (all of them or only the default one)
5168                if (DEBUG_DOMAIN_VERIFICATION) {
5169                    Slog.v(TAG, "   ...including browsers in candidate set");
5170                }
5171                if ((matchFlags & MATCH_ALL) != 0) {
5172                    result.addAll(matchAllList);
5173                } else {
5174                    // Browser/generic handling case.  If there's a default browser, go straight
5175                    // to that (but only if there is no other higher-priority match).
5176                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5177                    int maxMatchPrio = 0;
5178                    ResolveInfo defaultBrowserMatch = null;
5179                    final int numCandidates = matchAllList.size();
5180                    for (int n = 0; n < numCandidates; n++) {
5181                        ResolveInfo info = matchAllList.get(n);
5182                        // track the highest overall match priority...
5183                        if (info.priority > maxMatchPrio) {
5184                            maxMatchPrio = info.priority;
5185                        }
5186                        // ...and the highest-priority default browser match
5187                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5188                            if (defaultBrowserMatch == null
5189                                    || (defaultBrowserMatch.priority < info.priority)) {
5190                                if (debug) {
5191                                    Slog.v(TAG, "Considering default browser match " + info);
5192                                }
5193                                defaultBrowserMatch = info;
5194                            }
5195                        }
5196                    }
5197                    if (defaultBrowserMatch != null
5198                            && defaultBrowserMatch.priority >= maxMatchPrio
5199                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5200                    {
5201                        if (debug) {
5202                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5203                        }
5204                        result.add(defaultBrowserMatch);
5205                    } else {
5206                        result.addAll(matchAllList);
5207                    }
5208                }
5209
5210                // If there is nothing selected, add all candidates and remove the ones that the user
5211                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5212                if (result.size() == 0) {
5213                    result.addAll(candidates);
5214                    result.removeAll(neverList);
5215                }
5216            }
5217        }
5218        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5219            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5220                    result.size());
5221            for (ResolveInfo info : result) {
5222                Slog.v(TAG, "  + " + info.activityInfo);
5223            }
5224        }
5225        return result;
5226    }
5227
5228    // Returns a packed value as a long:
5229    //
5230    // high 'int'-sized word: link status: undefined/ask/never/always.
5231    // low 'int'-sized word: relative priority among 'always' results.
5232    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5233        long result = ps.getDomainVerificationStatusForUser(userId);
5234        // if none available, get the master status
5235        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5236            if (ps.getIntentFilterVerificationInfo() != null) {
5237                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5238            }
5239        }
5240        return result;
5241    }
5242
5243    private ResolveInfo querySkipCurrentProfileIntents(
5244            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5245            int flags, int sourceUserId) {
5246        if (matchingFilters != null) {
5247            int size = matchingFilters.size();
5248            for (int i = 0; i < size; i ++) {
5249                CrossProfileIntentFilter filter = matchingFilters.get(i);
5250                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5251                    // Checking if there are activities in the target user that can handle the
5252                    // intent.
5253                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5254                            resolvedType, flags, sourceUserId);
5255                    if (resolveInfo != null) {
5256                        return resolveInfo;
5257                    }
5258                }
5259            }
5260        }
5261        return null;
5262    }
5263
5264    // Return matching ResolveInfo in target user if any.
5265    private ResolveInfo queryCrossProfileIntents(
5266            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5267            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5268        if (matchingFilters != null) {
5269            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5270            // match the same intent. For performance reasons, it is better not to
5271            // run queryIntent twice for the same userId
5272            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5273            int size = matchingFilters.size();
5274            for (int i = 0; i < size; i++) {
5275                CrossProfileIntentFilter filter = matchingFilters.get(i);
5276                int targetUserId = filter.getTargetUserId();
5277                boolean skipCurrentProfile =
5278                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5279                boolean skipCurrentProfileIfNoMatchFound =
5280                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5281                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5282                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
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) return resolveInfo;
5288                    alreadyTriedUserIds.put(targetUserId, true);
5289                }
5290            }
5291        }
5292        return null;
5293    }
5294
5295    /**
5296     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5297     * will forward the intent to the filter's target user.
5298     * Otherwise, returns null.
5299     */
5300    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5301            String resolvedType, int flags, int sourceUserId) {
5302        int targetUserId = filter.getTargetUserId();
5303        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5304                resolvedType, flags, targetUserId);
5305        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5306                && isUserEnabled(targetUserId)) {
5307            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5308        }
5309        return null;
5310    }
5311
5312    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5313            int sourceUserId, int targetUserId) {
5314        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5315        long ident = Binder.clearCallingIdentity();
5316        boolean targetIsProfile;
5317        try {
5318            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5319        } finally {
5320            Binder.restoreCallingIdentity(ident);
5321        }
5322        String className;
5323        if (targetIsProfile) {
5324            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5325        } else {
5326            className = FORWARD_INTENT_TO_PARENT;
5327        }
5328        ComponentName forwardingActivityComponentName = new ComponentName(
5329                mAndroidApplication.packageName, className);
5330        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5331                sourceUserId);
5332        if (!targetIsProfile) {
5333            forwardingActivityInfo.showUserIcon = targetUserId;
5334            forwardingResolveInfo.noResourceId = true;
5335        }
5336        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5337        forwardingResolveInfo.priority = 0;
5338        forwardingResolveInfo.preferredOrder = 0;
5339        forwardingResolveInfo.match = 0;
5340        forwardingResolveInfo.isDefault = true;
5341        forwardingResolveInfo.filter = filter;
5342        forwardingResolveInfo.targetUserId = targetUserId;
5343        return forwardingResolveInfo;
5344    }
5345
5346    @Override
5347    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5348            Intent[] specifics, String[] specificTypes, Intent intent,
5349            String resolvedType, int flags, int userId) {
5350        if (!sUserManager.exists(userId)) return Collections.emptyList();
5351        flags = augmentFlagsForUser(flags, userId);
5352        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5353                false, "query intent activity options");
5354        final String resultsAction = intent.getAction();
5355
5356        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5357                | PackageManager.GET_RESOLVED_FILTER, userId);
5358
5359        if (DEBUG_INTENT_MATCHING) {
5360            Log.v(TAG, "Query " + intent + ": " + results);
5361        }
5362
5363        int specificsPos = 0;
5364        int N;
5365
5366        // todo: note that the algorithm used here is O(N^2).  This
5367        // isn't a problem in our current environment, but if we start running
5368        // into situations where we have more than 5 or 10 matches then this
5369        // should probably be changed to something smarter...
5370
5371        // First we go through and resolve each of the specific items
5372        // that were supplied, taking care of removing any corresponding
5373        // duplicate items in the generic resolve list.
5374        if (specifics != null) {
5375            for (int i=0; i<specifics.length; i++) {
5376                final Intent sintent = specifics[i];
5377                if (sintent == null) {
5378                    continue;
5379                }
5380
5381                if (DEBUG_INTENT_MATCHING) {
5382                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5383                }
5384
5385                String action = sintent.getAction();
5386                if (resultsAction != null && resultsAction.equals(action)) {
5387                    // If this action was explicitly requested, then don't
5388                    // remove things that have it.
5389                    action = null;
5390                }
5391
5392                ResolveInfo ri = null;
5393                ActivityInfo ai = null;
5394
5395                ComponentName comp = sintent.getComponent();
5396                if (comp == null) {
5397                    ri = resolveIntent(
5398                        sintent,
5399                        specificTypes != null ? specificTypes[i] : null,
5400                            flags, userId);
5401                    if (ri == null) {
5402                        continue;
5403                    }
5404                    if (ri == mResolveInfo) {
5405                        // ACK!  Must do something better with this.
5406                    }
5407                    ai = ri.activityInfo;
5408                    comp = new ComponentName(ai.applicationInfo.packageName,
5409                            ai.name);
5410                } else {
5411                    ai = getActivityInfo(comp, flags, userId);
5412                    if (ai == null) {
5413                        continue;
5414                    }
5415                }
5416
5417                // Look for any generic query activities that are duplicates
5418                // of this specific one, and remove them from the results.
5419                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5420                N = results.size();
5421                int j;
5422                for (j=specificsPos; j<N; j++) {
5423                    ResolveInfo sri = results.get(j);
5424                    if ((sri.activityInfo.name.equals(comp.getClassName())
5425                            && sri.activityInfo.applicationInfo.packageName.equals(
5426                                    comp.getPackageName()))
5427                        || (action != null && sri.filter.matchAction(action))) {
5428                        results.remove(j);
5429                        if (DEBUG_INTENT_MATCHING) Log.v(
5430                            TAG, "Removing duplicate item from " + j
5431                            + " due to specific " + specificsPos);
5432                        if (ri == null) {
5433                            ri = sri;
5434                        }
5435                        j--;
5436                        N--;
5437                    }
5438                }
5439
5440                // Add this specific item to its proper place.
5441                if (ri == null) {
5442                    ri = new ResolveInfo();
5443                    ri.activityInfo = ai;
5444                }
5445                results.add(specificsPos, ri);
5446                ri.specificIndex = i;
5447                specificsPos++;
5448            }
5449        }
5450
5451        // Now we go through the remaining generic results and remove any
5452        // duplicate actions that are found here.
5453        N = results.size();
5454        for (int i=specificsPos; i<N-1; i++) {
5455            final ResolveInfo rii = results.get(i);
5456            if (rii.filter == null) {
5457                continue;
5458            }
5459
5460            // Iterate over all of the actions of this result's intent
5461            // filter...  typically this should be just one.
5462            final Iterator<String> it = rii.filter.actionsIterator();
5463            if (it == null) {
5464                continue;
5465            }
5466            while (it.hasNext()) {
5467                final String action = it.next();
5468                if (resultsAction != null && resultsAction.equals(action)) {
5469                    // If this action was explicitly requested, then don't
5470                    // remove things that have it.
5471                    continue;
5472                }
5473                for (int j=i+1; j<N; j++) {
5474                    final ResolveInfo rij = results.get(j);
5475                    if (rij.filter != null && rij.filter.hasAction(action)) {
5476                        results.remove(j);
5477                        if (DEBUG_INTENT_MATCHING) Log.v(
5478                            TAG, "Removing duplicate item from " + j
5479                            + " due to action " + action + " at " + i);
5480                        j--;
5481                        N--;
5482                    }
5483                }
5484            }
5485
5486            // If the caller didn't request filter information, drop it now
5487            // so we don't have to marshall/unmarshall it.
5488            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5489                rii.filter = null;
5490            }
5491        }
5492
5493        // Filter out the caller activity if so requested.
5494        if (caller != null) {
5495            N = results.size();
5496            for (int i=0; i<N; i++) {
5497                ActivityInfo ainfo = results.get(i).activityInfo;
5498                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5499                        && caller.getClassName().equals(ainfo.name)) {
5500                    results.remove(i);
5501                    break;
5502                }
5503            }
5504        }
5505
5506        // If the caller didn't request filter information,
5507        // drop them now so we don't have to
5508        // marshall/unmarshall it.
5509        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5510            N = results.size();
5511            for (int i=0; i<N; i++) {
5512                results.get(i).filter = null;
5513            }
5514        }
5515
5516        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5517        return results;
5518    }
5519
5520    @Override
5521    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5522            int userId) {
5523        if (!sUserManager.exists(userId)) return Collections.emptyList();
5524        flags = augmentFlagsForUser(flags, userId);
5525        ComponentName comp = intent.getComponent();
5526        if (comp == null) {
5527            if (intent.getSelector() != null) {
5528                intent = intent.getSelector();
5529                comp = intent.getComponent();
5530            }
5531        }
5532        if (comp != null) {
5533            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5534            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5535            if (ai != null) {
5536                ResolveInfo ri = new ResolveInfo();
5537                ri.activityInfo = ai;
5538                list.add(ri);
5539            }
5540            return list;
5541        }
5542
5543        // reader
5544        synchronized (mPackages) {
5545            String pkgName = intent.getPackage();
5546            if (pkgName == null) {
5547                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5548            }
5549            final PackageParser.Package pkg = mPackages.get(pkgName);
5550            if (pkg != null) {
5551                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5552                        userId);
5553            }
5554            return null;
5555        }
5556    }
5557
5558    @Override
5559    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5560        if (!sUserManager.exists(userId)) return null;
5561        flags = augmentFlagsForUser(flags, userId);
5562        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5563        if (query != null) {
5564            if (query.size() >= 1) {
5565                // If there is more than one service with the same priority,
5566                // just arbitrarily pick the first one.
5567                return query.get(0);
5568            }
5569        }
5570        return null;
5571    }
5572
5573    @Override
5574    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5575            int userId) {
5576        if (!sUserManager.exists(userId)) return Collections.emptyList();
5577        flags = augmentFlagsForUser(flags, userId);
5578        ComponentName comp = intent.getComponent();
5579        if (comp == null) {
5580            if (intent.getSelector() != null) {
5581                intent = intent.getSelector();
5582                comp = intent.getComponent();
5583            }
5584        }
5585        if (comp != null) {
5586            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5587            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5588            if (si != null) {
5589                final ResolveInfo ri = new ResolveInfo();
5590                ri.serviceInfo = si;
5591                list.add(ri);
5592            }
5593            return list;
5594        }
5595
5596        // reader
5597        synchronized (mPackages) {
5598            String pkgName = intent.getPackage();
5599            if (pkgName == null) {
5600                return mServices.queryIntent(intent, resolvedType, flags, userId);
5601            }
5602            final PackageParser.Package pkg = mPackages.get(pkgName);
5603            if (pkg != null) {
5604                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5605                        userId);
5606            }
5607            return null;
5608        }
5609    }
5610
5611    @Override
5612    public List<ResolveInfo> queryIntentContentProviders(
5613            Intent intent, String resolvedType, int flags, int userId) {
5614        if (!sUserManager.exists(userId)) return Collections.emptyList();
5615        flags = augmentFlagsForUser(flags, userId);
5616        ComponentName comp = intent.getComponent();
5617        if (comp == null) {
5618            if (intent.getSelector() != null) {
5619                intent = intent.getSelector();
5620                comp = intent.getComponent();
5621            }
5622        }
5623        if (comp != null) {
5624            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5625            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5626            if (pi != null) {
5627                final ResolveInfo ri = new ResolveInfo();
5628                ri.providerInfo = pi;
5629                list.add(ri);
5630            }
5631            return list;
5632        }
5633
5634        // reader
5635        synchronized (mPackages) {
5636            String pkgName = intent.getPackage();
5637            if (pkgName == null) {
5638                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5639            }
5640            final PackageParser.Package pkg = mPackages.get(pkgName);
5641            if (pkg != null) {
5642                return mProviders.queryIntentForPackage(
5643                        intent, resolvedType, flags, pkg.providers, userId);
5644            }
5645            return null;
5646        }
5647    }
5648
5649    @Override
5650    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5651        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5652
5653        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5654
5655        // writer
5656        synchronized (mPackages) {
5657            ArrayList<PackageInfo> list;
5658            if (listUninstalled) {
5659                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5660                for (PackageSetting ps : mSettings.mPackages.values()) {
5661                    PackageInfo pi;
5662                    if (ps.pkg != null) {
5663                        pi = generatePackageInfo(ps.pkg, flags, userId);
5664                    } else {
5665                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5666                    }
5667                    if (pi != null) {
5668                        list.add(pi);
5669                    }
5670                }
5671            } else {
5672                list = new ArrayList<PackageInfo>(mPackages.size());
5673                for (PackageParser.Package p : mPackages.values()) {
5674                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5675                    if (pi != null) {
5676                        list.add(pi);
5677                    }
5678                }
5679            }
5680
5681            return new ParceledListSlice<PackageInfo>(list);
5682        }
5683    }
5684
5685    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5686            String[] permissions, boolean[] tmp, int flags, int userId) {
5687        int numMatch = 0;
5688        final PermissionsState permissionsState = ps.getPermissionsState();
5689        for (int i=0; i<permissions.length; i++) {
5690            final String permission = permissions[i];
5691            if (permissionsState.hasPermission(permission, userId)) {
5692                tmp[i] = true;
5693                numMatch++;
5694            } else {
5695                tmp[i] = false;
5696            }
5697        }
5698        if (numMatch == 0) {
5699            return;
5700        }
5701        PackageInfo pi;
5702        if (ps.pkg != null) {
5703            pi = generatePackageInfo(ps.pkg, flags, userId);
5704        } else {
5705            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5706        }
5707        // The above might return null in cases of uninstalled apps or install-state
5708        // skew across users/profiles.
5709        if (pi != null) {
5710            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5711                if (numMatch == permissions.length) {
5712                    pi.requestedPermissions = permissions;
5713                } else {
5714                    pi.requestedPermissions = new String[numMatch];
5715                    numMatch = 0;
5716                    for (int i=0; i<permissions.length; i++) {
5717                        if (tmp[i]) {
5718                            pi.requestedPermissions[numMatch] = permissions[i];
5719                            numMatch++;
5720                        }
5721                    }
5722                }
5723            }
5724            list.add(pi);
5725        }
5726    }
5727
5728    @Override
5729    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5730            String[] permissions, int flags, int userId) {
5731        if (!sUserManager.exists(userId)) return null;
5732        flags = augmentFlagsForUser(flags, userId);
5733        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5734
5735        // writer
5736        synchronized (mPackages) {
5737            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5738            boolean[] tmpBools = new boolean[permissions.length];
5739            if (listUninstalled) {
5740                for (PackageSetting ps : mSettings.mPackages.values()) {
5741                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5742                }
5743            } else {
5744                for (PackageParser.Package pkg : mPackages.values()) {
5745                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5746                    if (ps != null) {
5747                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5748                                userId);
5749                    }
5750                }
5751            }
5752
5753            return new ParceledListSlice<PackageInfo>(list);
5754        }
5755    }
5756
5757    @Override
5758    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5759        if (!sUserManager.exists(userId)) return null;
5760        flags = augmentFlagsForUser(flags, userId);
5761        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5762
5763        // writer
5764        synchronized (mPackages) {
5765            ArrayList<ApplicationInfo> list;
5766            if (listUninstalled) {
5767                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5768                for (PackageSetting ps : mSettings.mPackages.values()) {
5769                    ApplicationInfo ai;
5770                    if (ps.pkg != null) {
5771                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5772                                ps.readUserState(userId), userId);
5773                    } else {
5774                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5775                    }
5776                    if (ai != null) {
5777                        list.add(ai);
5778                    }
5779                }
5780            } else {
5781                list = new ArrayList<ApplicationInfo>(mPackages.size());
5782                for (PackageParser.Package p : mPackages.values()) {
5783                    if (p.mExtras != null) {
5784                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5785                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5786                        if (ai != null) {
5787                            list.add(ai);
5788                        }
5789                    }
5790                }
5791            }
5792
5793            return new ParceledListSlice<ApplicationInfo>(list);
5794        }
5795    }
5796
5797    @Override
5798    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5799        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5800                "getEphemeralApplications");
5801        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5802                "getEphemeralApplications");
5803        synchronized (mPackages) {
5804            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5805                    .getEphemeralApplicationsLPw(userId);
5806            if (ephemeralApps != null) {
5807                return new ParceledListSlice<>(ephemeralApps);
5808            }
5809        }
5810        return null;
5811    }
5812
5813    @Override
5814    public boolean isEphemeralApplication(String packageName, int userId) {
5815        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5816                "isEphemeral");
5817        if (!isCallerSameApp(packageName)) {
5818            return false;
5819        }
5820        synchronized (mPackages) {
5821            PackageParser.Package pkg = mPackages.get(packageName);
5822            if (pkg != null) {
5823                return pkg.applicationInfo.isEphemeralApp();
5824            }
5825        }
5826        return false;
5827    }
5828
5829    @Override
5830    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5831        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5832                "getCookie");
5833        if (!isCallerSameApp(packageName)) {
5834            return null;
5835        }
5836        synchronized (mPackages) {
5837            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5838                    packageName, userId);
5839        }
5840    }
5841
5842    @Override
5843    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5844        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5845                "setCookie");
5846        if (!isCallerSameApp(packageName)) {
5847            return false;
5848        }
5849        synchronized (mPackages) {
5850            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5851                    packageName, cookie, userId);
5852        }
5853    }
5854
5855    @Override
5856    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5857        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5858                "getEphemeralApplicationIcon");
5859        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5860                "getEphemeralApplicationIcon");
5861        synchronized (mPackages) {
5862            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5863                    packageName, userId);
5864        }
5865    }
5866
5867    private boolean isCallerSameApp(String packageName) {
5868        PackageParser.Package pkg = mPackages.get(packageName);
5869        return pkg != null
5870                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5871    }
5872
5873    public List<ApplicationInfo> getPersistentApplications(int flags) {
5874        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5875
5876        // reader
5877        synchronized (mPackages) {
5878            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5879            final int userId = UserHandle.getCallingUserId();
5880            while (i.hasNext()) {
5881                final PackageParser.Package p = i.next();
5882                if (p.applicationInfo != null
5883                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5884                        && (!mSafeMode || isSystemApp(p))) {
5885                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5886                    if (ps != null) {
5887                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5888                                ps.readUserState(userId), userId);
5889                        if (ai != null) {
5890                            finalList.add(ai);
5891                        }
5892                    }
5893                }
5894            }
5895        }
5896
5897        return finalList;
5898    }
5899
5900    @Override
5901    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5902        if (!sUserManager.exists(userId)) return null;
5903        flags = augmentFlagsForUser(flags, userId);
5904        // reader
5905        synchronized (mPackages) {
5906            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5907            PackageSetting ps = provider != null
5908                    ? mSettings.mPackages.get(provider.owner.packageName)
5909                    : null;
5910            return ps != null
5911                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5912                    && (!mSafeMode || (provider.info.applicationInfo.flags
5913                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5914                    ? PackageParser.generateProviderInfo(provider, flags,
5915                            ps.readUserState(userId), userId)
5916                    : null;
5917        }
5918    }
5919
5920    /**
5921     * @deprecated
5922     */
5923    @Deprecated
5924    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5925        // reader
5926        synchronized (mPackages) {
5927            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5928                    .entrySet().iterator();
5929            final int userId = UserHandle.getCallingUserId();
5930            while (i.hasNext()) {
5931                Map.Entry<String, PackageParser.Provider> entry = i.next();
5932                PackageParser.Provider p = entry.getValue();
5933                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5934
5935                if (ps != null && p.syncable
5936                        && (!mSafeMode || (p.info.applicationInfo.flags
5937                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5938                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5939                            ps.readUserState(userId), userId);
5940                    if (info != null) {
5941                        outNames.add(entry.getKey());
5942                        outInfo.add(info);
5943                    }
5944                }
5945            }
5946        }
5947    }
5948
5949    @Override
5950    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5951            int uid, int flags) {
5952        final int userId = processName != null ? UserHandle.getUserId(uid)
5953                : UserHandle.getCallingUserId();
5954        if (!sUserManager.exists(userId)) return null;
5955        flags = augmentFlagsForUser(flags, userId);
5956
5957        ArrayList<ProviderInfo> finalList = null;
5958        // reader
5959        synchronized (mPackages) {
5960            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5961            while (i.hasNext()) {
5962                final PackageParser.Provider p = i.next();
5963                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5964                if (ps != null && p.info.authority != null
5965                        && (processName == null
5966                                || (p.info.processName.equals(processName)
5967                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5968                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5969                        && (!mSafeMode
5970                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5971                    if (finalList == null) {
5972                        finalList = new ArrayList<ProviderInfo>(3);
5973                    }
5974                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5975                            ps.readUserState(userId), userId);
5976                    if (info != null) {
5977                        finalList.add(info);
5978                    }
5979                }
5980            }
5981        }
5982
5983        if (finalList != null) {
5984            Collections.sort(finalList, mProviderInitOrderSorter);
5985            return new ParceledListSlice<ProviderInfo>(finalList);
5986        }
5987
5988        return null;
5989    }
5990
5991    @Override
5992    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5993            int flags) {
5994        // reader
5995        synchronized (mPackages) {
5996            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5997            return PackageParser.generateInstrumentationInfo(i, flags);
5998        }
5999    }
6000
6001    @Override
6002    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6003            int flags) {
6004        ArrayList<InstrumentationInfo> finalList =
6005            new ArrayList<InstrumentationInfo>();
6006
6007        // reader
6008        synchronized (mPackages) {
6009            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6010            while (i.hasNext()) {
6011                final PackageParser.Instrumentation p = i.next();
6012                if (targetPackage == null
6013                        || targetPackage.equals(p.info.targetPackage)) {
6014                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6015                            flags);
6016                    if (ii != null) {
6017                        finalList.add(ii);
6018                    }
6019                }
6020            }
6021        }
6022
6023        return finalList;
6024    }
6025
6026    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6027        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6028        if (overlays == null) {
6029            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6030            return;
6031        }
6032        for (PackageParser.Package opkg : overlays.values()) {
6033            // Not much to do if idmap fails: we already logged the error
6034            // and we certainly don't want to abort installation of pkg simply
6035            // because an overlay didn't fit properly. For these reasons,
6036            // ignore the return value of createIdmapForPackagePairLI.
6037            createIdmapForPackagePairLI(pkg, opkg);
6038        }
6039    }
6040
6041    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6042            PackageParser.Package opkg) {
6043        if (!opkg.mTrustedOverlay) {
6044            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6045                    opkg.baseCodePath + ": overlay not trusted");
6046            return false;
6047        }
6048        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6049        if (overlaySet == null) {
6050            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6051                    opkg.baseCodePath + " but target package has no known overlays");
6052            return false;
6053        }
6054        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6055        // TODO: generate idmap for split APKs
6056        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6057            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6058                    + opkg.baseCodePath);
6059            return false;
6060        }
6061        PackageParser.Package[] overlayArray =
6062            overlaySet.values().toArray(new PackageParser.Package[0]);
6063        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6064            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6065                return p1.mOverlayPriority - p2.mOverlayPriority;
6066            }
6067        };
6068        Arrays.sort(overlayArray, cmp);
6069
6070        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6071        int i = 0;
6072        for (PackageParser.Package p : overlayArray) {
6073            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6074        }
6075        return true;
6076    }
6077
6078    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6079        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6080        try {
6081            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6082        } finally {
6083            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6084        }
6085    }
6086
6087    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6088        final File[] files = dir.listFiles();
6089        if (ArrayUtils.isEmpty(files)) {
6090            Log.d(TAG, "No files in app dir " + dir);
6091            return;
6092        }
6093
6094        if (DEBUG_PACKAGE_SCANNING) {
6095            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6096                    + " flags=0x" + Integer.toHexString(parseFlags));
6097        }
6098
6099        for (File file : files) {
6100            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6101                    && !PackageInstallerService.isStageName(file.getName());
6102            if (!isPackage) {
6103                // Ignore entries which are not packages
6104                continue;
6105            }
6106            try {
6107                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6108                        scanFlags, currentTime, null);
6109            } catch (PackageManagerException e) {
6110                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6111
6112                // Delete invalid userdata apps
6113                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6114                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6115                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6116                    if (file.isDirectory()) {
6117                        mInstaller.rmPackageDir(file.getAbsolutePath());
6118                    } else {
6119                        file.delete();
6120                    }
6121                }
6122            }
6123        }
6124    }
6125
6126    private static File getSettingsProblemFile() {
6127        File dataDir = Environment.getDataDirectory();
6128        File systemDir = new File(dataDir, "system");
6129        File fname = new File(systemDir, "uiderrors.txt");
6130        return fname;
6131    }
6132
6133    static void reportSettingsProblem(int priority, String msg) {
6134        logCriticalInfo(priority, msg);
6135    }
6136
6137    static void logCriticalInfo(int priority, String msg) {
6138        Slog.println(priority, TAG, msg);
6139        EventLogTags.writePmCriticalInfo(msg);
6140        try {
6141            File fname = getSettingsProblemFile();
6142            FileOutputStream out = new FileOutputStream(fname, true);
6143            PrintWriter pw = new FastPrintWriter(out);
6144            SimpleDateFormat formatter = new SimpleDateFormat();
6145            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6146            pw.println(dateString + ": " + msg);
6147            pw.close();
6148            FileUtils.setPermissions(
6149                    fname.toString(),
6150                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6151                    -1, -1);
6152        } catch (java.io.IOException e) {
6153        }
6154    }
6155
6156    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6157            PackageParser.Package pkg, File srcFile, int parseFlags)
6158            throws PackageManagerException {
6159        if (ps != null
6160                && ps.codePath.equals(srcFile)
6161                && ps.timeStamp == srcFile.lastModified()
6162                && !isCompatSignatureUpdateNeeded(pkg)
6163                && !isRecoverSignatureUpdateNeeded(pkg)) {
6164            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6165            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6166            ArraySet<PublicKey> signingKs;
6167            synchronized (mPackages) {
6168                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6169            }
6170            if (ps.signatures.mSignatures != null
6171                    && ps.signatures.mSignatures.length != 0
6172                    && signingKs != null) {
6173                // Optimization: reuse the existing cached certificates
6174                // if the package appears to be unchanged.
6175                pkg.mSignatures = ps.signatures.mSignatures;
6176                pkg.mSigningKeys = signingKs;
6177                return;
6178            }
6179
6180            Slog.w(TAG, "PackageSetting for " + ps.name
6181                    + " is missing signatures.  Collecting certs again to recover them.");
6182        } else {
6183            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6184        }
6185
6186        try {
6187            pp.collectCertificates(pkg, parseFlags);
6188            pp.collectManifestDigest(pkg);
6189        } catch (PackageParserException e) {
6190            throw PackageManagerException.from(e);
6191        }
6192    }
6193
6194    /**
6195     *  Traces a package scan.
6196     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6197     */
6198    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6199            long currentTime, UserHandle user) throws PackageManagerException {
6200        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6201        try {
6202            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6203        } finally {
6204            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6205        }
6206    }
6207
6208    /**
6209     *  Scans a package and returns the newly parsed package.
6210     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6211     */
6212    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6213            long currentTime, UserHandle user) throws PackageManagerException {
6214        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6215        parseFlags |= mDefParseFlags;
6216        PackageParser pp = new PackageParser();
6217        pp.setSeparateProcesses(mSeparateProcesses);
6218        pp.setOnlyCoreApps(mOnlyCore);
6219        pp.setDisplayMetrics(mMetrics);
6220
6221        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6222            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6223        }
6224
6225        final PackageParser.Package pkg;
6226        try {
6227            pkg = pp.parsePackage(scanFile, parseFlags);
6228        } catch (PackageParserException e) {
6229            throw PackageManagerException.from(e);
6230        }
6231
6232        PackageSetting ps = null;
6233        PackageSetting updatedPkg;
6234        // reader
6235        synchronized (mPackages) {
6236            // Look to see if we already know about this package.
6237            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6238            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6239                // This package has been renamed to its original name.  Let's
6240                // use that.
6241                ps = mSettings.peekPackageLPr(oldName);
6242            }
6243            // If there was no original package, see one for the real package name.
6244            if (ps == null) {
6245                ps = mSettings.peekPackageLPr(pkg.packageName);
6246            }
6247            // Check to see if this package could be hiding/updating a system
6248            // package.  Must look for it either under the original or real
6249            // package name depending on our state.
6250            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6251            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6252        }
6253        boolean updatedPkgBetter = false;
6254        // First check if this is a system package that may involve an update
6255        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6256            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6257            // it needs to drop FLAG_PRIVILEGED.
6258            if (locationIsPrivileged(scanFile)) {
6259                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6260            } else {
6261                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6262            }
6263
6264            if (ps != null && !ps.codePath.equals(scanFile)) {
6265                // The path has changed from what was last scanned...  check the
6266                // version of the new path against what we have stored to determine
6267                // what to do.
6268                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6269                if (pkg.mVersionCode <= ps.versionCode) {
6270                    // The system package has been updated and the code path does not match
6271                    // Ignore entry. Skip it.
6272                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6273                            + " ignored: updated version " + ps.versionCode
6274                            + " better than this " + pkg.mVersionCode);
6275                    if (!updatedPkg.codePath.equals(scanFile)) {
6276                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6277                                + ps.name + " changing from " + updatedPkg.codePathString
6278                                + " to " + scanFile);
6279                        updatedPkg.codePath = scanFile;
6280                        updatedPkg.codePathString = scanFile.toString();
6281                        updatedPkg.resourcePath = scanFile;
6282                        updatedPkg.resourcePathString = scanFile.toString();
6283                    }
6284                    updatedPkg.pkg = pkg;
6285                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6286                            "Package " + ps.name + " at " + scanFile
6287                                    + " ignored: updated version " + ps.versionCode
6288                                    + " better than this " + pkg.mVersionCode);
6289                } else {
6290                    // The current app on the system partition is better than
6291                    // what we have updated to on the data partition; switch
6292                    // back to the system partition version.
6293                    // At this point, its safely assumed that package installation for
6294                    // apps in system partition will go through. If not there won't be a working
6295                    // version of the app
6296                    // writer
6297                    synchronized (mPackages) {
6298                        // Just remove the loaded entries from package lists.
6299                        mPackages.remove(ps.name);
6300                    }
6301
6302                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6303                            + " reverting from " + ps.codePathString
6304                            + ": new version " + pkg.mVersionCode
6305                            + " better than installed " + ps.versionCode);
6306
6307                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6308                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6309                    synchronized (mInstallLock) {
6310                        args.cleanUpResourcesLI();
6311                    }
6312                    synchronized (mPackages) {
6313                        mSettings.enableSystemPackageLPw(ps.name);
6314                    }
6315                    updatedPkgBetter = true;
6316                }
6317            }
6318        }
6319
6320        if (updatedPkg != null) {
6321            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6322            // initially
6323            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6324
6325            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6326            // flag set initially
6327            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6328                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6329            }
6330        }
6331
6332        // Verify certificates against what was last scanned
6333        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6334
6335        /*
6336         * A new system app appeared, but we already had a non-system one of the
6337         * same name installed earlier.
6338         */
6339        boolean shouldHideSystemApp = false;
6340        if (updatedPkg == null && ps != null
6341                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6342            /*
6343             * Check to make sure the signatures match first. If they don't,
6344             * wipe the installed application and its data.
6345             */
6346            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6347                    != PackageManager.SIGNATURE_MATCH) {
6348                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6349                        + " signatures don't match existing userdata copy; removing");
6350                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6351                ps = null;
6352            } else {
6353                /*
6354                 * If the newly-added system app is an older version than the
6355                 * already installed version, hide it. It will be scanned later
6356                 * and re-added like an update.
6357                 */
6358                if (pkg.mVersionCode <= ps.versionCode) {
6359                    shouldHideSystemApp = true;
6360                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6361                            + " but new version " + pkg.mVersionCode + " better than installed "
6362                            + ps.versionCode + "; hiding system");
6363                } else {
6364                    /*
6365                     * The newly found system app is a newer version that the
6366                     * one previously installed. Simply remove the
6367                     * already-installed application and replace it with our own
6368                     * while keeping the application data.
6369                     */
6370                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6371                            + " reverting from " + ps.codePathString + ": new version "
6372                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6373                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6374                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6375                    synchronized (mInstallLock) {
6376                        args.cleanUpResourcesLI();
6377                    }
6378                }
6379            }
6380        }
6381
6382        // The apk is forward locked (not public) if its code and resources
6383        // are kept in different files. (except for app in either system or
6384        // vendor path).
6385        // TODO grab this value from PackageSettings
6386        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6387            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6388                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6389            }
6390        }
6391
6392        // TODO: extend to support forward-locked splits
6393        String resourcePath = null;
6394        String baseResourcePath = null;
6395        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6396            if (ps != null && ps.resourcePathString != null) {
6397                resourcePath = ps.resourcePathString;
6398                baseResourcePath = ps.resourcePathString;
6399            } else {
6400                // Should not happen at all. Just log an error.
6401                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6402            }
6403        } else {
6404            resourcePath = pkg.codePath;
6405            baseResourcePath = pkg.baseCodePath;
6406        }
6407
6408        // Set application objects path explicitly.
6409        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6410        pkg.applicationInfo.setCodePath(pkg.codePath);
6411        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6412        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6413        pkg.applicationInfo.setResourcePath(resourcePath);
6414        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6415        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6416
6417        // Note that we invoke the following method only if we are about to unpack an application
6418        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6419                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6420
6421        /*
6422         * If the system app should be overridden by a previously installed
6423         * data, hide the system app now and let the /data/app scan pick it up
6424         * again.
6425         */
6426        if (shouldHideSystemApp) {
6427            synchronized (mPackages) {
6428                mSettings.disableSystemPackageLPw(pkg.packageName);
6429            }
6430        }
6431
6432        return scannedPkg;
6433    }
6434
6435    private static String fixProcessName(String defProcessName,
6436            String processName, int uid) {
6437        if (processName == null) {
6438            return defProcessName;
6439        }
6440        return processName;
6441    }
6442
6443    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6444            throws PackageManagerException {
6445        if (pkgSetting.signatures.mSignatures != null) {
6446            // Already existing package. Make sure signatures match
6447            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6448                    == PackageManager.SIGNATURE_MATCH;
6449            if (!match) {
6450                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6451                        == PackageManager.SIGNATURE_MATCH;
6452            }
6453            if (!match) {
6454                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6455                        == PackageManager.SIGNATURE_MATCH;
6456            }
6457            if (!match) {
6458                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6459                        + pkg.packageName + " signatures do not match the "
6460                        + "previously installed version; ignoring!");
6461            }
6462        }
6463
6464        // Check for shared user signatures
6465        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6466            // Already existing package. Make sure signatures match
6467            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6468                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6469            if (!match) {
6470                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6471                        == PackageManager.SIGNATURE_MATCH;
6472            }
6473            if (!match) {
6474                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6475                        == PackageManager.SIGNATURE_MATCH;
6476            }
6477            if (!match) {
6478                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6479                        "Package " + pkg.packageName
6480                        + " has no signatures that match those in shared user "
6481                        + pkgSetting.sharedUser.name + "; ignoring!");
6482            }
6483        }
6484    }
6485
6486    /**
6487     * Enforces that only the system UID or root's UID can call a method exposed
6488     * via Binder.
6489     *
6490     * @param message used as message if SecurityException is thrown
6491     * @throws SecurityException if the caller is not system or root
6492     */
6493    private static final void enforceSystemOrRoot(String message) {
6494        final int uid = Binder.getCallingUid();
6495        if (uid != Process.SYSTEM_UID && uid != 0) {
6496            throw new SecurityException(message);
6497        }
6498    }
6499
6500    @Override
6501    public void performFstrimIfNeeded() {
6502        enforceSystemOrRoot("Only the system can request fstrim");
6503
6504        // Before everything else, see whether we need to fstrim.
6505        try {
6506            IMountService ms = PackageHelper.getMountService();
6507            if (ms != null) {
6508                final boolean isUpgrade = isUpgrade();
6509                boolean doTrim = isUpgrade;
6510                if (doTrim) {
6511                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6512                } else {
6513                    final long interval = android.provider.Settings.Global.getLong(
6514                            mContext.getContentResolver(),
6515                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6516                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6517                    if (interval > 0) {
6518                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6519                        if (timeSinceLast > interval) {
6520                            doTrim = true;
6521                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6522                                    + "; running immediately");
6523                        }
6524                    }
6525                }
6526                if (doTrim) {
6527                    if (!isFirstBoot()) {
6528                        try {
6529                            ActivityManagerNative.getDefault().showBootMessage(
6530                                    mContext.getResources().getString(
6531                                            R.string.android_upgrading_fstrim), true);
6532                        } catch (RemoteException e) {
6533                        }
6534                    }
6535                    ms.runMaintenance();
6536                }
6537            } else {
6538                Slog.e(TAG, "Mount service unavailable!");
6539            }
6540        } catch (RemoteException e) {
6541            // Can't happen; MountService is local
6542        }
6543    }
6544
6545    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6546        List<ResolveInfo> ris = null;
6547        try {
6548            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6549                    intent, null, 0, userId);
6550        } catch (RemoteException e) {
6551        }
6552        ArraySet<String> pkgNames = new ArraySet<String>();
6553        if (ris != null) {
6554            for (ResolveInfo ri : ris) {
6555                pkgNames.add(ri.activityInfo.packageName);
6556            }
6557        }
6558        return pkgNames;
6559    }
6560
6561    @Override
6562    public void notifyPackageUse(String packageName) {
6563        synchronized (mPackages) {
6564            PackageParser.Package p = mPackages.get(packageName);
6565            if (p == null) {
6566                return;
6567            }
6568            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6569        }
6570    }
6571
6572    @Override
6573    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6574        return performDexOptTraced(packageName, instructionSet);
6575    }
6576
6577    public boolean performDexOpt(String packageName, String instructionSet) {
6578        return performDexOptTraced(packageName, instructionSet);
6579    }
6580
6581    private boolean performDexOptTraced(String packageName, String instructionSet) {
6582        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6583        try {
6584            return performDexOptInternal(packageName, instructionSet);
6585        } finally {
6586            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6587        }
6588    }
6589
6590    private boolean performDexOptInternal(String packageName, String instructionSet) {
6591        PackageParser.Package p;
6592        final String targetInstructionSet;
6593        synchronized (mPackages) {
6594            p = mPackages.get(packageName);
6595            if (p == null) {
6596                return false;
6597            }
6598            mPackageUsage.write(false);
6599
6600            targetInstructionSet = instructionSet != null ? instructionSet :
6601                    getPrimaryInstructionSet(p.applicationInfo);
6602            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6603                return false;
6604            }
6605        }
6606        long callingId = Binder.clearCallingIdentity();
6607        try {
6608            synchronized (mInstallLock) {
6609                final String[] instructionSets = new String[] { targetInstructionSet };
6610                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6611                        true /* inclDependencies */);
6612                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6613            }
6614        } finally {
6615            Binder.restoreCallingIdentity(callingId);
6616        }
6617    }
6618
6619    public ArraySet<String> getPackagesThatNeedDexOpt() {
6620        ArraySet<String> pkgs = null;
6621        synchronized (mPackages) {
6622            for (PackageParser.Package p : mPackages.values()) {
6623                if (DEBUG_DEXOPT) {
6624                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6625                }
6626                if (!p.mDexOptPerformed.isEmpty()) {
6627                    continue;
6628                }
6629                if (pkgs == null) {
6630                    pkgs = new ArraySet<String>();
6631                }
6632                pkgs.add(p.packageName);
6633            }
6634        }
6635        return pkgs;
6636    }
6637
6638    public void shutdown() {
6639        mPackageUsage.write(true);
6640    }
6641
6642    @Override
6643    public void forceDexOpt(String packageName) {
6644        enforceSystemOrRoot("forceDexOpt");
6645
6646        PackageParser.Package pkg;
6647        synchronized (mPackages) {
6648            pkg = mPackages.get(packageName);
6649            if (pkg == null) {
6650                throw new IllegalArgumentException("Missing package: " + packageName);
6651            }
6652        }
6653
6654        synchronized (mInstallLock) {
6655            final String[] instructionSets = new String[] {
6656                    getPrimaryInstructionSet(pkg.applicationInfo) };
6657
6658            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6659
6660            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6661                    true /* inclDependencies */);
6662
6663            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6664            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6665                throw new IllegalStateException("Failed to dexopt: " + res);
6666            }
6667        }
6668    }
6669
6670    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6671        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6672            Slog.w(TAG, "Unable to update from " + oldPkg.name
6673                    + " to " + newPkg.packageName
6674                    + ": old package not in system partition");
6675            return false;
6676        } else if (mPackages.get(oldPkg.name) != null) {
6677            Slog.w(TAG, "Unable to update from " + oldPkg.name
6678                    + " to " + newPkg.packageName
6679                    + ": old package still exists");
6680            return false;
6681        }
6682        return true;
6683    }
6684
6685    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6686            throws PackageManagerException {
6687        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6688        if (res != 0) {
6689            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6690                    "Failed to install " + packageName + ": " + res);
6691        }
6692
6693        final int[] users = sUserManager.getUserIds();
6694        for (int user : users) {
6695            if (user != 0) {
6696                res = mInstaller.createUserData(volumeUuid, packageName,
6697                        UserHandle.getUid(user, uid), user, seinfo);
6698                if (res != 0) {
6699                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6700                            "Failed to createUserData " + packageName + ": " + res);
6701                }
6702            }
6703        }
6704    }
6705
6706    private int removeDataDirsLI(String volumeUuid, String packageName) {
6707        int[] users = sUserManager.getUserIds();
6708        int res = 0;
6709        for (int user : users) {
6710            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6711            if (resInner < 0) {
6712                res = resInner;
6713            }
6714        }
6715
6716        return res;
6717    }
6718
6719    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6720        int[] users = sUserManager.getUserIds();
6721        int res = 0;
6722        for (int user : users) {
6723            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6724            if (resInner < 0) {
6725                res = resInner;
6726            }
6727        }
6728        return res;
6729    }
6730
6731    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6732            PackageParser.Package changingLib) {
6733        if (file.path != null) {
6734            usesLibraryFiles.add(file.path);
6735            return;
6736        }
6737        PackageParser.Package p = mPackages.get(file.apk);
6738        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6739            // If we are doing this while in the middle of updating a library apk,
6740            // then we need to make sure to use that new apk for determining the
6741            // dependencies here.  (We haven't yet finished committing the new apk
6742            // to the package manager state.)
6743            if (p == null || p.packageName.equals(changingLib.packageName)) {
6744                p = changingLib;
6745            }
6746        }
6747        if (p != null) {
6748            usesLibraryFiles.addAll(p.getAllCodePaths());
6749        }
6750    }
6751
6752    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6753            PackageParser.Package changingLib) throws PackageManagerException {
6754        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6755            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6756            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6757            for (int i=0; i<N; i++) {
6758                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6759                if (file == null) {
6760                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6761                            "Package " + pkg.packageName + " requires unavailable shared library "
6762                            + pkg.usesLibraries.get(i) + "; failing!");
6763                }
6764                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6765            }
6766            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6767            for (int i=0; i<N; i++) {
6768                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6769                if (file == null) {
6770                    Slog.w(TAG, "Package " + pkg.packageName
6771                            + " desires unavailable shared library "
6772                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6773                } else {
6774                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6775                }
6776            }
6777            N = usesLibraryFiles.size();
6778            if (N > 0) {
6779                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6780            } else {
6781                pkg.usesLibraryFiles = null;
6782            }
6783        }
6784    }
6785
6786    private static boolean hasString(List<String> list, List<String> which) {
6787        if (list == null) {
6788            return false;
6789        }
6790        for (int i=list.size()-1; i>=0; i--) {
6791            for (int j=which.size()-1; j>=0; j--) {
6792                if (which.get(j).equals(list.get(i))) {
6793                    return true;
6794                }
6795            }
6796        }
6797        return false;
6798    }
6799
6800    private void updateAllSharedLibrariesLPw() {
6801        for (PackageParser.Package pkg : mPackages.values()) {
6802            try {
6803                updateSharedLibrariesLPw(pkg, null);
6804            } catch (PackageManagerException e) {
6805                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6806            }
6807        }
6808    }
6809
6810    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6811            PackageParser.Package changingPkg) {
6812        ArrayList<PackageParser.Package> res = null;
6813        for (PackageParser.Package pkg : mPackages.values()) {
6814            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6815                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6816                if (res == null) {
6817                    res = new ArrayList<PackageParser.Package>();
6818                }
6819                res.add(pkg);
6820                try {
6821                    updateSharedLibrariesLPw(pkg, changingPkg);
6822                } catch (PackageManagerException e) {
6823                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6824                }
6825            }
6826        }
6827        return res;
6828    }
6829
6830    /**
6831     * Derive the value of the {@code cpuAbiOverride} based on the provided
6832     * value and an optional stored value from the package settings.
6833     */
6834    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6835        String cpuAbiOverride = null;
6836
6837        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6838            cpuAbiOverride = null;
6839        } else if (abiOverride != null) {
6840            cpuAbiOverride = abiOverride;
6841        } else if (settings != null) {
6842            cpuAbiOverride = settings.cpuAbiOverrideString;
6843        }
6844
6845        return cpuAbiOverride;
6846    }
6847
6848    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6849            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6850        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6851        try {
6852            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6853        } finally {
6854            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6855        }
6856    }
6857
6858    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6859            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6860        boolean success = false;
6861        try {
6862            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6863                    currentTime, user);
6864            success = true;
6865            return res;
6866        } finally {
6867            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6868                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6869            }
6870        }
6871    }
6872
6873    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6874            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6875        final File scanFile = new File(pkg.codePath);
6876        if (pkg.applicationInfo.getCodePath() == null ||
6877                pkg.applicationInfo.getResourcePath() == null) {
6878            // Bail out. The resource and code paths haven't been set.
6879            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6880                    "Code and resource paths haven't been set correctly");
6881        }
6882
6883        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6884            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6885        } else {
6886            // Only allow system apps to be flagged as core apps.
6887            pkg.coreApp = false;
6888        }
6889
6890        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6891            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6892        }
6893
6894        if (mCustomResolverComponentName != null &&
6895                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6896            setUpCustomResolverActivity(pkg);
6897        }
6898
6899        if (pkg.packageName.equals("android")) {
6900            synchronized (mPackages) {
6901                if (mAndroidApplication != null) {
6902                    Slog.w(TAG, "*************************************************");
6903                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6904                    Slog.w(TAG, " file=" + scanFile);
6905                    Slog.w(TAG, "*************************************************");
6906                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6907                            "Core android package being redefined.  Skipping.");
6908                }
6909
6910                // Set up information for our fall-back user intent resolution activity.
6911                mPlatformPackage = pkg;
6912                pkg.mVersionCode = mSdkVersion;
6913                mAndroidApplication = pkg.applicationInfo;
6914
6915                if (!mResolverReplaced) {
6916                    mResolveActivity.applicationInfo = mAndroidApplication;
6917                    mResolveActivity.name = ResolverActivity.class.getName();
6918                    mResolveActivity.packageName = mAndroidApplication.packageName;
6919                    mResolveActivity.processName = "system:ui";
6920                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6921                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6922                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6923                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6924                    mResolveActivity.exported = true;
6925                    mResolveActivity.enabled = true;
6926                    mResolveInfo.activityInfo = mResolveActivity;
6927                    mResolveInfo.priority = 0;
6928                    mResolveInfo.preferredOrder = 0;
6929                    mResolveInfo.match = 0;
6930                    mResolveComponentName = new ComponentName(
6931                            mAndroidApplication.packageName, mResolveActivity.name);
6932                }
6933            }
6934        }
6935
6936        if (DEBUG_PACKAGE_SCANNING) {
6937            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6938                Log.d(TAG, "Scanning package " + pkg.packageName);
6939        }
6940
6941        if (mPackages.containsKey(pkg.packageName)
6942                || mSharedLibraries.containsKey(pkg.packageName)) {
6943            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6944                    "Application package " + pkg.packageName
6945                    + " already installed.  Skipping duplicate.");
6946        }
6947
6948        // If we're only installing presumed-existing packages, require that the
6949        // scanned APK is both already known and at the path previously established
6950        // for it.  Previously unknown packages we pick up normally, but if we have an
6951        // a priori expectation about this package's install presence, enforce it.
6952        // With a singular exception for new system packages. When an OTA contains
6953        // a new system package, we allow the codepath to change from a system location
6954        // to the user-installed location. If we don't allow this change, any newer,
6955        // user-installed version of the application will be ignored.
6956        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6957            if (mExpectingBetter.containsKey(pkg.packageName)) {
6958                logCriticalInfo(Log.WARN,
6959                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6960            } else {
6961                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6962                if (known != null) {
6963                    if (DEBUG_PACKAGE_SCANNING) {
6964                        Log.d(TAG, "Examining " + pkg.codePath
6965                                + " and requiring known paths " + known.codePathString
6966                                + " & " + known.resourcePathString);
6967                    }
6968                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6969                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6970                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6971                                "Application package " + pkg.packageName
6972                                + " found at " + pkg.applicationInfo.getCodePath()
6973                                + " but expected at " + known.codePathString + "; ignoring.");
6974                    }
6975                }
6976            }
6977        }
6978
6979        // Initialize package source and resource directories
6980        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6981        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6982
6983        SharedUserSetting suid = null;
6984        PackageSetting pkgSetting = null;
6985
6986        if (!isSystemApp(pkg)) {
6987            // Only system apps can use these features.
6988            pkg.mOriginalPackages = null;
6989            pkg.mRealPackage = null;
6990            pkg.mAdoptPermissions = null;
6991        }
6992
6993        // writer
6994        synchronized (mPackages) {
6995            if (pkg.mSharedUserId != null) {
6996                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6997                if (suid == null) {
6998                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6999                            "Creating application package " + pkg.packageName
7000                            + " for shared user failed");
7001                }
7002                if (DEBUG_PACKAGE_SCANNING) {
7003                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7004                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7005                                + "): packages=" + suid.packages);
7006                }
7007            }
7008
7009            // Check if we are renaming from an original package name.
7010            PackageSetting origPackage = null;
7011            String realName = null;
7012            if (pkg.mOriginalPackages != null) {
7013                // This package may need to be renamed to a previously
7014                // installed name.  Let's check on that...
7015                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7016                if (pkg.mOriginalPackages.contains(renamed)) {
7017                    // This package had originally been installed as the
7018                    // original name, and we have already taken care of
7019                    // transitioning to the new one.  Just update the new
7020                    // one to continue using the old name.
7021                    realName = pkg.mRealPackage;
7022                    if (!pkg.packageName.equals(renamed)) {
7023                        // Callers into this function may have already taken
7024                        // care of renaming the package; only do it here if
7025                        // it is not already done.
7026                        pkg.setPackageName(renamed);
7027                    }
7028
7029                } else {
7030                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7031                        if ((origPackage = mSettings.peekPackageLPr(
7032                                pkg.mOriginalPackages.get(i))) != null) {
7033                            // We do have the package already installed under its
7034                            // original name...  should we use it?
7035                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7036                                // New package is not compatible with original.
7037                                origPackage = null;
7038                                continue;
7039                            } else if (origPackage.sharedUser != null) {
7040                                // Make sure uid is compatible between packages.
7041                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7042                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7043                                            + " to " + pkg.packageName + ": old uid "
7044                                            + origPackage.sharedUser.name
7045                                            + " differs from " + pkg.mSharedUserId);
7046                                    origPackage = null;
7047                                    continue;
7048                                }
7049                            } else {
7050                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7051                                        + pkg.packageName + " to old name " + origPackage.name);
7052                            }
7053                            break;
7054                        }
7055                    }
7056                }
7057            }
7058
7059            if (mTransferedPackages.contains(pkg.packageName)) {
7060                Slog.w(TAG, "Package " + pkg.packageName
7061                        + " was transferred to another, but its .apk remains");
7062            }
7063
7064            // Just create the setting, don't add it yet. For already existing packages
7065            // the PkgSetting exists already and doesn't have to be created.
7066            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7067                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7068                    pkg.applicationInfo.primaryCpuAbi,
7069                    pkg.applicationInfo.secondaryCpuAbi,
7070                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7071                    user, false);
7072            if (pkgSetting == null) {
7073                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7074                        "Creating application package " + pkg.packageName + " failed");
7075            }
7076
7077            if (pkgSetting.origPackage != null) {
7078                // If we are first transitioning from an original package,
7079                // fix up the new package's name now.  We need to do this after
7080                // looking up the package under its new name, so getPackageLP
7081                // can take care of fiddling things correctly.
7082                pkg.setPackageName(origPackage.name);
7083
7084                // File a report about this.
7085                String msg = "New package " + pkgSetting.realName
7086                        + " renamed to replace old package " + pkgSetting.name;
7087                reportSettingsProblem(Log.WARN, msg);
7088
7089                // Make a note of it.
7090                mTransferedPackages.add(origPackage.name);
7091
7092                // No longer need to retain this.
7093                pkgSetting.origPackage = null;
7094            }
7095
7096            if (realName != null) {
7097                // Make a note of it.
7098                mTransferedPackages.add(pkg.packageName);
7099            }
7100
7101            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7102                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7103            }
7104
7105            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7106                // Check all shared libraries and map to their actual file path.
7107                // We only do this here for apps not on a system dir, because those
7108                // are the only ones that can fail an install due to this.  We
7109                // will take care of the system apps by updating all of their
7110                // library paths after the scan is done.
7111                updateSharedLibrariesLPw(pkg, null);
7112            }
7113
7114            if (mFoundPolicyFile) {
7115                SELinuxMMAC.assignSeinfoValue(pkg);
7116            }
7117
7118            pkg.applicationInfo.uid = pkgSetting.appId;
7119            pkg.mExtras = pkgSetting;
7120            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7121                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7122                    // We just determined the app is signed correctly, so bring
7123                    // over the latest parsed certs.
7124                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7125                } else {
7126                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7127                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7128                                "Package " + pkg.packageName + " upgrade keys do not match the "
7129                                + "previously installed version");
7130                    } else {
7131                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7132                        String msg = "System package " + pkg.packageName
7133                            + " signature changed; retaining data.";
7134                        reportSettingsProblem(Log.WARN, msg);
7135                    }
7136                }
7137            } else {
7138                try {
7139                    verifySignaturesLP(pkgSetting, pkg);
7140                    // We just determined the app is signed correctly, so bring
7141                    // over the latest parsed certs.
7142                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7143                } catch (PackageManagerException e) {
7144                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7145                        throw e;
7146                    }
7147                    // The signature has changed, but this package is in the system
7148                    // image...  let's recover!
7149                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7150                    // However...  if this package is part of a shared user, but it
7151                    // doesn't match the signature of the shared user, let's fail.
7152                    // What this means is that you can't change the signatures
7153                    // associated with an overall shared user, which doesn't seem all
7154                    // that unreasonable.
7155                    if (pkgSetting.sharedUser != null) {
7156                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7157                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7158                            throw new PackageManagerException(
7159                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7160                                            "Signature mismatch for shared user : "
7161                                            + pkgSetting.sharedUser);
7162                        }
7163                    }
7164                    // File a report about this.
7165                    String msg = "System package " + pkg.packageName
7166                        + " signature changed; retaining data.";
7167                    reportSettingsProblem(Log.WARN, msg);
7168                }
7169            }
7170            // Verify that this new package doesn't have any content providers
7171            // that conflict with existing packages.  Only do this if the
7172            // package isn't already installed, since we don't want to break
7173            // things that are installed.
7174            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7175                final int N = pkg.providers.size();
7176                int i;
7177                for (i=0; i<N; i++) {
7178                    PackageParser.Provider p = pkg.providers.get(i);
7179                    if (p.info.authority != null) {
7180                        String names[] = p.info.authority.split(";");
7181                        for (int j = 0; j < names.length; j++) {
7182                            if (mProvidersByAuthority.containsKey(names[j])) {
7183                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7184                                final String otherPackageName =
7185                                        ((other != null && other.getComponentName() != null) ?
7186                                                other.getComponentName().getPackageName() : "?");
7187                                throw new PackageManagerException(
7188                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7189                                                "Can't install because provider name " + names[j]
7190                                                + " (in package " + pkg.applicationInfo.packageName
7191                                                + ") is already used by " + otherPackageName);
7192                            }
7193                        }
7194                    }
7195                }
7196            }
7197
7198            if (pkg.mAdoptPermissions != null) {
7199                // This package wants to adopt ownership of permissions from
7200                // another package.
7201                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7202                    final String origName = pkg.mAdoptPermissions.get(i);
7203                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7204                    if (orig != null) {
7205                        if (verifyPackageUpdateLPr(orig, pkg)) {
7206                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7207                                    + pkg.packageName);
7208                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7209                        }
7210                    }
7211                }
7212            }
7213        }
7214
7215        final String pkgName = pkg.packageName;
7216
7217        final long scanFileTime = scanFile.lastModified();
7218        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7219        pkg.applicationInfo.processName = fixProcessName(
7220                pkg.applicationInfo.packageName,
7221                pkg.applicationInfo.processName,
7222                pkg.applicationInfo.uid);
7223
7224        if (pkg != mPlatformPackage) {
7225            // This is a normal package, need to make its data directory.
7226            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7227                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7228
7229            boolean uidError = false;
7230            if (dataPath.exists()) {
7231                int currentUid = 0;
7232                try {
7233                    StructStat stat = Os.stat(dataPath.getPath());
7234                    currentUid = stat.st_uid;
7235                } catch (ErrnoException e) {
7236                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7237                }
7238
7239                // If we have mismatched owners for the data path, we have a problem.
7240                if (currentUid != pkg.applicationInfo.uid) {
7241                    boolean recovered = false;
7242                    if (currentUid == 0) {
7243                        // The directory somehow became owned by root.  Wow.
7244                        // This is probably because the system was stopped while
7245                        // installd was in the middle of messing with its libs
7246                        // directory.  Ask installd to fix that.
7247                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7248                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7249                        if (ret >= 0) {
7250                            recovered = true;
7251                            String msg = "Package " + pkg.packageName
7252                                    + " unexpectedly changed to uid 0; recovered to " +
7253                                    + pkg.applicationInfo.uid;
7254                            reportSettingsProblem(Log.WARN, msg);
7255                        }
7256                    }
7257                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7258                            || (scanFlags&SCAN_BOOTING) != 0)) {
7259                        // If this is a system app, we can at least delete its
7260                        // current data so the application will still work.
7261                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7262                        if (ret >= 0) {
7263                            // TODO: Kill the processes first
7264                            // Old data gone!
7265                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7266                                    ? "System package " : "Third party package ";
7267                            String msg = prefix + pkg.packageName
7268                                    + " has changed from uid: "
7269                                    + currentUid + " to "
7270                                    + pkg.applicationInfo.uid + "; old data erased";
7271                            reportSettingsProblem(Log.WARN, msg);
7272                            recovered = true;
7273                        }
7274                        if (!recovered) {
7275                            mHasSystemUidErrors = true;
7276                        }
7277                    } else if (!recovered) {
7278                        // If we allow this install to proceed, we will be broken.
7279                        // Abort, abort!
7280                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7281                                "scanPackageLI");
7282                    }
7283                    if (!recovered) {
7284                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7285                            + pkg.applicationInfo.uid + "/fs_"
7286                            + currentUid;
7287                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7288                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7289                        String msg = "Package " + pkg.packageName
7290                                + " has mismatched uid: "
7291                                + currentUid + " on disk, "
7292                                + pkg.applicationInfo.uid + " in settings";
7293                        // writer
7294                        synchronized (mPackages) {
7295                            mSettings.mReadMessages.append(msg);
7296                            mSettings.mReadMessages.append('\n');
7297                            uidError = true;
7298                            if (!pkgSetting.uidError) {
7299                                reportSettingsProblem(Log.ERROR, msg);
7300                            }
7301                        }
7302                    }
7303                }
7304
7305                // Ensure that directories are prepared
7306                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7307                        pkg.applicationInfo.seinfo);
7308
7309                if (mShouldRestoreconData) {
7310                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7311                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7312                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7313                }
7314            } else {
7315                if (DEBUG_PACKAGE_SCANNING) {
7316                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7317                        Log.v(TAG, "Want this data dir: " + dataPath);
7318                }
7319                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7320                        pkg.applicationInfo.seinfo);
7321            }
7322
7323            // Get all of our default paths setup
7324            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7325
7326            pkgSetting.uidError = uidError;
7327        }
7328
7329        final String path = scanFile.getPath();
7330        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7331
7332        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7333            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7334
7335            // Some system apps still use directory structure for native libraries
7336            // in which case we might end up not detecting abi solely based on apk
7337            // structure. Try to detect abi based on directory structure.
7338            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7339                    pkg.applicationInfo.primaryCpuAbi == null) {
7340                setBundledAppAbisAndRoots(pkg, pkgSetting);
7341                setNativeLibraryPaths(pkg);
7342            }
7343
7344        } else {
7345            if ((scanFlags & SCAN_MOVE) != 0) {
7346                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7347                // but we already have this packages package info in the PackageSetting. We just
7348                // use that and derive the native library path based on the new codepath.
7349                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7350                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7351            }
7352
7353            // Set native library paths again. For moves, the path will be updated based on the
7354            // ABIs we've determined above. For non-moves, the path will be updated based on the
7355            // ABIs we determined during compilation, but the path will depend on the final
7356            // package path (after the rename away from the stage path).
7357            setNativeLibraryPaths(pkg);
7358        }
7359
7360        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7361        final int[] userIds = sUserManager.getUserIds();
7362        synchronized (mInstallLock) {
7363            // Make sure all user data directories are ready to roll; we're okay
7364            // if they already exist
7365            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7366                for (int userId : userIds) {
7367                    if (userId != UserHandle.USER_SYSTEM) {
7368                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7369                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7370                                pkg.applicationInfo.seinfo);
7371                    }
7372                }
7373            }
7374
7375            // Create a native library symlink only if we have native libraries
7376            // and if the native libraries are 32 bit libraries. We do not provide
7377            // this symlink for 64 bit libraries.
7378            if (pkg.applicationInfo.primaryCpuAbi != null &&
7379                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7380                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7381                try {
7382                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7383                    for (int userId : userIds) {
7384                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7385                                nativeLibPath, userId) < 0) {
7386                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7387                                    "Failed linking native library dir (user=" + userId + ")");
7388                        }
7389                    }
7390                } finally {
7391                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7392                }
7393            }
7394        }
7395
7396        // This is a special case for the "system" package, where the ABI is
7397        // dictated by the zygote configuration (and init.rc). We should keep track
7398        // of this ABI so that we can deal with "normal" applications that run under
7399        // the same UID correctly.
7400        if (mPlatformPackage == pkg) {
7401            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7402                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7403        }
7404
7405        // If there's a mismatch between the abi-override in the package setting
7406        // and the abiOverride specified for the install. Warn about this because we
7407        // would've already compiled the app without taking the package setting into
7408        // account.
7409        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7410            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7411                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7412                        " for package: " + pkg.packageName);
7413            }
7414        }
7415
7416        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7417        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7418        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7419
7420        // Copy the derived override back to the parsed package, so that we can
7421        // update the package settings accordingly.
7422        pkg.cpuAbiOverride = cpuAbiOverride;
7423
7424        if (DEBUG_ABI_SELECTION) {
7425            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7426                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7427                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7428        }
7429
7430        // Push the derived path down into PackageSettings so we know what to
7431        // clean up at uninstall time.
7432        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7433
7434        if (DEBUG_ABI_SELECTION) {
7435            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7436                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7437                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7438        }
7439
7440        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7441            // We don't do this here during boot because we can do it all
7442            // at once after scanning all existing packages.
7443            //
7444            // We also do this *before* we perform dexopt on this package, so that
7445            // we can avoid redundant dexopts, and also to make sure we've got the
7446            // code and package path correct.
7447            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7448                    pkg, true /* boot complete */);
7449        }
7450
7451        if (mFactoryTest && pkg.requestedPermissions.contains(
7452                android.Manifest.permission.FACTORY_TEST)) {
7453            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7454        }
7455
7456        ArrayList<PackageParser.Package> clientLibPkgs = null;
7457
7458        // writer
7459        synchronized (mPackages) {
7460            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7461                // Only system apps can add new shared libraries.
7462                if (pkg.libraryNames != null) {
7463                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7464                        String name = pkg.libraryNames.get(i);
7465                        boolean allowed = false;
7466                        if (pkg.isUpdatedSystemApp()) {
7467                            // New library entries can only be added through the
7468                            // system image.  This is important to get rid of a lot
7469                            // of nasty edge cases: for example if we allowed a non-
7470                            // system update of the app to add a library, then uninstalling
7471                            // the update would make the library go away, and assumptions
7472                            // we made such as through app install filtering would now
7473                            // have allowed apps on the device which aren't compatible
7474                            // with it.  Better to just have the restriction here, be
7475                            // conservative, and create many fewer cases that can negatively
7476                            // impact the user experience.
7477                            final PackageSetting sysPs = mSettings
7478                                    .getDisabledSystemPkgLPr(pkg.packageName);
7479                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7480                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7481                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7482                                        allowed = true;
7483                                        break;
7484                                    }
7485                                }
7486                            }
7487                        } else {
7488                            allowed = true;
7489                        }
7490                        if (allowed) {
7491                            if (!mSharedLibraries.containsKey(name)) {
7492                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7493                            } else if (!name.equals(pkg.packageName)) {
7494                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7495                                        + name + " already exists; skipping");
7496                            }
7497                        } else {
7498                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7499                                    + name + " that is not declared on system image; skipping");
7500                        }
7501                    }
7502                    if ((scanFlags & SCAN_BOOTING) == 0) {
7503                        // If we are not booting, we need to update any applications
7504                        // that are clients of our shared library.  If we are booting,
7505                        // this will all be done once the scan is complete.
7506                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7507                    }
7508                }
7509            }
7510        }
7511
7512        // Request the ActivityManager to kill the process(only for existing packages)
7513        // so that we do not end up in a confused state while the user is still using the older
7514        // version of the application while the new one gets installed.
7515        if ((scanFlags & SCAN_REPLACING) != 0) {
7516            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7517
7518            killApplication(pkg.applicationInfo.packageName,
7519                        pkg.applicationInfo.uid, "replace pkg");
7520
7521            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7522        }
7523
7524        // Also need to kill any apps that are dependent on the library.
7525        if (clientLibPkgs != null) {
7526            for (int i=0; i<clientLibPkgs.size(); i++) {
7527                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7528                killApplication(clientPkg.applicationInfo.packageName,
7529                        clientPkg.applicationInfo.uid, "update lib");
7530            }
7531        }
7532
7533        // Make sure we're not adding any bogus keyset info
7534        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7535        ksms.assertScannedPackageValid(pkg);
7536
7537        // writer
7538        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7539
7540        boolean createIdmapFailed = false;
7541        synchronized (mPackages) {
7542            // We don't expect installation to fail beyond this point
7543
7544            // Add the new setting to mSettings
7545            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7546            // Add the new setting to mPackages
7547            mPackages.put(pkg.applicationInfo.packageName, pkg);
7548            // Make sure we don't accidentally delete its data.
7549            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7550            while (iter.hasNext()) {
7551                PackageCleanItem item = iter.next();
7552                if (pkgName.equals(item.packageName)) {
7553                    iter.remove();
7554                }
7555            }
7556
7557            // Take care of first install / last update times.
7558            if (currentTime != 0) {
7559                if (pkgSetting.firstInstallTime == 0) {
7560                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7561                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7562                    pkgSetting.lastUpdateTime = currentTime;
7563                }
7564            } else if (pkgSetting.firstInstallTime == 0) {
7565                // We need *something*.  Take time time stamp of the file.
7566                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7567            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7568                if (scanFileTime != pkgSetting.timeStamp) {
7569                    // A package on the system image has changed; consider this
7570                    // to be an update.
7571                    pkgSetting.lastUpdateTime = scanFileTime;
7572                }
7573            }
7574
7575            // Add the package's KeySets to the global KeySetManagerService
7576            ksms.addScannedPackageLPw(pkg);
7577
7578            int N = pkg.providers.size();
7579            StringBuilder r = null;
7580            int i;
7581            for (i=0; i<N; i++) {
7582                PackageParser.Provider p = pkg.providers.get(i);
7583                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7584                        p.info.processName, pkg.applicationInfo.uid);
7585                mProviders.addProvider(p);
7586                p.syncable = p.info.isSyncable;
7587                if (p.info.authority != null) {
7588                    String names[] = p.info.authority.split(";");
7589                    p.info.authority = null;
7590                    for (int j = 0; j < names.length; j++) {
7591                        if (j == 1 && p.syncable) {
7592                            // We only want the first authority for a provider to possibly be
7593                            // syncable, so if we already added this provider using a different
7594                            // authority clear the syncable flag. We copy the provider before
7595                            // changing it because the mProviders object contains a reference
7596                            // to a provider that we don't want to change.
7597                            // Only do this for the second authority since the resulting provider
7598                            // object can be the same for all future authorities for this provider.
7599                            p = new PackageParser.Provider(p);
7600                            p.syncable = false;
7601                        }
7602                        if (!mProvidersByAuthority.containsKey(names[j])) {
7603                            mProvidersByAuthority.put(names[j], p);
7604                            if (p.info.authority == null) {
7605                                p.info.authority = names[j];
7606                            } else {
7607                                p.info.authority = p.info.authority + ";" + names[j];
7608                            }
7609                            if (DEBUG_PACKAGE_SCANNING) {
7610                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7611                                    Log.d(TAG, "Registered content provider: " + names[j]
7612                                            + ", className = " + p.info.name + ", isSyncable = "
7613                                            + p.info.isSyncable);
7614                            }
7615                        } else {
7616                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7617                            Slog.w(TAG, "Skipping provider name " + names[j] +
7618                                    " (in package " + pkg.applicationInfo.packageName +
7619                                    "): name already used by "
7620                                    + ((other != null && other.getComponentName() != null)
7621                                            ? other.getComponentName().getPackageName() : "?"));
7622                        }
7623                    }
7624                }
7625                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7626                    if (r == null) {
7627                        r = new StringBuilder(256);
7628                    } else {
7629                        r.append(' ');
7630                    }
7631                    r.append(p.info.name);
7632                }
7633            }
7634            if (r != null) {
7635                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7636            }
7637
7638            N = pkg.services.size();
7639            r = null;
7640            for (i=0; i<N; i++) {
7641                PackageParser.Service s = pkg.services.get(i);
7642                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7643                        s.info.processName, pkg.applicationInfo.uid);
7644                mServices.addService(s);
7645                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7646                    if (r == null) {
7647                        r = new StringBuilder(256);
7648                    } else {
7649                        r.append(' ');
7650                    }
7651                    r.append(s.info.name);
7652                }
7653            }
7654            if (r != null) {
7655                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7656            }
7657
7658            N = pkg.receivers.size();
7659            r = null;
7660            for (i=0; i<N; i++) {
7661                PackageParser.Activity a = pkg.receivers.get(i);
7662                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7663                        a.info.processName, pkg.applicationInfo.uid);
7664                mReceivers.addActivity(a, "receiver");
7665                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7666                    if (r == null) {
7667                        r = new StringBuilder(256);
7668                    } else {
7669                        r.append(' ');
7670                    }
7671                    r.append(a.info.name);
7672                }
7673            }
7674            if (r != null) {
7675                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7676            }
7677
7678            N = pkg.activities.size();
7679            r = null;
7680            for (i=0; i<N; i++) {
7681                PackageParser.Activity a = pkg.activities.get(i);
7682                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7683                        a.info.processName, pkg.applicationInfo.uid);
7684                mActivities.addActivity(a, "activity");
7685                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7686                    if (r == null) {
7687                        r = new StringBuilder(256);
7688                    } else {
7689                        r.append(' ');
7690                    }
7691                    r.append(a.info.name);
7692                }
7693            }
7694            if (r != null) {
7695                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7696            }
7697
7698            N = pkg.permissionGroups.size();
7699            r = null;
7700            for (i=0; i<N; i++) {
7701                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7702                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7703                if (cur == null) {
7704                    mPermissionGroups.put(pg.info.name, pg);
7705                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7706                        if (r == null) {
7707                            r = new StringBuilder(256);
7708                        } else {
7709                            r.append(' ');
7710                        }
7711                        r.append(pg.info.name);
7712                    }
7713                } else {
7714                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7715                            + pg.info.packageName + " ignored: original from "
7716                            + cur.info.packageName);
7717                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7718                        if (r == null) {
7719                            r = new StringBuilder(256);
7720                        } else {
7721                            r.append(' ');
7722                        }
7723                        r.append("DUP:");
7724                        r.append(pg.info.name);
7725                    }
7726                }
7727            }
7728            if (r != null) {
7729                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7730            }
7731
7732            N = pkg.permissions.size();
7733            r = null;
7734            for (i=0; i<N; i++) {
7735                PackageParser.Permission p = pkg.permissions.get(i);
7736
7737                // Assume by default that we did not install this permission into the system.
7738                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7739
7740                // Now that permission groups have a special meaning, we ignore permission
7741                // groups for legacy apps to prevent unexpected behavior. In particular,
7742                // permissions for one app being granted to someone just becuase they happen
7743                // to be in a group defined by another app (before this had no implications).
7744                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7745                    p.group = mPermissionGroups.get(p.info.group);
7746                    // Warn for a permission in an unknown group.
7747                    if (p.info.group != null && p.group == null) {
7748                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7749                                + p.info.packageName + " in an unknown group " + p.info.group);
7750                    }
7751                }
7752
7753                ArrayMap<String, BasePermission> permissionMap =
7754                        p.tree ? mSettings.mPermissionTrees
7755                                : mSettings.mPermissions;
7756                BasePermission bp = permissionMap.get(p.info.name);
7757
7758                // Allow system apps to redefine non-system permissions
7759                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7760                    final boolean currentOwnerIsSystem = (bp.perm != null
7761                            && isSystemApp(bp.perm.owner));
7762                    if (isSystemApp(p.owner)) {
7763                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7764                            // It's a built-in permission and no owner, take ownership now
7765                            bp.packageSetting = pkgSetting;
7766                            bp.perm = p;
7767                            bp.uid = pkg.applicationInfo.uid;
7768                            bp.sourcePackage = p.info.packageName;
7769                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7770                        } else if (!currentOwnerIsSystem) {
7771                            String msg = "New decl " + p.owner + " of permission  "
7772                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7773                            reportSettingsProblem(Log.WARN, msg);
7774                            bp = null;
7775                        }
7776                    }
7777                }
7778
7779                if (bp == null) {
7780                    bp = new BasePermission(p.info.name, p.info.packageName,
7781                            BasePermission.TYPE_NORMAL);
7782                    permissionMap.put(p.info.name, bp);
7783                }
7784
7785                if (bp.perm == null) {
7786                    if (bp.sourcePackage == null
7787                            || bp.sourcePackage.equals(p.info.packageName)) {
7788                        BasePermission tree = findPermissionTreeLP(p.info.name);
7789                        if (tree == null
7790                                || tree.sourcePackage.equals(p.info.packageName)) {
7791                            bp.packageSetting = pkgSetting;
7792                            bp.perm = p;
7793                            bp.uid = pkg.applicationInfo.uid;
7794                            bp.sourcePackage = p.info.packageName;
7795                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7796                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7797                                if (r == null) {
7798                                    r = new StringBuilder(256);
7799                                } else {
7800                                    r.append(' ');
7801                                }
7802                                r.append(p.info.name);
7803                            }
7804                        } else {
7805                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7806                                    + p.info.packageName + " ignored: base tree "
7807                                    + tree.name + " is from package "
7808                                    + tree.sourcePackage);
7809                        }
7810                    } else {
7811                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7812                                + p.info.packageName + " ignored: original from "
7813                                + bp.sourcePackage);
7814                    }
7815                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7816                    if (r == null) {
7817                        r = new StringBuilder(256);
7818                    } else {
7819                        r.append(' ');
7820                    }
7821                    r.append("DUP:");
7822                    r.append(p.info.name);
7823                }
7824                if (bp.perm == p) {
7825                    bp.protectionLevel = p.info.protectionLevel;
7826                }
7827            }
7828
7829            if (r != null) {
7830                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7831            }
7832
7833            N = pkg.instrumentation.size();
7834            r = null;
7835            for (i=0; i<N; i++) {
7836                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7837                a.info.packageName = pkg.applicationInfo.packageName;
7838                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7839                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7840                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7841                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7842                a.info.dataDir = pkg.applicationInfo.dataDir;
7843                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7844                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7845
7846                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7847                // need other information about the application, like the ABI and what not ?
7848                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7849                mInstrumentation.put(a.getComponentName(), a);
7850                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7851                    if (r == null) {
7852                        r = new StringBuilder(256);
7853                    } else {
7854                        r.append(' ');
7855                    }
7856                    r.append(a.info.name);
7857                }
7858            }
7859            if (r != null) {
7860                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7861            }
7862
7863            if (pkg.protectedBroadcasts != null) {
7864                N = pkg.protectedBroadcasts.size();
7865                for (i=0; i<N; i++) {
7866                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7867                }
7868            }
7869
7870            pkgSetting.setTimeStamp(scanFileTime);
7871
7872            // Create idmap files for pairs of (packages, overlay packages).
7873            // Note: "android", ie framework-res.apk, is handled by native layers.
7874            if (pkg.mOverlayTarget != null) {
7875                // This is an overlay package.
7876                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7877                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7878                        mOverlays.put(pkg.mOverlayTarget,
7879                                new ArrayMap<String, PackageParser.Package>());
7880                    }
7881                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7882                    map.put(pkg.packageName, pkg);
7883                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7884                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7885                        createIdmapFailed = true;
7886                    }
7887                }
7888            } else if (mOverlays.containsKey(pkg.packageName) &&
7889                    !pkg.packageName.equals("android")) {
7890                // This is a regular package, with one or more known overlay packages.
7891                createIdmapsForPackageLI(pkg);
7892            }
7893        }
7894
7895        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7896
7897        if (createIdmapFailed) {
7898            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7899                    "scanPackageLI failed to createIdmap");
7900        }
7901        return pkg;
7902    }
7903
7904    /**
7905     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7906     * is derived purely on the basis of the contents of {@code scanFile} and
7907     * {@code cpuAbiOverride}.
7908     *
7909     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7910     */
7911    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7912                                 String cpuAbiOverride, boolean extractLibs)
7913            throws PackageManagerException {
7914        // TODO: We can probably be smarter about this stuff. For installed apps,
7915        // we can calculate this information at install time once and for all. For
7916        // system apps, we can probably assume that this information doesn't change
7917        // after the first boot scan. As things stand, we do lots of unnecessary work.
7918
7919        // Give ourselves some initial paths; we'll come back for another
7920        // pass once we've determined ABI below.
7921        setNativeLibraryPaths(pkg);
7922
7923        // We would never need to extract libs for forward-locked and external packages,
7924        // since the container service will do it for us. We shouldn't attempt to
7925        // extract libs from system app when it was not updated.
7926        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7927                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7928            extractLibs = false;
7929        }
7930
7931        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7932        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7933
7934        NativeLibraryHelper.Handle handle = null;
7935        try {
7936            handle = NativeLibraryHelper.Handle.create(pkg);
7937            // TODO(multiArch): This can be null for apps that didn't go through the
7938            // usual installation process. We can calculate it again, like we
7939            // do during install time.
7940            //
7941            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7942            // unnecessary.
7943            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7944
7945            // Null out the abis so that they can be recalculated.
7946            pkg.applicationInfo.primaryCpuAbi = null;
7947            pkg.applicationInfo.secondaryCpuAbi = null;
7948            if (isMultiArch(pkg.applicationInfo)) {
7949                // Warn if we've set an abiOverride for multi-lib packages..
7950                // By definition, we need to copy both 32 and 64 bit libraries for
7951                // such packages.
7952                if (pkg.cpuAbiOverride != null
7953                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7954                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7955                }
7956
7957                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7958                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7959                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7960                    if (extractLibs) {
7961                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7962                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7963                                useIsaSpecificSubdirs);
7964                    } else {
7965                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7966                    }
7967                }
7968
7969                maybeThrowExceptionForMultiArchCopy(
7970                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7971
7972                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7973                    if (extractLibs) {
7974                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7975                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7976                                useIsaSpecificSubdirs);
7977                    } else {
7978                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7979                    }
7980                }
7981
7982                maybeThrowExceptionForMultiArchCopy(
7983                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7984
7985                if (abi64 >= 0) {
7986                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7987                }
7988
7989                if (abi32 >= 0) {
7990                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7991                    if (abi64 >= 0) {
7992                        pkg.applicationInfo.secondaryCpuAbi = abi;
7993                    } else {
7994                        pkg.applicationInfo.primaryCpuAbi = abi;
7995                    }
7996                }
7997            } else {
7998                String[] abiList = (cpuAbiOverride != null) ?
7999                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8000
8001                // Enable gross and lame hacks for apps that are built with old
8002                // SDK tools. We must scan their APKs for renderscript bitcode and
8003                // not launch them if it's present. Don't bother checking on devices
8004                // that don't have 64 bit support.
8005                boolean needsRenderScriptOverride = false;
8006                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8007                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8008                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8009                    needsRenderScriptOverride = true;
8010                }
8011
8012                final int copyRet;
8013                if (extractLibs) {
8014                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8015                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8016                } else {
8017                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8018                }
8019
8020                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8021                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8022                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8023                }
8024
8025                if (copyRet >= 0) {
8026                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8027                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8028                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8029                } else if (needsRenderScriptOverride) {
8030                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8031                }
8032            }
8033        } catch (IOException ioe) {
8034            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8035        } finally {
8036            IoUtils.closeQuietly(handle);
8037        }
8038
8039        // Now that we've calculated the ABIs and determined if it's an internal app,
8040        // we will go ahead and populate the nativeLibraryPath.
8041        setNativeLibraryPaths(pkg);
8042    }
8043
8044    /**
8045     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8046     * i.e, so that all packages can be run inside a single process if required.
8047     *
8048     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8049     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8050     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8051     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8052     * updating a package that belongs to a shared user.
8053     *
8054     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8055     * adds unnecessary complexity.
8056     */
8057    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8058            PackageParser.Package scannedPackage, boolean bootComplete) {
8059        String requiredInstructionSet = null;
8060        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8061            requiredInstructionSet = VMRuntime.getInstructionSet(
8062                     scannedPackage.applicationInfo.primaryCpuAbi);
8063        }
8064
8065        PackageSetting requirer = null;
8066        for (PackageSetting ps : packagesForUser) {
8067            // If packagesForUser contains scannedPackage, we skip it. This will happen
8068            // when scannedPackage is an update of an existing package. Without this check,
8069            // we will never be able to change the ABI of any package belonging to a shared
8070            // user, even if it's compatible with other packages.
8071            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8072                if (ps.primaryCpuAbiString == null) {
8073                    continue;
8074                }
8075
8076                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8077                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8078                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8079                    // this but there's not much we can do.
8080                    String errorMessage = "Instruction set mismatch, "
8081                            + ((requirer == null) ? "[caller]" : requirer)
8082                            + " requires " + requiredInstructionSet + " whereas " + ps
8083                            + " requires " + instructionSet;
8084                    Slog.w(TAG, errorMessage);
8085                }
8086
8087                if (requiredInstructionSet == null) {
8088                    requiredInstructionSet = instructionSet;
8089                    requirer = ps;
8090                }
8091            }
8092        }
8093
8094        if (requiredInstructionSet != null) {
8095            String adjustedAbi;
8096            if (requirer != null) {
8097                // requirer != null implies that either scannedPackage was null or that scannedPackage
8098                // did not require an ABI, in which case we have to adjust scannedPackage to match
8099                // the ABI of the set (which is the same as requirer's ABI)
8100                adjustedAbi = requirer.primaryCpuAbiString;
8101                if (scannedPackage != null) {
8102                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8103                }
8104            } else {
8105                // requirer == null implies that we're updating all ABIs in the set to
8106                // match scannedPackage.
8107                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8108            }
8109
8110            for (PackageSetting ps : packagesForUser) {
8111                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8112                    if (ps.primaryCpuAbiString != null) {
8113                        continue;
8114                    }
8115
8116                    ps.primaryCpuAbiString = adjustedAbi;
8117                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8118                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8119                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8120                        mInstaller.rmdex(ps.codePathString,
8121                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8122                    }
8123                }
8124            }
8125        }
8126    }
8127
8128    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8129        synchronized (mPackages) {
8130            mResolverReplaced = true;
8131            // Set up information for custom user intent resolution activity.
8132            mResolveActivity.applicationInfo = pkg.applicationInfo;
8133            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8134            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8135            mResolveActivity.processName = pkg.applicationInfo.packageName;
8136            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8137            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8138                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8139            mResolveActivity.theme = 0;
8140            mResolveActivity.exported = true;
8141            mResolveActivity.enabled = true;
8142            mResolveInfo.activityInfo = mResolveActivity;
8143            mResolveInfo.priority = 0;
8144            mResolveInfo.preferredOrder = 0;
8145            mResolveInfo.match = 0;
8146            mResolveComponentName = mCustomResolverComponentName;
8147            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8148                    mResolveComponentName);
8149        }
8150    }
8151
8152    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8153        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8154
8155        // Set up information for ephemeral installer activity
8156        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8157        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8158        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8159        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8160        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8161        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8162                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8163        mEphemeralInstallerActivity.theme = 0;
8164        mEphemeralInstallerActivity.exported = true;
8165        mEphemeralInstallerActivity.enabled = true;
8166        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8167        mEphemeralInstallerInfo.priority = 0;
8168        mEphemeralInstallerInfo.preferredOrder = 0;
8169        mEphemeralInstallerInfo.match = 0;
8170
8171        if (DEBUG_EPHEMERAL) {
8172            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8173        }
8174    }
8175
8176    private static String calculateBundledApkRoot(final String codePathString) {
8177        final File codePath = new File(codePathString);
8178        final File codeRoot;
8179        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8180            codeRoot = Environment.getRootDirectory();
8181        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8182            codeRoot = Environment.getOemDirectory();
8183        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8184            codeRoot = Environment.getVendorDirectory();
8185        } else {
8186            // Unrecognized code path; take its top real segment as the apk root:
8187            // e.g. /something/app/blah.apk => /something
8188            try {
8189                File f = codePath.getCanonicalFile();
8190                File parent = f.getParentFile();    // non-null because codePath is a file
8191                File tmp;
8192                while ((tmp = parent.getParentFile()) != null) {
8193                    f = parent;
8194                    parent = tmp;
8195                }
8196                codeRoot = f;
8197                Slog.w(TAG, "Unrecognized code path "
8198                        + codePath + " - using " + codeRoot);
8199            } catch (IOException e) {
8200                // Can't canonicalize the code path -- shenanigans?
8201                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8202                return Environment.getRootDirectory().getPath();
8203            }
8204        }
8205        return codeRoot.getPath();
8206    }
8207
8208    /**
8209     * Derive and set the location of native libraries for the given package,
8210     * which varies depending on where and how the package was installed.
8211     */
8212    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8213        final ApplicationInfo info = pkg.applicationInfo;
8214        final String codePath = pkg.codePath;
8215        final File codeFile = new File(codePath);
8216        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8217        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8218
8219        info.nativeLibraryRootDir = null;
8220        info.nativeLibraryRootRequiresIsa = false;
8221        info.nativeLibraryDir = null;
8222        info.secondaryNativeLibraryDir = null;
8223
8224        if (isApkFile(codeFile)) {
8225            // Monolithic install
8226            if (bundledApp) {
8227                // If "/system/lib64/apkname" exists, assume that is the per-package
8228                // native library directory to use; otherwise use "/system/lib/apkname".
8229                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8230                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8231                        getPrimaryInstructionSet(info));
8232
8233                // This is a bundled system app so choose the path based on the ABI.
8234                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8235                // is just the default path.
8236                final String apkName = deriveCodePathName(codePath);
8237                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8238                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8239                        apkName).getAbsolutePath();
8240
8241                if (info.secondaryCpuAbi != null) {
8242                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8243                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8244                            secondaryLibDir, apkName).getAbsolutePath();
8245                }
8246            } else if (asecApp) {
8247                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8248                        .getAbsolutePath();
8249            } else {
8250                final String apkName = deriveCodePathName(codePath);
8251                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8252                        .getAbsolutePath();
8253            }
8254
8255            info.nativeLibraryRootRequiresIsa = false;
8256            info.nativeLibraryDir = info.nativeLibraryRootDir;
8257        } else {
8258            // Cluster install
8259            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8260            info.nativeLibraryRootRequiresIsa = true;
8261
8262            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8263                    getPrimaryInstructionSet(info)).getAbsolutePath();
8264
8265            if (info.secondaryCpuAbi != null) {
8266                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8267                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8268            }
8269        }
8270    }
8271
8272    /**
8273     * Calculate the abis and roots for a bundled app. These can uniquely
8274     * be determined from the contents of the system partition, i.e whether
8275     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8276     * of this information, and instead assume that the system was built
8277     * sensibly.
8278     */
8279    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8280                                           PackageSetting pkgSetting) {
8281        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8282
8283        // If "/system/lib64/apkname" exists, assume that is the per-package
8284        // native library directory to use; otherwise use "/system/lib/apkname".
8285        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8286        setBundledAppAbi(pkg, apkRoot, apkName);
8287        // pkgSetting might be null during rescan following uninstall of updates
8288        // to a bundled app, so accommodate that possibility.  The settings in
8289        // that case will be established later from the parsed package.
8290        //
8291        // If the settings aren't null, sync them up with what we've just derived.
8292        // note that apkRoot isn't stored in the package settings.
8293        if (pkgSetting != null) {
8294            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8295            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8296        }
8297    }
8298
8299    /**
8300     * Deduces the ABI of a bundled app and sets the relevant fields on the
8301     * parsed pkg object.
8302     *
8303     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8304     *        under which system libraries are installed.
8305     * @param apkName the name of the installed package.
8306     */
8307    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8308        final File codeFile = new File(pkg.codePath);
8309
8310        final boolean has64BitLibs;
8311        final boolean has32BitLibs;
8312        if (isApkFile(codeFile)) {
8313            // Monolithic install
8314            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8315            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8316        } else {
8317            // Cluster install
8318            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8319            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8320                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8321                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8322                has64BitLibs = (new File(rootDir, isa)).exists();
8323            } else {
8324                has64BitLibs = false;
8325            }
8326            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8327                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8328                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8329                has32BitLibs = (new File(rootDir, isa)).exists();
8330            } else {
8331                has32BitLibs = false;
8332            }
8333        }
8334
8335        if (has64BitLibs && !has32BitLibs) {
8336            // The package has 64 bit libs, but not 32 bit libs. Its primary
8337            // ABI should be 64 bit. We can safely assume here that the bundled
8338            // native libraries correspond to the most preferred ABI in the list.
8339
8340            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8341            pkg.applicationInfo.secondaryCpuAbi = null;
8342        } else if (has32BitLibs && !has64BitLibs) {
8343            // The package has 32 bit libs but not 64 bit libs. Its primary
8344            // ABI should be 32 bit.
8345
8346            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8347            pkg.applicationInfo.secondaryCpuAbi = null;
8348        } else if (has32BitLibs && has64BitLibs) {
8349            // The application has both 64 and 32 bit bundled libraries. We check
8350            // here that the app declares multiArch support, and warn if it doesn't.
8351            //
8352            // We will be lenient here and record both ABIs. The primary will be the
8353            // ABI that's higher on the list, i.e, a device that's configured to prefer
8354            // 64 bit apps will see a 64 bit primary ABI,
8355
8356            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8357                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8358            }
8359
8360            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8361                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8362                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8363            } else {
8364                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8365                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8366            }
8367        } else {
8368            pkg.applicationInfo.primaryCpuAbi = null;
8369            pkg.applicationInfo.secondaryCpuAbi = null;
8370        }
8371    }
8372
8373    private void killApplication(String pkgName, int appId, String reason) {
8374        // Request the ActivityManager to kill the process(only for existing packages)
8375        // so that we do not end up in a confused state while the user is still using the older
8376        // version of the application while the new one gets installed.
8377        IActivityManager am = ActivityManagerNative.getDefault();
8378        if (am != null) {
8379            try {
8380                am.killApplicationWithAppId(pkgName, appId, reason);
8381            } catch (RemoteException e) {
8382            }
8383        }
8384    }
8385
8386    void removePackageLI(PackageSetting ps, boolean chatty) {
8387        if (DEBUG_INSTALL) {
8388            if (chatty)
8389                Log.d(TAG, "Removing package " + ps.name);
8390        }
8391
8392        // writer
8393        synchronized (mPackages) {
8394            mPackages.remove(ps.name);
8395            final PackageParser.Package pkg = ps.pkg;
8396            if (pkg != null) {
8397                cleanPackageDataStructuresLILPw(pkg, chatty);
8398            }
8399        }
8400    }
8401
8402    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8403        if (DEBUG_INSTALL) {
8404            if (chatty)
8405                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8406        }
8407
8408        // writer
8409        synchronized (mPackages) {
8410            mPackages.remove(pkg.applicationInfo.packageName);
8411            cleanPackageDataStructuresLILPw(pkg, chatty);
8412        }
8413    }
8414
8415    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8416        int N = pkg.providers.size();
8417        StringBuilder r = null;
8418        int i;
8419        for (i=0; i<N; i++) {
8420            PackageParser.Provider p = pkg.providers.get(i);
8421            mProviders.removeProvider(p);
8422            if (p.info.authority == null) {
8423
8424                /* There was another ContentProvider with this authority when
8425                 * this app was installed so this authority is null,
8426                 * Ignore it as we don't have to unregister the provider.
8427                 */
8428                continue;
8429            }
8430            String names[] = p.info.authority.split(";");
8431            for (int j = 0; j < names.length; j++) {
8432                if (mProvidersByAuthority.get(names[j]) == p) {
8433                    mProvidersByAuthority.remove(names[j]);
8434                    if (DEBUG_REMOVE) {
8435                        if (chatty)
8436                            Log.d(TAG, "Unregistered content provider: " + names[j]
8437                                    + ", className = " + p.info.name + ", isSyncable = "
8438                                    + p.info.isSyncable);
8439                    }
8440                }
8441            }
8442            if (DEBUG_REMOVE && chatty) {
8443                if (r == null) {
8444                    r = new StringBuilder(256);
8445                } else {
8446                    r.append(' ');
8447                }
8448                r.append(p.info.name);
8449            }
8450        }
8451        if (r != null) {
8452            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8453        }
8454
8455        N = pkg.services.size();
8456        r = null;
8457        for (i=0; i<N; i++) {
8458            PackageParser.Service s = pkg.services.get(i);
8459            mServices.removeService(s);
8460            if (chatty) {
8461                if (r == null) {
8462                    r = new StringBuilder(256);
8463                } else {
8464                    r.append(' ');
8465                }
8466                r.append(s.info.name);
8467            }
8468        }
8469        if (r != null) {
8470            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8471        }
8472
8473        N = pkg.receivers.size();
8474        r = null;
8475        for (i=0; i<N; i++) {
8476            PackageParser.Activity a = pkg.receivers.get(i);
8477            mReceivers.removeActivity(a, "receiver");
8478            if (DEBUG_REMOVE && chatty) {
8479                if (r == null) {
8480                    r = new StringBuilder(256);
8481                } else {
8482                    r.append(' ');
8483                }
8484                r.append(a.info.name);
8485            }
8486        }
8487        if (r != null) {
8488            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8489        }
8490
8491        N = pkg.activities.size();
8492        r = null;
8493        for (i=0; i<N; i++) {
8494            PackageParser.Activity a = pkg.activities.get(i);
8495            mActivities.removeActivity(a, "activity");
8496            if (DEBUG_REMOVE && chatty) {
8497                if (r == null) {
8498                    r = new StringBuilder(256);
8499                } else {
8500                    r.append(' ');
8501                }
8502                r.append(a.info.name);
8503            }
8504        }
8505        if (r != null) {
8506            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8507        }
8508
8509        N = pkg.permissions.size();
8510        r = null;
8511        for (i=0; i<N; i++) {
8512            PackageParser.Permission p = pkg.permissions.get(i);
8513            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8514            if (bp == null) {
8515                bp = mSettings.mPermissionTrees.get(p.info.name);
8516            }
8517            if (bp != null && bp.perm == p) {
8518                bp.perm = null;
8519                if (DEBUG_REMOVE && chatty) {
8520                    if (r == null) {
8521                        r = new StringBuilder(256);
8522                    } else {
8523                        r.append(' ');
8524                    }
8525                    r.append(p.info.name);
8526                }
8527            }
8528            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8529                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8530                if (appOpPkgs != null) {
8531                    appOpPkgs.remove(pkg.packageName);
8532                }
8533            }
8534        }
8535        if (r != null) {
8536            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8537        }
8538
8539        N = pkg.requestedPermissions.size();
8540        r = null;
8541        for (i=0; i<N; i++) {
8542            String perm = pkg.requestedPermissions.get(i);
8543            BasePermission bp = mSettings.mPermissions.get(perm);
8544            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8545                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8546                if (appOpPkgs != null) {
8547                    appOpPkgs.remove(pkg.packageName);
8548                    if (appOpPkgs.isEmpty()) {
8549                        mAppOpPermissionPackages.remove(perm);
8550                    }
8551                }
8552            }
8553        }
8554        if (r != null) {
8555            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8556        }
8557
8558        N = pkg.instrumentation.size();
8559        r = null;
8560        for (i=0; i<N; i++) {
8561            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8562            mInstrumentation.remove(a.getComponentName());
8563            if (DEBUG_REMOVE && chatty) {
8564                if (r == null) {
8565                    r = new StringBuilder(256);
8566                } else {
8567                    r.append(' ');
8568                }
8569                r.append(a.info.name);
8570            }
8571        }
8572        if (r != null) {
8573            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8574        }
8575
8576        r = null;
8577        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8578            // Only system apps can hold shared libraries.
8579            if (pkg.libraryNames != null) {
8580                for (i=0; i<pkg.libraryNames.size(); i++) {
8581                    String name = pkg.libraryNames.get(i);
8582                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8583                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8584                        mSharedLibraries.remove(name);
8585                        if (DEBUG_REMOVE && chatty) {
8586                            if (r == null) {
8587                                r = new StringBuilder(256);
8588                            } else {
8589                                r.append(' ');
8590                            }
8591                            r.append(name);
8592                        }
8593                    }
8594                }
8595            }
8596        }
8597        if (r != null) {
8598            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8599        }
8600    }
8601
8602    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8603        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8604            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8605                return true;
8606            }
8607        }
8608        return false;
8609    }
8610
8611    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8612    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8613    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8614
8615    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8616            int flags) {
8617        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8618        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8619    }
8620
8621    private void updatePermissionsLPw(String changingPkg,
8622            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8623        // Make sure there are no dangling permission trees.
8624        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8625        while (it.hasNext()) {
8626            final BasePermission bp = it.next();
8627            if (bp.packageSetting == null) {
8628                // We may not yet have parsed the package, so just see if
8629                // we still know about its settings.
8630                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8631            }
8632            if (bp.packageSetting == null) {
8633                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8634                        + " from package " + bp.sourcePackage);
8635                it.remove();
8636            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8637                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8638                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8639                            + " from package " + bp.sourcePackage);
8640                    flags |= UPDATE_PERMISSIONS_ALL;
8641                    it.remove();
8642                }
8643            }
8644        }
8645
8646        // Make sure all dynamic permissions have been assigned to a package,
8647        // and make sure there are no dangling permissions.
8648        it = mSettings.mPermissions.values().iterator();
8649        while (it.hasNext()) {
8650            final BasePermission bp = it.next();
8651            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8652                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8653                        + bp.name + " pkg=" + bp.sourcePackage
8654                        + " info=" + bp.pendingInfo);
8655                if (bp.packageSetting == null && bp.pendingInfo != null) {
8656                    final BasePermission tree = findPermissionTreeLP(bp.name);
8657                    if (tree != null && tree.perm != null) {
8658                        bp.packageSetting = tree.packageSetting;
8659                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8660                                new PermissionInfo(bp.pendingInfo));
8661                        bp.perm.info.packageName = tree.perm.info.packageName;
8662                        bp.perm.info.name = bp.name;
8663                        bp.uid = tree.uid;
8664                    }
8665                }
8666            }
8667            if (bp.packageSetting == null) {
8668                // We may not yet have parsed the package, so just see if
8669                // we still know about its settings.
8670                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8671            }
8672            if (bp.packageSetting == null) {
8673                Slog.w(TAG, "Removing dangling permission: " + bp.name
8674                        + " from package " + bp.sourcePackage);
8675                it.remove();
8676            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8677                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8678                    Slog.i(TAG, "Removing old permission: " + bp.name
8679                            + " from package " + bp.sourcePackage);
8680                    flags |= UPDATE_PERMISSIONS_ALL;
8681                    it.remove();
8682                }
8683            }
8684        }
8685
8686        // Now update the permissions for all packages, in particular
8687        // replace the granted permissions of the system packages.
8688        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8689            for (PackageParser.Package pkg : mPackages.values()) {
8690                if (pkg != pkgInfo) {
8691                    // Only replace for packages on requested volume
8692                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8693                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8694                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8695                    grantPermissionsLPw(pkg, replace, changingPkg);
8696                }
8697            }
8698        }
8699
8700        if (pkgInfo != null) {
8701            // Only replace for packages on requested volume
8702            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8703            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8704                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8705            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8706        }
8707    }
8708
8709    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8710            String packageOfInterest) {
8711        // IMPORTANT: There are two types of permissions: install and runtime.
8712        // Install time permissions are granted when the app is installed to
8713        // all device users and users added in the future. Runtime permissions
8714        // are granted at runtime explicitly to specific users. Normal and signature
8715        // protected permissions are install time permissions. Dangerous permissions
8716        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8717        // otherwise they are runtime permissions. This function does not manage
8718        // runtime permissions except for the case an app targeting Lollipop MR1
8719        // being upgraded to target a newer SDK, in which case dangerous permissions
8720        // are transformed from install time to runtime ones.
8721
8722        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8723        if (ps == null) {
8724            return;
8725        }
8726
8727        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8728
8729        PermissionsState permissionsState = ps.getPermissionsState();
8730        PermissionsState origPermissions = permissionsState;
8731
8732        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8733
8734        boolean runtimePermissionsRevoked = false;
8735        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8736
8737        boolean changedInstallPermission = false;
8738
8739        if (replace) {
8740            ps.installPermissionsFixed = false;
8741            if (!ps.isSharedUser()) {
8742                origPermissions = new PermissionsState(permissionsState);
8743                permissionsState.reset();
8744            } else {
8745                // We need to know only about runtime permission changes since the
8746                // calling code always writes the install permissions state but
8747                // the runtime ones are written only if changed. The only cases of
8748                // changed runtime permissions here are promotion of an install to
8749                // runtime and revocation of a runtime from a shared user.
8750                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8751                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8752                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8753                    runtimePermissionsRevoked = true;
8754                }
8755            }
8756        }
8757
8758        permissionsState.setGlobalGids(mGlobalGids);
8759
8760        final int N = pkg.requestedPermissions.size();
8761        for (int i=0; i<N; i++) {
8762            final String name = pkg.requestedPermissions.get(i);
8763            final BasePermission bp = mSettings.mPermissions.get(name);
8764
8765            if (DEBUG_INSTALL) {
8766                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8767            }
8768
8769            if (bp == null || bp.packageSetting == null) {
8770                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8771                    Slog.w(TAG, "Unknown permission " + name
8772                            + " in package " + pkg.packageName);
8773                }
8774                continue;
8775            }
8776
8777            final String perm = bp.name;
8778            boolean allowedSig = false;
8779            int grant = GRANT_DENIED;
8780
8781            // Keep track of app op permissions.
8782            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8783                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8784                if (pkgs == null) {
8785                    pkgs = new ArraySet<>();
8786                    mAppOpPermissionPackages.put(bp.name, pkgs);
8787                }
8788                pkgs.add(pkg.packageName);
8789            }
8790
8791            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8792            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8793                    >= Build.VERSION_CODES.M;
8794            switch (level) {
8795                case PermissionInfo.PROTECTION_NORMAL: {
8796                    // For all apps normal permissions are install time ones.
8797                    grant = GRANT_INSTALL;
8798                } break;
8799
8800                case PermissionInfo.PROTECTION_DANGEROUS: {
8801                    // If a permission review is required for legacy apps we represent
8802                    // their permissions as always granted runtime ones since we need
8803                    // to keep the review required permission flag per user while an
8804                    // install permission's state is shared across all users.
8805                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8806                        // For legacy apps dangerous permissions are install time ones.
8807                        grant = GRANT_INSTALL;
8808                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8809                        // For legacy apps that became modern, install becomes runtime.
8810                        grant = GRANT_UPGRADE;
8811                    } else if (mPromoteSystemApps
8812                            && isSystemApp(ps)
8813                            && mExistingSystemPackages.contains(ps.name)) {
8814                        // For legacy system apps, install becomes runtime.
8815                        // We cannot check hasInstallPermission() for system apps since those
8816                        // permissions were granted implicitly and not persisted pre-M.
8817                        grant = GRANT_UPGRADE;
8818                    } else {
8819                        // For modern apps keep runtime permissions unchanged.
8820                        grant = GRANT_RUNTIME;
8821                    }
8822                } break;
8823
8824                case PermissionInfo.PROTECTION_SIGNATURE: {
8825                    // For all apps signature permissions are install time ones.
8826                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8827                    if (allowedSig) {
8828                        grant = GRANT_INSTALL;
8829                    }
8830                } break;
8831            }
8832
8833            if (DEBUG_INSTALL) {
8834                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8835            }
8836
8837            if (grant != GRANT_DENIED) {
8838                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8839                    // If this is an existing, non-system package, then
8840                    // we can't add any new permissions to it.
8841                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8842                        // Except...  if this is a permission that was added
8843                        // to the platform (note: need to only do this when
8844                        // updating the platform).
8845                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8846                            grant = GRANT_DENIED;
8847                        }
8848                    }
8849                }
8850
8851                switch (grant) {
8852                    case GRANT_INSTALL: {
8853                        // Revoke this as runtime permission to handle the case of
8854                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8855                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8856                            if (origPermissions.getRuntimePermissionState(
8857                                    bp.name, userId) != null) {
8858                                // Revoke the runtime permission and clear the flags.
8859                                origPermissions.revokeRuntimePermission(bp, userId);
8860                                origPermissions.updatePermissionFlags(bp, userId,
8861                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8862                                // If we revoked a permission permission, we have to write.
8863                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8864                                        changedRuntimePermissionUserIds, userId);
8865                            }
8866                        }
8867                        // Grant an install permission.
8868                        if (permissionsState.grantInstallPermission(bp) !=
8869                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8870                            changedInstallPermission = true;
8871                        }
8872                    } break;
8873
8874                    case GRANT_RUNTIME: {
8875                        // Grant previously granted runtime permissions.
8876                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8877                            PermissionState permissionState = origPermissions
8878                                    .getRuntimePermissionState(bp.name, userId);
8879                            int flags = permissionState != null
8880                                    ? permissionState.getFlags() : 0;
8881                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8882                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8883                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8884                                    // If we cannot put the permission as it was, we have to write.
8885                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8886                                            changedRuntimePermissionUserIds, userId);
8887                                }
8888                                // If the app supports runtime permissions no need for a review.
8889                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8890                                        && appSupportsRuntimePermissions
8891                                        && (flags & PackageManager
8892                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8893                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8894                                    // Since we changed the flags, we have to write.
8895                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8896                                            changedRuntimePermissionUserIds, userId);
8897                                }
8898                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8899                                    && !appSupportsRuntimePermissions) {
8900                                // For legacy apps that need a permission review, every new
8901                                // runtime permission is granted but it is pending a review.
8902                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8903                                    permissionsState.grantRuntimePermission(bp, userId);
8904                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8905                                    // We changed the permission and flags, hence have to write.
8906                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8907                                            changedRuntimePermissionUserIds, userId);
8908                                }
8909                            }
8910                            // Propagate the permission flags.
8911                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8912                        }
8913                    } break;
8914
8915                    case GRANT_UPGRADE: {
8916                        // Grant runtime permissions for a previously held install permission.
8917                        PermissionState permissionState = origPermissions
8918                                .getInstallPermissionState(bp.name);
8919                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8920
8921                        if (origPermissions.revokeInstallPermission(bp)
8922                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8923                            // We will be transferring the permission flags, so clear them.
8924                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8925                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8926                            changedInstallPermission = true;
8927                        }
8928
8929                        // If the permission is not to be promoted to runtime we ignore it and
8930                        // also its other flags as they are not applicable to install permissions.
8931                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8932                            for (int userId : currentUserIds) {
8933                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8934                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8935                                    // Transfer the permission flags.
8936                                    permissionsState.updatePermissionFlags(bp, userId,
8937                                            flags, flags);
8938                                    // If we granted the permission, we have to write.
8939                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8940                                            changedRuntimePermissionUserIds, userId);
8941                                }
8942                            }
8943                        }
8944                    } break;
8945
8946                    default: {
8947                        if (packageOfInterest == null
8948                                || packageOfInterest.equals(pkg.packageName)) {
8949                            Slog.w(TAG, "Not granting permission " + perm
8950                                    + " to package " + pkg.packageName
8951                                    + " because it was previously installed without");
8952                        }
8953                    } break;
8954                }
8955            } else {
8956                if (permissionsState.revokeInstallPermission(bp) !=
8957                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8958                    // Also drop the permission flags.
8959                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8960                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8961                    changedInstallPermission = true;
8962                    Slog.i(TAG, "Un-granting permission " + perm
8963                            + " from package " + pkg.packageName
8964                            + " (protectionLevel=" + bp.protectionLevel
8965                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8966                            + ")");
8967                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8968                    // Don't print warning for app op permissions, since it is fine for them
8969                    // not to be granted, there is a UI for the user to decide.
8970                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8971                        Slog.w(TAG, "Not granting permission " + perm
8972                                + " to package " + pkg.packageName
8973                                + " (protectionLevel=" + bp.protectionLevel
8974                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8975                                + ")");
8976                    }
8977                }
8978            }
8979        }
8980
8981        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8982                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8983            // This is the first that we have heard about this package, so the
8984            // permissions we have now selected are fixed until explicitly
8985            // changed.
8986            ps.installPermissionsFixed = true;
8987        }
8988
8989        // Persist the runtime permissions state for users with changes. If permissions
8990        // were revoked because no app in the shared user declares them we have to
8991        // write synchronously to avoid losing runtime permissions state.
8992        for (int userId : changedRuntimePermissionUserIds) {
8993            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8994        }
8995
8996        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8997    }
8998
8999    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9000        boolean allowed = false;
9001        final int NP = PackageParser.NEW_PERMISSIONS.length;
9002        for (int ip=0; ip<NP; ip++) {
9003            final PackageParser.NewPermissionInfo npi
9004                    = PackageParser.NEW_PERMISSIONS[ip];
9005            if (npi.name.equals(perm)
9006                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9007                allowed = true;
9008                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9009                        + pkg.packageName);
9010                break;
9011            }
9012        }
9013        return allowed;
9014    }
9015
9016    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9017            BasePermission bp, PermissionsState origPermissions) {
9018        boolean allowed;
9019        allowed = (compareSignatures(
9020                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9021                        == PackageManager.SIGNATURE_MATCH)
9022                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9023                        == PackageManager.SIGNATURE_MATCH);
9024        if (!allowed && (bp.protectionLevel
9025                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9026            if (isSystemApp(pkg)) {
9027                // For updated system applications, a system permission
9028                // is granted only if it had been defined by the original application.
9029                if (pkg.isUpdatedSystemApp()) {
9030                    final PackageSetting sysPs = mSettings
9031                            .getDisabledSystemPkgLPr(pkg.packageName);
9032                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9033                        // If the original was granted this permission, we take
9034                        // that grant decision as read and propagate it to the
9035                        // update.
9036                        if (sysPs.isPrivileged()) {
9037                            allowed = true;
9038                        }
9039                    } else {
9040                        // The system apk may have been updated with an older
9041                        // version of the one on the data partition, but which
9042                        // granted a new system permission that it didn't have
9043                        // before.  In this case we do want to allow the app to
9044                        // now get the new permission if the ancestral apk is
9045                        // privileged to get it.
9046                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9047                            for (int j=0;
9048                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9049                                if (perm.equals(
9050                                        sysPs.pkg.requestedPermissions.get(j))) {
9051                                    allowed = true;
9052                                    break;
9053                                }
9054                            }
9055                        }
9056                    }
9057                } else {
9058                    allowed = isPrivilegedApp(pkg);
9059                }
9060            }
9061        }
9062        if (!allowed) {
9063            if (!allowed && (bp.protectionLevel
9064                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9065                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9066                // If this was a previously normal/dangerous permission that got moved
9067                // to a system permission as part of the runtime permission redesign, then
9068                // we still want to blindly grant it to old apps.
9069                allowed = true;
9070            }
9071            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9072                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9073                // If this permission is to be granted to the system installer and
9074                // this app is an installer, then it gets the permission.
9075                allowed = true;
9076            }
9077            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9078                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9079                // If this permission is to be granted to the system verifier and
9080                // this app is a verifier, then it gets the permission.
9081                allowed = true;
9082            }
9083            if (!allowed && (bp.protectionLevel
9084                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9085                    && isSystemApp(pkg)) {
9086                // Any pre-installed system app is allowed to get this permission.
9087                allowed = true;
9088            }
9089            if (!allowed && (bp.protectionLevel
9090                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9091                // For development permissions, a development permission
9092                // is granted only if it was already granted.
9093                allowed = origPermissions.hasInstallPermission(perm);
9094            }
9095        }
9096        return allowed;
9097    }
9098
9099    final class ActivityIntentResolver
9100            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9101        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9102                boolean defaultOnly, int userId) {
9103            if (!sUserManager.exists(userId)) return null;
9104            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9105            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9106        }
9107
9108        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9109                int userId) {
9110            if (!sUserManager.exists(userId)) return null;
9111            mFlags = flags;
9112            return super.queryIntent(intent, resolvedType,
9113                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9114        }
9115
9116        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9117                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9118            if (!sUserManager.exists(userId)) return null;
9119            if (packageActivities == null) {
9120                return null;
9121            }
9122            mFlags = flags;
9123            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9124            final int N = packageActivities.size();
9125            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9126                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9127
9128            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9129            for (int i = 0; i < N; ++i) {
9130                intentFilters = packageActivities.get(i).intents;
9131                if (intentFilters != null && intentFilters.size() > 0) {
9132                    PackageParser.ActivityIntentInfo[] array =
9133                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9134                    intentFilters.toArray(array);
9135                    listCut.add(array);
9136                }
9137            }
9138            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9139        }
9140
9141        public final void addActivity(PackageParser.Activity a, String type) {
9142            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9143            mActivities.put(a.getComponentName(), a);
9144            if (DEBUG_SHOW_INFO)
9145                Log.v(
9146                TAG, "  " + type + " " +
9147                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9148            if (DEBUG_SHOW_INFO)
9149                Log.v(TAG, "    Class=" + a.info.name);
9150            final int NI = a.intents.size();
9151            for (int j=0; j<NI; j++) {
9152                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9153                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9154                    intent.setPriority(0);
9155                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9156                            + a.className + " with priority > 0, forcing to 0");
9157                }
9158                if (DEBUG_SHOW_INFO) {
9159                    Log.v(TAG, "    IntentFilter:");
9160                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9161                }
9162                if (!intent.debugCheck()) {
9163                    Log.w(TAG, "==> For Activity " + a.info.name);
9164                }
9165                addFilter(intent);
9166            }
9167        }
9168
9169        public final void removeActivity(PackageParser.Activity a, String type) {
9170            mActivities.remove(a.getComponentName());
9171            if (DEBUG_SHOW_INFO) {
9172                Log.v(TAG, "  " + type + " "
9173                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9174                                : a.info.name) + ":");
9175                Log.v(TAG, "    Class=" + a.info.name);
9176            }
9177            final int NI = a.intents.size();
9178            for (int j=0; j<NI; j++) {
9179                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9180                if (DEBUG_SHOW_INFO) {
9181                    Log.v(TAG, "    IntentFilter:");
9182                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9183                }
9184                removeFilter(intent);
9185            }
9186        }
9187
9188        @Override
9189        protected boolean allowFilterResult(
9190                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9191            ActivityInfo filterAi = filter.activity.info;
9192            for (int i=dest.size()-1; i>=0; i--) {
9193                ActivityInfo destAi = dest.get(i).activityInfo;
9194                if (destAi.name == filterAi.name
9195                        && destAi.packageName == filterAi.packageName) {
9196                    return false;
9197                }
9198            }
9199            return true;
9200        }
9201
9202        @Override
9203        protected ActivityIntentInfo[] newArray(int size) {
9204            return new ActivityIntentInfo[size];
9205        }
9206
9207        @Override
9208        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9209            if (!sUserManager.exists(userId)) return true;
9210            PackageParser.Package p = filter.activity.owner;
9211            if (p != null) {
9212                PackageSetting ps = (PackageSetting)p.mExtras;
9213                if (ps != null) {
9214                    // System apps are never considered stopped for purposes of
9215                    // filtering, because there may be no way for the user to
9216                    // actually re-launch them.
9217                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9218                            && ps.getStopped(userId);
9219                }
9220            }
9221            return false;
9222        }
9223
9224        @Override
9225        protected boolean isPackageForFilter(String packageName,
9226                PackageParser.ActivityIntentInfo info) {
9227            return packageName.equals(info.activity.owner.packageName);
9228        }
9229
9230        @Override
9231        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9232                int match, int userId) {
9233            if (!sUserManager.exists(userId)) return null;
9234            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9235                return null;
9236            }
9237            final PackageParser.Activity activity = info.activity;
9238            if (mSafeMode && (activity.info.applicationInfo.flags
9239                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9240                return null;
9241            }
9242            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9243            if (ps == null) {
9244                return null;
9245            }
9246            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9247                    ps.readUserState(userId), userId);
9248            if (ai == null) {
9249                return null;
9250            }
9251            final ResolveInfo res = new ResolveInfo();
9252            res.activityInfo = ai;
9253            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9254                res.filter = info;
9255            }
9256            if (info != null) {
9257                res.handleAllWebDataURI = info.handleAllWebDataURI();
9258            }
9259            res.priority = info.getPriority();
9260            res.preferredOrder = activity.owner.mPreferredOrder;
9261            //System.out.println("Result: " + res.activityInfo.className +
9262            //                   " = " + res.priority);
9263            res.match = match;
9264            res.isDefault = info.hasDefault;
9265            res.labelRes = info.labelRes;
9266            res.nonLocalizedLabel = info.nonLocalizedLabel;
9267            if (userNeedsBadging(userId)) {
9268                res.noResourceId = true;
9269            } else {
9270                res.icon = info.icon;
9271            }
9272            res.iconResourceId = info.icon;
9273            res.system = res.activityInfo.applicationInfo.isSystemApp();
9274            return res;
9275        }
9276
9277        @Override
9278        protected void sortResults(List<ResolveInfo> results) {
9279            Collections.sort(results, mResolvePrioritySorter);
9280        }
9281
9282        @Override
9283        protected void dumpFilter(PrintWriter out, String prefix,
9284                PackageParser.ActivityIntentInfo filter) {
9285            out.print(prefix); out.print(
9286                    Integer.toHexString(System.identityHashCode(filter.activity)));
9287                    out.print(' ');
9288                    filter.activity.printComponentShortName(out);
9289                    out.print(" filter ");
9290                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9291        }
9292
9293        @Override
9294        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9295            return filter.activity;
9296        }
9297
9298        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9299            PackageParser.Activity activity = (PackageParser.Activity)label;
9300            out.print(prefix); out.print(
9301                    Integer.toHexString(System.identityHashCode(activity)));
9302                    out.print(' ');
9303                    activity.printComponentShortName(out);
9304            if (count > 1) {
9305                out.print(" ("); out.print(count); out.print(" filters)");
9306            }
9307            out.println();
9308        }
9309
9310//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9311//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9312//            final List<ResolveInfo> retList = Lists.newArrayList();
9313//            while (i.hasNext()) {
9314//                final ResolveInfo resolveInfo = i.next();
9315//                if (isEnabledLP(resolveInfo.activityInfo)) {
9316//                    retList.add(resolveInfo);
9317//                }
9318//            }
9319//            return retList;
9320//        }
9321
9322        // Keys are String (activity class name), values are Activity.
9323        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9324                = new ArrayMap<ComponentName, PackageParser.Activity>();
9325        private int mFlags;
9326    }
9327
9328    private final class ServiceIntentResolver
9329            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9330        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9331                boolean defaultOnly, int userId) {
9332            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9333            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9334        }
9335
9336        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9337                int userId) {
9338            if (!sUserManager.exists(userId)) return null;
9339            mFlags = flags;
9340            return super.queryIntent(intent, resolvedType,
9341                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9342        }
9343
9344        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9345                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9346            if (!sUserManager.exists(userId)) return null;
9347            if (packageServices == null) {
9348                return null;
9349            }
9350            mFlags = flags;
9351            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9352            final int N = packageServices.size();
9353            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9354                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9355
9356            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9357            for (int i = 0; i < N; ++i) {
9358                intentFilters = packageServices.get(i).intents;
9359                if (intentFilters != null && intentFilters.size() > 0) {
9360                    PackageParser.ServiceIntentInfo[] array =
9361                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9362                    intentFilters.toArray(array);
9363                    listCut.add(array);
9364                }
9365            }
9366            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9367        }
9368
9369        public final void addService(PackageParser.Service s) {
9370            mServices.put(s.getComponentName(), s);
9371            if (DEBUG_SHOW_INFO) {
9372                Log.v(TAG, "  "
9373                        + (s.info.nonLocalizedLabel != null
9374                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9375                Log.v(TAG, "    Class=" + s.info.name);
9376            }
9377            final int NI = s.intents.size();
9378            int j;
9379            for (j=0; j<NI; j++) {
9380                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9381                if (DEBUG_SHOW_INFO) {
9382                    Log.v(TAG, "    IntentFilter:");
9383                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9384                }
9385                if (!intent.debugCheck()) {
9386                    Log.w(TAG, "==> For Service " + s.info.name);
9387                }
9388                addFilter(intent);
9389            }
9390        }
9391
9392        public final void removeService(PackageParser.Service s) {
9393            mServices.remove(s.getComponentName());
9394            if (DEBUG_SHOW_INFO) {
9395                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9396                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9397                Log.v(TAG, "    Class=" + s.info.name);
9398            }
9399            final int NI = s.intents.size();
9400            int j;
9401            for (j=0; j<NI; j++) {
9402                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9403                if (DEBUG_SHOW_INFO) {
9404                    Log.v(TAG, "    IntentFilter:");
9405                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9406                }
9407                removeFilter(intent);
9408            }
9409        }
9410
9411        @Override
9412        protected boolean allowFilterResult(
9413                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9414            ServiceInfo filterSi = filter.service.info;
9415            for (int i=dest.size()-1; i>=0; i--) {
9416                ServiceInfo destAi = dest.get(i).serviceInfo;
9417                if (destAi.name == filterSi.name
9418                        && destAi.packageName == filterSi.packageName) {
9419                    return false;
9420                }
9421            }
9422            return true;
9423        }
9424
9425        @Override
9426        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9427            return new PackageParser.ServiceIntentInfo[size];
9428        }
9429
9430        @Override
9431        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9432            if (!sUserManager.exists(userId)) return true;
9433            PackageParser.Package p = filter.service.owner;
9434            if (p != null) {
9435                PackageSetting ps = (PackageSetting)p.mExtras;
9436                if (ps != null) {
9437                    // System apps are never considered stopped for purposes of
9438                    // filtering, because there may be no way for the user to
9439                    // actually re-launch them.
9440                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9441                            && ps.getStopped(userId);
9442                }
9443            }
9444            return false;
9445        }
9446
9447        @Override
9448        protected boolean isPackageForFilter(String packageName,
9449                PackageParser.ServiceIntentInfo info) {
9450            return packageName.equals(info.service.owner.packageName);
9451        }
9452
9453        @Override
9454        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9455                int match, int userId) {
9456            if (!sUserManager.exists(userId)) return null;
9457            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9458            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9459                return null;
9460            }
9461            final PackageParser.Service service = info.service;
9462            if (mSafeMode && (service.info.applicationInfo.flags
9463                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9464                return null;
9465            }
9466            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9467            if (ps == null) {
9468                return null;
9469            }
9470            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9471                    ps.readUserState(userId), userId);
9472            if (si == null) {
9473                return null;
9474            }
9475            final ResolveInfo res = new ResolveInfo();
9476            res.serviceInfo = si;
9477            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9478                res.filter = filter;
9479            }
9480            res.priority = info.getPriority();
9481            res.preferredOrder = service.owner.mPreferredOrder;
9482            res.match = match;
9483            res.isDefault = info.hasDefault;
9484            res.labelRes = info.labelRes;
9485            res.nonLocalizedLabel = info.nonLocalizedLabel;
9486            res.icon = info.icon;
9487            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9488            return res;
9489        }
9490
9491        @Override
9492        protected void sortResults(List<ResolveInfo> results) {
9493            Collections.sort(results, mResolvePrioritySorter);
9494        }
9495
9496        @Override
9497        protected void dumpFilter(PrintWriter out, String prefix,
9498                PackageParser.ServiceIntentInfo filter) {
9499            out.print(prefix); out.print(
9500                    Integer.toHexString(System.identityHashCode(filter.service)));
9501                    out.print(' ');
9502                    filter.service.printComponentShortName(out);
9503                    out.print(" filter ");
9504                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9505        }
9506
9507        @Override
9508        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9509            return filter.service;
9510        }
9511
9512        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9513            PackageParser.Service service = (PackageParser.Service)label;
9514            out.print(prefix); out.print(
9515                    Integer.toHexString(System.identityHashCode(service)));
9516                    out.print(' ');
9517                    service.printComponentShortName(out);
9518            if (count > 1) {
9519                out.print(" ("); out.print(count); out.print(" filters)");
9520            }
9521            out.println();
9522        }
9523
9524//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9525//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9526//            final List<ResolveInfo> retList = Lists.newArrayList();
9527//            while (i.hasNext()) {
9528//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9529//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9530//                    retList.add(resolveInfo);
9531//                }
9532//            }
9533//            return retList;
9534//        }
9535
9536        // Keys are String (activity class name), values are Activity.
9537        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9538                = new ArrayMap<ComponentName, PackageParser.Service>();
9539        private int mFlags;
9540    };
9541
9542    private final class ProviderIntentResolver
9543            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9544        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9545                boolean defaultOnly, int userId) {
9546            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9547            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9548        }
9549
9550        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9551                int userId) {
9552            if (!sUserManager.exists(userId))
9553                return null;
9554            mFlags = flags;
9555            return super.queryIntent(intent, resolvedType,
9556                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9557        }
9558
9559        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9560                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9561            if (!sUserManager.exists(userId))
9562                return null;
9563            if (packageProviders == null) {
9564                return null;
9565            }
9566            mFlags = flags;
9567            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9568            final int N = packageProviders.size();
9569            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9570                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9571
9572            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9573            for (int i = 0; i < N; ++i) {
9574                intentFilters = packageProviders.get(i).intents;
9575                if (intentFilters != null && intentFilters.size() > 0) {
9576                    PackageParser.ProviderIntentInfo[] array =
9577                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9578                    intentFilters.toArray(array);
9579                    listCut.add(array);
9580                }
9581            }
9582            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9583        }
9584
9585        public final void addProvider(PackageParser.Provider p) {
9586            if (mProviders.containsKey(p.getComponentName())) {
9587                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9588                return;
9589            }
9590
9591            mProviders.put(p.getComponentName(), p);
9592            if (DEBUG_SHOW_INFO) {
9593                Log.v(TAG, "  "
9594                        + (p.info.nonLocalizedLabel != null
9595                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9596                Log.v(TAG, "    Class=" + p.info.name);
9597            }
9598            final int NI = p.intents.size();
9599            int j;
9600            for (j = 0; j < NI; j++) {
9601                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9602                if (DEBUG_SHOW_INFO) {
9603                    Log.v(TAG, "    IntentFilter:");
9604                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9605                }
9606                if (!intent.debugCheck()) {
9607                    Log.w(TAG, "==> For Provider " + p.info.name);
9608                }
9609                addFilter(intent);
9610            }
9611        }
9612
9613        public final void removeProvider(PackageParser.Provider p) {
9614            mProviders.remove(p.getComponentName());
9615            if (DEBUG_SHOW_INFO) {
9616                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9617                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9618                Log.v(TAG, "    Class=" + p.info.name);
9619            }
9620            final int NI = p.intents.size();
9621            int j;
9622            for (j = 0; j < NI; j++) {
9623                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9624                if (DEBUG_SHOW_INFO) {
9625                    Log.v(TAG, "    IntentFilter:");
9626                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9627                }
9628                removeFilter(intent);
9629            }
9630        }
9631
9632        @Override
9633        protected boolean allowFilterResult(
9634                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9635            ProviderInfo filterPi = filter.provider.info;
9636            for (int i = dest.size() - 1; i >= 0; i--) {
9637                ProviderInfo destPi = dest.get(i).providerInfo;
9638                if (destPi.name == filterPi.name
9639                        && destPi.packageName == filterPi.packageName) {
9640                    return false;
9641                }
9642            }
9643            return true;
9644        }
9645
9646        @Override
9647        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9648            return new PackageParser.ProviderIntentInfo[size];
9649        }
9650
9651        @Override
9652        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9653            if (!sUserManager.exists(userId))
9654                return true;
9655            PackageParser.Package p = filter.provider.owner;
9656            if (p != null) {
9657                PackageSetting ps = (PackageSetting) p.mExtras;
9658                if (ps != null) {
9659                    // System apps are never considered stopped for purposes of
9660                    // filtering, because there may be no way for the user to
9661                    // actually re-launch them.
9662                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9663                            && ps.getStopped(userId);
9664                }
9665            }
9666            return false;
9667        }
9668
9669        @Override
9670        protected boolean isPackageForFilter(String packageName,
9671                PackageParser.ProviderIntentInfo info) {
9672            return packageName.equals(info.provider.owner.packageName);
9673        }
9674
9675        @Override
9676        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9677                int match, int userId) {
9678            if (!sUserManager.exists(userId))
9679                return null;
9680            final PackageParser.ProviderIntentInfo info = filter;
9681            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9682                return null;
9683            }
9684            final PackageParser.Provider provider = info.provider;
9685            if (mSafeMode && (provider.info.applicationInfo.flags
9686                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9687                return null;
9688            }
9689            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9690            if (ps == null) {
9691                return null;
9692            }
9693            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9694                    ps.readUserState(userId), userId);
9695            if (pi == null) {
9696                return null;
9697            }
9698            final ResolveInfo res = new ResolveInfo();
9699            res.providerInfo = pi;
9700            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9701                res.filter = filter;
9702            }
9703            res.priority = info.getPriority();
9704            res.preferredOrder = provider.owner.mPreferredOrder;
9705            res.match = match;
9706            res.isDefault = info.hasDefault;
9707            res.labelRes = info.labelRes;
9708            res.nonLocalizedLabel = info.nonLocalizedLabel;
9709            res.icon = info.icon;
9710            res.system = res.providerInfo.applicationInfo.isSystemApp();
9711            return res;
9712        }
9713
9714        @Override
9715        protected void sortResults(List<ResolveInfo> results) {
9716            Collections.sort(results, mResolvePrioritySorter);
9717        }
9718
9719        @Override
9720        protected void dumpFilter(PrintWriter out, String prefix,
9721                PackageParser.ProviderIntentInfo filter) {
9722            out.print(prefix);
9723            out.print(
9724                    Integer.toHexString(System.identityHashCode(filter.provider)));
9725            out.print(' ');
9726            filter.provider.printComponentShortName(out);
9727            out.print(" filter ");
9728            out.println(Integer.toHexString(System.identityHashCode(filter)));
9729        }
9730
9731        @Override
9732        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9733            return filter.provider;
9734        }
9735
9736        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9737            PackageParser.Provider provider = (PackageParser.Provider)label;
9738            out.print(prefix); out.print(
9739                    Integer.toHexString(System.identityHashCode(provider)));
9740                    out.print(' ');
9741                    provider.printComponentShortName(out);
9742            if (count > 1) {
9743                out.print(" ("); out.print(count); out.print(" filters)");
9744            }
9745            out.println();
9746        }
9747
9748        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9749                = new ArrayMap<ComponentName, PackageParser.Provider>();
9750        private int mFlags;
9751    }
9752
9753    private static final class EphemeralIntentResolver
9754            extends IntentResolver<IntentFilter, ResolveInfo> {
9755        @Override
9756        protected IntentFilter[] newArray(int size) {
9757            return new IntentFilter[size];
9758        }
9759
9760        @Override
9761        protected boolean isPackageForFilter(String packageName, IntentFilter info) {
9762            return true;
9763        }
9764
9765        @Override
9766        protected ResolveInfo newResult(IntentFilter info, int match, int userId) {
9767            if (!sUserManager.exists(userId)) return null;
9768            final ResolveInfo res = new ResolveInfo();
9769            res.filter = info;
9770            return res;
9771        }
9772    }
9773
9774    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9775            new Comparator<ResolveInfo>() {
9776        public int compare(ResolveInfo r1, ResolveInfo r2) {
9777            int v1 = r1.priority;
9778            int v2 = r2.priority;
9779            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9780            if (v1 != v2) {
9781                return (v1 > v2) ? -1 : 1;
9782            }
9783            v1 = r1.preferredOrder;
9784            v2 = r2.preferredOrder;
9785            if (v1 != v2) {
9786                return (v1 > v2) ? -1 : 1;
9787            }
9788            if (r1.isDefault != r2.isDefault) {
9789                return r1.isDefault ? -1 : 1;
9790            }
9791            v1 = r1.match;
9792            v2 = r2.match;
9793            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9794            if (v1 != v2) {
9795                return (v1 > v2) ? -1 : 1;
9796            }
9797            if (r1.system != r2.system) {
9798                return r1.system ? -1 : 1;
9799            }
9800            if (r1.activityInfo != null) {
9801                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9802            }
9803            if (r1.serviceInfo != null) {
9804                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9805            }
9806            if (r1.providerInfo != null) {
9807                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9808            }
9809            return 0;
9810        }
9811    };
9812
9813    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9814            new Comparator<ProviderInfo>() {
9815        public int compare(ProviderInfo p1, ProviderInfo p2) {
9816            final int v1 = p1.initOrder;
9817            final int v2 = p2.initOrder;
9818            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9819        }
9820    };
9821
9822    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9823            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9824            final int[] userIds) {
9825        mHandler.post(new Runnable() {
9826            @Override
9827            public void run() {
9828                try {
9829                    final IActivityManager am = ActivityManagerNative.getDefault();
9830                    if (am == null) return;
9831                    final int[] resolvedUserIds;
9832                    if (userIds == null) {
9833                        resolvedUserIds = am.getRunningUserIds();
9834                    } else {
9835                        resolvedUserIds = userIds;
9836                    }
9837                    for (int id : resolvedUserIds) {
9838                        final Intent intent = new Intent(action,
9839                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9840                        if (extras != null) {
9841                            intent.putExtras(extras);
9842                        }
9843                        if (targetPkg != null) {
9844                            intent.setPackage(targetPkg);
9845                        }
9846                        // Modify the UID when posting to other users
9847                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9848                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9849                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9850                            intent.putExtra(Intent.EXTRA_UID, uid);
9851                        }
9852                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9853                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9854                        if (DEBUG_BROADCASTS) {
9855                            RuntimeException here = new RuntimeException("here");
9856                            here.fillInStackTrace();
9857                            Slog.d(TAG, "Sending to user " + id + ": "
9858                                    + intent.toShortString(false, true, false, false)
9859                                    + " " + intent.getExtras(), here);
9860                        }
9861                        am.broadcastIntent(null, intent, null, finishedReceiver,
9862                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9863                                null, finishedReceiver != null, false, id);
9864                    }
9865                } catch (RemoteException ex) {
9866                }
9867            }
9868        });
9869    }
9870
9871    /**
9872     * Check if the external storage media is available. This is true if there
9873     * is a mounted external storage medium or if the external storage is
9874     * emulated.
9875     */
9876    private boolean isExternalMediaAvailable() {
9877        return mMediaMounted || Environment.isExternalStorageEmulated();
9878    }
9879
9880    @Override
9881    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9882        // writer
9883        synchronized (mPackages) {
9884            if (!isExternalMediaAvailable()) {
9885                // If the external storage is no longer mounted at this point,
9886                // the caller may not have been able to delete all of this
9887                // packages files and can not delete any more.  Bail.
9888                return null;
9889            }
9890            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9891            if (lastPackage != null) {
9892                pkgs.remove(lastPackage);
9893            }
9894            if (pkgs.size() > 0) {
9895                return pkgs.get(0);
9896            }
9897        }
9898        return null;
9899    }
9900
9901    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9902        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9903                userId, andCode ? 1 : 0, packageName);
9904        if (mSystemReady) {
9905            msg.sendToTarget();
9906        } else {
9907            if (mPostSystemReadyMessages == null) {
9908                mPostSystemReadyMessages = new ArrayList<>();
9909            }
9910            mPostSystemReadyMessages.add(msg);
9911        }
9912    }
9913
9914    void startCleaningPackages() {
9915        // reader
9916        synchronized (mPackages) {
9917            if (!isExternalMediaAvailable()) {
9918                return;
9919            }
9920            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9921                return;
9922            }
9923        }
9924        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9925        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9926        IActivityManager am = ActivityManagerNative.getDefault();
9927        if (am != null) {
9928            try {
9929                am.startService(null, intent, null, mContext.getOpPackageName(),
9930                        UserHandle.USER_SYSTEM);
9931            } catch (RemoteException e) {
9932            }
9933        }
9934    }
9935
9936    @Override
9937    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9938            int installFlags, String installerPackageName, VerificationParams verificationParams,
9939            String packageAbiOverride) {
9940        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9941                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9942    }
9943
9944    @Override
9945    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9946            int installFlags, String installerPackageName, VerificationParams verificationParams,
9947            String packageAbiOverride, int userId) {
9948        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9949
9950        final int callingUid = Binder.getCallingUid();
9951        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9952
9953        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9954            try {
9955                if (observer != null) {
9956                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9957                }
9958            } catch (RemoteException re) {
9959            }
9960            return;
9961        }
9962
9963        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9964            installFlags |= PackageManager.INSTALL_FROM_ADB;
9965
9966        } else {
9967            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9968            // about installerPackageName.
9969
9970            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9971            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9972        }
9973
9974        UserHandle user;
9975        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9976            user = UserHandle.ALL;
9977        } else {
9978            user = new UserHandle(userId);
9979        }
9980
9981        // Only system components can circumvent runtime permissions when installing.
9982        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9983                && mContext.checkCallingOrSelfPermission(Manifest.permission
9984                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9985            throw new SecurityException("You need the "
9986                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9987                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9988        }
9989
9990        verificationParams.setInstallerUid(callingUid);
9991
9992        final File originFile = new File(originPath);
9993        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9994
9995        final Message msg = mHandler.obtainMessage(INIT_COPY);
9996        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9997                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9998        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9999        msg.obj = params;
10000
10001        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10002                System.identityHashCode(msg.obj));
10003        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10004                System.identityHashCode(msg.obj));
10005
10006        mHandler.sendMessage(msg);
10007    }
10008
10009    void installStage(String packageName, File stagedDir, String stagedCid,
10010            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10011            String installerPackageName, int installerUid, UserHandle user) {
10012        if (DEBUG_EPHEMERAL) {
10013            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10014                Slog.d(TAG, "Ephemeral install of " + packageName);
10015            }
10016        }
10017        final VerificationParams verifParams = new VerificationParams(
10018                null, sessionParams.originatingUri, sessionParams.referrerUri,
10019                sessionParams.originatingUid, null);
10020        verifParams.setInstallerUid(installerUid);
10021
10022        final OriginInfo origin;
10023        if (stagedDir != null) {
10024            origin = OriginInfo.fromStagedFile(stagedDir);
10025        } else {
10026            origin = OriginInfo.fromStagedContainer(stagedCid);
10027        }
10028
10029        final Message msg = mHandler.obtainMessage(INIT_COPY);
10030        final InstallParams params = new InstallParams(origin, null, observer,
10031                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10032                verifParams, user, sessionParams.abiOverride,
10033                sessionParams.grantedRuntimePermissions);
10034        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10035        msg.obj = params;
10036
10037        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10038                System.identityHashCode(msg.obj));
10039        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10040                System.identityHashCode(msg.obj));
10041
10042        mHandler.sendMessage(msg);
10043    }
10044
10045    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10046        Bundle extras = new Bundle(1);
10047        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10048
10049        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10050                packageName, extras, 0, null, null, new int[] {userId});
10051        try {
10052            IActivityManager am = ActivityManagerNative.getDefault();
10053            final boolean isSystem =
10054                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10055            if (isSystem && am.isUserRunning(userId, 0)) {
10056                // The just-installed/enabled app is bundled on the system, so presumed
10057                // to be able to run automatically without needing an explicit launch.
10058                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10059                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10060                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10061                        .setPackage(packageName);
10062                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10063                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10064            }
10065        } catch (RemoteException e) {
10066            // shouldn't happen
10067            Slog.w(TAG, "Unable to bootstrap installed package", e);
10068        }
10069    }
10070
10071    @Override
10072    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10073            int userId) {
10074        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10075        PackageSetting pkgSetting;
10076        final int uid = Binder.getCallingUid();
10077        enforceCrossUserPermission(uid, userId, true, true,
10078                "setApplicationHiddenSetting for user " + userId);
10079
10080        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10081            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10082            return false;
10083        }
10084
10085        long callingId = Binder.clearCallingIdentity();
10086        try {
10087            boolean sendAdded = false;
10088            boolean sendRemoved = false;
10089            // writer
10090            synchronized (mPackages) {
10091                pkgSetting = mSettings.mPackages.get(packageName);
10092                if (pkgSetting == null) {
10093                    return false;
10094                }
10095                if (pkgSetting.getHidden(userId) != hidden) {
10096                    pkgSetting.setHidden(hidden, userId);
10097                    mSettings.writePackageRestrictionsLPr(userId);
10098                    if (hidden) {
10099                        sendRemoved = true;
10100                    } else {
10101                        sendAdded = true;
10102                    }
10103                }
10104            }
10105            if (sendAdded) {
10106                sendPackageAddedForUser(packageName, pkgSetting, userId);
10107                return true;
10108            }
10109            if (sendRemoved) {
10110                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10111                        "hiding pkg");
10112                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10113                return true;
10114            }
10115        } finally {
10116            Binder.restoreCallingIdentity(callingId);
10117        }
10118        return false;
10119    }
10120
10121    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10122            int userId) {
10123        final PackageRemovedInfo info = new PackageRemovedInfo();
10124        info.removedPackage = packageName;
10125        info.removedUsers = new int[] {userId};
10126        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10127        info.sendBroadcast(false, false, false);
10128    }
10129
10130    /**
10131     * Returns true if application is not found or there was an error. Otherwise it returns
10132     * the hidden state of the package for the given user.
10133     */
10134    @Override
10135    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10136        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10137        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10138                false, "getApplicationHidden for user " + userId);
10139        PackageSetting pkgSetting;
10140        long callingId = Binder.clearCallingIdentity();
10141        try {
10142            // writer
10143            synchronized (mPackages) {
10144                pkgSetting = mSettings.mPackages.get(packageName);
10145                if (pkgSetting == null) {
10146                    return true;
10147                }
10148                return pkgSetting.getHidden(userId);
10149            }
10150        } finally {
10151            Binder.restoreCallingIdentity(callingId);
10152        }
10153    }
10154
10155    /**
10156     * @hide
10157     */
10158    @Override
10159    public int installExistingPackageAsUser(String packageName, int userId) {
10160        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10161                null);
10162        PackageSetting pkgSetting;
10163        final int uid = Binder.getCallingUid();
10164        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10165                + userId);
10166        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10167            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10168        }
10169
10170        long callingId = Binder.clearCallingIdentity();
10171        try {
10172            boolean sendAdded = false;
10173
10174            // writer
10175            synchronized (mPackages) {
10176                pkgSetting = mSettings.mPackages.get(packageName);
10177                if (pkgSetting == null) {
10178                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10179                }
10180                if (!pkgSetting.getInstalled(userId)) {
10181                    pkgSetting.setInstalled(true, userId);
10182                    pkgSetting.setHidden(false, userId);
10183                    mSettings.writePackageRestrictionsLPr(userId);
10184                    sendAdded = true;
10185                }
10186            }
10187
10188            if (sendAdded) {
10189                sendPackageAddedForUser(packageName, pkgSetting, userId);
10190            }
10191        } finally {
10192            Binder.restoreCallingIdentity(callingId);
10193        }
10194
10195        return PackageManager.INSTALL_SUCCEEDED;
10196    }
10197
10198    boolean isUserRestricted(int userId, String restrictionKey) {
10199        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10200        if (restrictions.getBoolean(restrictionKey, false)) {
10201            Log.w(TAG, "User is restricted: " + restrictionKey);
10202            return true;
10203        }
10204        return false;
10205    }
10206
10207    @Override
10208    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10209        mContext.enforceCallingOrSelfPermission(
10210                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10211                "Only package verification agents can verify applications");
10212
10213        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10214        final PackageVerificationResponse response = new PackageVerificationResponse(
10215                verificationCode, Binder.getCallingUid());
10216        msg.arg1 = id;
10217        msg.obj = response;
10218        mHandler.sendMessage(msg);
10219    }
10220
10221    @Override
10222    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10223            long millisecondsToDelay) {
10224        mContext.enforceCallingOrSelfPermission(
10225                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10226                "Only package verification agents can extend verification timeouts");
10227
10228        final PackageVerificationState state = mPendingVerification.get(id);
10229        final PackageVerificationResponse response = new PackageVerificationResponse(
10230                verificationCodeAtTimeout, Binder.getCallingUid());
10231
10232        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10233            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10234        }
10235        if (millisecondsToDelay < 0) {
10236            millisecondsToDelay = 0;
10237        }
10238        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10239                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10240            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10241        }
10242
10243        if ((state != null) && !state.timeoutExtended()) {
10244            state.extendTimeout();
10245
10246            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10247            msg.arg1 = id;
10248            msg.obj = response;
10249            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10250        }
10251    }
10252
10253    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10254            int verificationCode, UserHandle user) {
10255        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10256        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10257        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10258        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10259        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10260
10261        mContext.sendBroadcastAsUser(intent, user,
10262                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10263    }
10264
10265    private ComponentName matchComponentForVerifier(String packageName,
10266            List<ResolveInfo> receivers) {
10267        ActivityInfo targetReceiver = null;
10268
10269        final int NR = receivers.size();
10270        for (int i = 0; i < NR; i++) {
10271            final ResolveInfo info = receivers.get(i);
10272            if (info.activityInfo == null) {
10273                continue;
10274            }
10275
10276            if (packageName.equals(info.activityInfo.packageName)) {
10277                targetReceiver = info.activityInfo;
10278                break;
10279            }
10280        }
10281
10282        if (targetReceiver == null) {
10283            return null;
10284        }
10285
10286        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10287    }
10288
10289    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10290            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10291        if (pkgInfo.verifiers.length == 0) {
10292            return null;
10293        }
10294
10295        final int N = pkgInfo.verifiers.length;
10296        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10297        for (int i = 0; i < N; i++) {
10298            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10299
10300            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10301                    receivers);
10302            if (comp == null) {
10303                continue;
10304            }
10305
10306            final int verifierUid = getUidForVerifier(verifierInfo);
10307            if (verifierUid == -1) {
10308                continue;
10309            }
10310
10311            if (DEBUG_VERIFY) {
10312                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10313                        + " with the correct signature");
10314            }
10315            sufficientVerifiers.add(comp);
10316            verificationState.addSufficientVerifier(verifierUid);
10317        }
10318
10319        return sufficientVerifiers;
10320    }
10321
10322    private int getUidForVerifier(VerifierInfo verifierInfo) {
10323        synchronized (mPackages) {
10324            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10325            if (pkg == null) {
10326                return -1;
10327            } else if (pkg.mSignatures.length != 1) {
10328                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10329                        + " has more than one signature; ignoring");
10330                return -1;
10331            }
10332
10333            /*
10334             * If the public key of the package's signature does not match
10335             * our expected public key, then this is a different package and
10336             * we should skip.
10337             */
10338
10339            final byte[] expectedPublicKey;
10340            try {
10341                final Signature verifierSig = pkg.mSignatures[0];
10342                final PublicKey publicKey = verifierSig.getPublicKey();
10343                expectedPublicKey = publicKey.getEncoded();
10344            } catch (CertificateException e) {
10345                return -1;
10346            }
10347
10348            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10349
10350            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10351                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10352                        + " does not have the expected public key; ignoring");
10353                return -1;
10354            }
10355
10356            return pkg.applicationInfo.uid;
10357        }
10358    }
10359
10360    @Override
10361    public void finishPackageInstall(int token) {
10362        enforceSystemOrRoot("Only the system is allowed to finish installs");
10363
10364        if (DEBUG_INSTALL) {
10365            Slog.v(TAG, "BM finishing package install for " + token);
10366        }
10367        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10368
10369        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10370        mHandler.sendMessage(msg);
10371    }
10372
10373    /**
10374     * Get the verification agent timeout.
10375     *
10376     * @return verification timeout in milliseconds
10377     */
10378    private long getVerificationTimeout() {
10379        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10380                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10381                DEFAULT_VERIFICATION_TIMEOUT);
10382    }
10383
10384    /**
10385     * Get the default verification agent response code.
10386     *
10387     * @return default verification response code
10388     */
10389    private int getDefaultVerificationResponse() {
10390        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10391                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10392                DEFAULT_VERIFICATION_RESPONSE);
10393    }
10394
10395    /**
10396     * Check whether or not package verification has been enabled.
10397     *
10398     * @return true if verification should be performed
10399     */
10400    private boolean isVerificationEnabled(int userId, int installFlags) {
10401        if (!DEFAULT_VERIFY_ENABLE) {
10402            return false;
10403        }
10404        // TODO: fix b/25118622; don't bypass verification
10405        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10406            return false;
10407        }
10408        // Ephemeral apps don't get the full verification treatment
10409        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10410            if (DEBUG_EPHEMERAL) {
10411                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10412            }
10413            return false;
10414        }
10415
10416        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10417
10418        // Check if installing from ADB
10419        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10420            // Do not run verification in a test harness environment
10421            if (ActivityManager.isRunningInTestHarness()) {
10422                return false;
10423            }
10424            if (ensureVerifyAppsEnabled) {
10425                return true;
10426            }
10427            // Check if the developer does not want package verification for ADB installs
10428            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10429                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10430                return false;
10431            }
10432        }
10433
10434        if (ensureVerifyAppsEnabled) {
10435            return true;
10436        }
10437
10438        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10439                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10440    }
10441
10442    @Override
10443    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10444            throws RemoteException {
10445        mContext.enforceCallingOrSelfPermission(
10446                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10447                "Only intentfilter verification agents can verify applications");
10448
10449        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10450        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10451                Binder.getCallingUid(), verificationCode, failedDomains);
10452        msg.arg1 = id;
10453        msg.obj = response;
10454        mHandler.sendMessage(msg);
10455    }
10456
10457    @Override
10458    public int getIntentVerificationStatus(String packageName, int userId) {
10459        synchronized (mPackages) {
10460            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10461        }
10462    }
10463
10464    @Override
10465    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10466        mContext.enforceCallingOrSelfPermission(
10467                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10468
10469        boolean result = false;
10470        synchronized (mPackages) {
10471            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10472        }
10473        if (result) {
10474            scheduleWritePackageRestrictionsLocked(userId);
10475        }
10476        return result;
10477    }
10478
10479    @Override
10480    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10481        synchronized (mPackages) {
10482            return mSettings.getIntentFilterVerificationsLPr(packageName);
10483        }
10484    }
10485
10486    @Override
10487    public List<IntentFilter> getAllIntentFilters(String packageName) {
10488        if (TextUtils.isEmpty(packageName)) {
10489            return Collections.<IntentFilter>emptyList();
10490        }
10491        synchronized (mPackages) {
10492            PackageParser.Package pkg = mPackages.get(packageName);
10493            if (pkg == null || pkg.activities == null) {
10494                return Collections.<IntentFilter>emptyList();
10495            }
10496            final int count = pkg.activities.size();
10497            ArrayList<IntentFilter> result = new ArrayList<>();
10498            for (int n=0; n<count; n++) {
10499                PackageParser.Activity activity = pkg.activities.get(n);
10500                if (activity.intents != null || activity.intents.size() > 0) {
10501                    result.addAll(activity.intents);
10502                }
10503            }
10504            return result;
10505        }
10506    }
10507
10508    @Override
10509    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10510        mContext.enforceCallingOrSelfPermission(
10511                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10512
10513        synchronized (mPackages) {
10514            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10515            if (packageName != null) {
10516                result |= updateIntentVerificationStatus(packageName,
10517                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10518                        userId);
10519                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10520                        packageName, userId);
10521            }
10522            return result;
10523        }
10524    }
10525
10526    @Override
10527    public String getDefaultBrowserPackageName(int userId) {
10528        synchronized (mPackages) {
10529            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10530        }
10531    }
10532
10533    /**
10534     * Get the "allow unknown sources" setting.
10535     *
10536     * @return the current "allow unknown sources" setting
10537     */
10538    private int getUnknownSourcesSettings() {
10539        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10540                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10541                -1);
10542    }
10543
10544    @Override
10545    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10546        final int uid = Binder.getCallingUid();
10547        // writer
10548        synchronized (mPackages) {
10549            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10550            if (targetPackageSetting == null) {
10551                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10552            }
10553
10554            PackageSetting installerPackageSetting;
10555            if (installerPackageName != null) {
10556                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10557                if (installerPackageSetting == null) {
10558                    throw new IllegalArgumentException("Unknown installer package: "
10559                            + installerPackageName);
10560                }
10561            } else {
10562                installerPackageSetting = null;
10563            }
10564
10565            Signature[] callerSignature;
10566            Object obj = mSettings.getUserIdLPr(uid);
10567            if (obj != null) {
10568                if (obj instanceof SharedUserSetting) {
10569                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10570                } else if (obj instanceof PackageSetting) {
10571                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10572                } else {
10573                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10574                }
10575            } else {
10576                throw new SecurityException("Unknown calling uid " + uid);
10577            }
10578
10579            // Verify: can't set installerPackageName to a package that is
10580            // not signed with the same cert as the caller.
10581            if (installerPackageSetting != null) {
10582                if (compareSignatures(callerSignature,
10583                        installerPackageSetting.signatures.mSignatures)
10584                        != PackageManager.SIGNATURE_MATCH) {
10585                    throw new SecurityException(
10586                            "Caller does not have same cert as new installer package "
10587                            + installerPackageName);
10588                }
10589            }
10590
10591            // Verify: if target already has an installer package, it must
10592            // be signed with the same cert as the caller.
10593            if (targetPackageSetting.installerPackageName != null) {
10594                PackageSetting setting = mSettings.mPackages.get(
10595                        targetPackageSetting.installerPackageName);
10596                // If the currently set package isn't valid, then it's always
10597                // okay to change it.
10598                if (setting != null) {
10599                    if (compareSignatures(callerSignature,
10600                            setting.signatures.mSignatures)
10601                            != PackageManager.SIGNATURE_MATCH) {
10602                        throw new SecurityException(
10603                                "Caller does not have same cert as old installer package "
10604                                + targetPackageSetting.installerPackageName);
10605                    }
10606                }
10607            }
10608
10609            // Okay!
10610            targetPackageSetting.installerPackageName = installerPackageName;
10611            scheduleWriteSettingsLocked();
10612        }
10613    }
10614
10615    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10616        // Queue up an async operation since the package installation may take a little while.
10617        mHandler.post(new Runnable() {
10618            public void run() {
10619                mHandler.removeCallbacks(this);
10620                 // Result object to be returned
10621                PackageInstalledInfo res = new PackageInstalledInfo();
10622                res.returnCode = currentStatus;
10623                res.uid = -1;
10624                res.pkg = null;
10625                res.removedInfo = new PackageRemovedInfo();
10626                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10627                    args.doPreInstall(res.returnCode);
10628                    synchronized (mInstallLock) {
10629                        installPackageTracedLI(args, res);
10630                    }
10631                    args.doPostInstall(res.returnCode, res.uid);
10632                }
10633
10634                // A restore should be performed at this point if (a) the install
10635                // succeeded, (b) the operation is not an update, and (c) the new
10636                // package has not opted out of backup participation.
10637                final boolean update = res.removedInfo.removedPackage != null;
10638                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10639                boolean doRestore = !update
10640                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10641
10642                // Set up the post-install work request bookkeeping.  This will be used
10643                // and cleaned up by the post-install event handling regardless of whether
10644                // there's a restore pass performed.  Token values are >= 1.
10645                int token;
10646                if (mNextInstallToken < 0) mNextInstallToken = 1;
10647                token = mNextInstallToken++;
10648
10649                PostInstallData data = new PostInstallData(args, res);
10650                mRunningInstalls.put(token, data);
10651                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10652
10653                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10654                    // Pass responsibility to the Backup Manager.  It will perform a
10655                    // restore if appropriate, then pass responsibility back to the
10656                    // Package Manager to run the post-install observer callbacks
10657                    // and broadcasts.
10658                    IBackupManager bm = IBackupManager.Stub.asInterface(
10659                            ServiceManager.getService(Context.BACKUP_SERVICE));
10660                    if (bm != null) {
10661                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10662                                + " to BM for possible restore");
10663                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10664                        try {
10665                            // TODO: http://b/22388012
10666                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10667                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10668                            } else {
10669                                doRestore = false;
10670                            }
10671                        } catch (RemoteException e) {
10672                            // can't happen; the backup manager is local
10673                        } catch (Exception e) {
10674                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10675                            doRestore = false;
10676                        }
10677                    } else {
10678                        Slog.e(TAG, "Backup Manager not found!");
10679                        doRestore = false;
10680                    }
10681                }
10682
10683                if (!doRestore) {
10684                    // No restore possible, or the Backup Manager was mysteriously not
10685                    // available -- just fire the post-install work request directly.
10686                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10687
10688                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10689
10690                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10691                    mHandler.sendMessage(msg);
10692                }
10693            }
10694        });
10695    }
10696
10697    private abstract class HandlerParams {
10698        private static final int MAX_RETRIES = 4;
10699
10700        /**
10701         * Number of times startCopy() has been attempted and had a non-fatal
10702         * error.
10703         */
10704        private int mRetries = 0;
10705
10706        /** User handle for the user requesting the information or installation. */
10707        private final UserHandle mUser;
10708        String traceMethod;
10709        int traceCookie;
10710
10711        HandlerParams(UserHandle user) {
10712            mUser = user;
10713        }
10714
10715        UserHandle getUser() {
10716            return mUser;
10717        }
10718
10719        HandlerParams setTraceMethod(String traceMethod) {
10720            this.traceMethod = traceMethod;
10721            return this;
10722        }
10723
10724        HandlerParams setTraceCookie(int traceCookie) {
10725            this.traceCookie = traceCookie;
10726            return this;
10727        }
10728
10729        final boolean startCopy() {
10730            boolean res;
10731            try {
10732                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10733
10734                if (++mRetries > MAX_RETRIES) {
10735                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10736                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10737                    handleServiceError();
10738                    return false;
10739                } else {
10740                    handleStartCopy();
10741                    res = true;
10742                }
10743            } catch (RemoteException e) {
10744                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10745                mHandler.sendEmptyMessage(MCS_RECONNECT);
10746                res = false;
10747            }
10748            handleReturnCode();
10749            return res;
10750        }
10751
10752        final void serviceError() {
10753            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10754            handleServiceError();
10755            handleReturnCode();
10756        }
10757
10758        abstract void handleStartCopy() throws RemoteException;
10759        abstract void handleServiceError();
10760        abstract void handleReturnCode();
10761    }
10762
10763    class MeasureParams extends HandlerParams {
10764        private final PackageStats mStats;
10765        private boolean mSuccess;
10766
10767        private final IPackageStatsObserver mObserver;
10768
10769        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10770            super(new UserHandle(stats.userHandle));
10771            mObserver = observer;
10772            mStats = stats;
10773        }
10774
10775        @Override
10776        public String toString() {
10777            return "MeasureParams{"
10778                + Integer.toHexString(System.identityHashCode(this))
10779                + " " + mStats.packageName + "}";
10780        }
10781
10782        @Override
10783        void handleStartCopy() throws RemoteException {
10784            synchronized (mInstallLock) {
10785                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10786            }
10787
10788            if (mSuccess) {
10789                final boolean mounted;
10790                if (Environment.isExternalStorageEmulated()) {
10791                    mounted = true;
10792                } else {
10793                    final String status = Environment.getExternalStorageState();
10794                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10795                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10796                }
10797
10798                if (mounted) {
10799                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10800
10801                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10802                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10803
10804                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10805                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10806
10807                    // Always subtract cache size, since it's a subdirectory
10808                    mStats.externalDataSize -= mStats.externalCacheSize;
10809
10810                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10811                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10812
10813                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10814                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10815                }
10816            }
10817        }
10818
10819        @Override
10820        void handleReturnCode() {
10821            if (mObserver != null) {
10822                try {
10823                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10824                } catch (RemoteException e) {
10825                    Slog.i(TAG, "Observer no longer exists.");
10826                }
10827            }
10828        }
10829
10830        @Override
10831        void handleServiceError() {
10832            Slog.e(TAG, "Could not measure application " + mStats.packageName
10833                            + " external storage");
10834        }
10835    }
10836
10837    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10838            throws RemoteException {
10839        long result = 0;
10840        for (File path : paths) {
10841            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10842        }
10843        return result;
10844    }
10845
10846    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10847        for (File path : paths) {
10848            try {
10849                mcs.clearDirectory(path.getAbsolutePath());
10850            } catch (RemoteException e) {
10851            }
10852        }
10853    }
10854
10855    static class OriginInfo {
10856        /**
10857         * Location where install is coming from, before it has been
10858         * copied/renamed into place. This could be a single monolithic APK
10859         * file, or a cluster directory. This location may be untrusted.
10860         */
10861        final File file;
10862        final String cid;
10863
10864        /**
10865         * Flag indicating that {@link #file} or {@link #cid} has already been
10866         * staged, meaning downstream users don't need to defensively copy the
10867         * contents.
10868         */
10869        final boolean staged;
10870
10871        /**
10872         * Flag indicating that {@link #file} or {@link #cid} is an already
10873         * installed app that is being moved.
10874         */
10875        final boolean existing;
10876
10877        final String resolvedPath;
10878        final File resolvedFile;
10879
10880        static OriginInfo fromNothing() {
10881            return new OriginInfo(null, null, false, false);
10882        }
10883
10884        static OriginInfo fromUntrustedFile(File file) {
10885            return new OriginInfo(file, null, false, false);
10886        }
10887
10888        static OriginInfo fromExistingFile(File file) {
10889            return new OriginInfo(file, null, false, true);
10890        }
10891
10892        static OriginInfo fromStagedFile(File file) {
10893            return new OriginInfo(file, null, true, false);
10894        }
10895
10896        static OriginInfo fromStagedContainer(String cid) {
10897            return new OriginInfo(null, cid, true, false);
10898        }
10899
10900        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10901            this.file = file;
10902            this.cid = cid;
10903            this.staged = staged;
10904            this.existing = existing;
10905
10906            if (cid != null) {
10907                resolvedPath = PackageHelper.getSdDir(cid);
10908                resolvedFile = new File(resolvedPath);
10909            } else if (file != null) {
10910                resolvedPath = file.getAbsolutePath();
10911                resolvedFile = file;
10912            } else {
10913                resolvedPath = null;
10914                resolvedFile = null;
10915            }
10916        }
10917    }
10918
10919    class MoveInfo {
10920        final int moveId;
10921        final String fromUuid;
10922        final String toUuid;
10923        final String packageName;
10924        final String dataAppName;
10925        final int appId;
10926        final String seinfo;
10927
10928        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10929                String dataAppName, int appId, String seinfo) {
10930            this.moveId = moveId;
10931            this.fromUuid = fromUuid;
10932            this.toUuid = toUuid;
10933            this.packageName = packageName;
10934            this.dataAppName = dataAppName;
10935            this.appId = appId;
10936            this.seinfo = seinfo;
10937        }
10938    }
10939
10940    class InstallParams extends HandlerParams {
10941        final OriginInfo origin;
10942        final MoveInfo move;
10943        final IPackageInstallObserver2 observer;
10944        int installFlags;
10945        final String installerPackageName;
10946        final String volumeUuid;
10947        final VerificationParams verificationParams;
10948        private InstallArgs mArgs;
10949        private int mRet;
10950        final String packageAbiOverride;
10951        final String[] grantedRuntimePermissions;
10952
10953        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10954                int installFlags, String installerPackageName, String volumeUuid,
10955                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10956                String[] grantedPermissions) {
10957            super(user);
10958            this.origin = origin;
10959            this.move = move;
10960            this.observer = observer;
10961            this.installFlags = installFlags;
10962            this.installerPackageName = installerPackageName;
10963            this.volumeUuid = volumeUuid;
10964            this.verificationParams = verificationParams;
10965            this.packageAbiOverride = packageAbiOverride;
10966            this.grantedRuntimePermissions = grantedPermissions;
10967        }
10968
10969        @Override
10970        public String toString() {
10971            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10972                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10973        }
10974
10975        public ManifestDigest getManifestDigest() {
10976            if (verificationParams == null) {
10977                return null;
10978            }
10979            return verificationParams.getManifestDigest();
10980        }
10981
10982        private int installLocationPolicy(PackageInfoLite pkgLite) {
10983            String packageName = pkgLite.packageName;
10984            int installLocation = pkgLite.installLocation;
10985            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10986            // reader
10987            synchronized (mPackages) {
10988                PackageParser.Package pkg = mPackages.get(packageName);
10989                if (pkg != null) {
10990                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10991                        // Check for downgrading.
10992                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10993                            try {
10994                                checkDowngrade(pkg, pkgLite);
10995                            } catch (PackageManagerException e) {
10996                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10997                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10998                            }
10999                        }
11000                        // Check for updated system application.
11001                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11002                            if (onSd) {
11003                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11004                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11005                            }
11006                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11007                        } else {
11008                            if (onSd) {
11009                                // Install flag overrides everything.
11010                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11011                            }
11012                            // If current upgrade specifies particular preference
11013                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11014                                // Application explicitly specified internal.
11015                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11016                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11017                                // App explictly prefers external. Let policy decide
11018                            } else {
11019                                // Prefer previous location
11020                                if (isExternal(pkg)) {
11021                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11022                                }
11023                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11024                            }
11025                        }
11026                    } else {
11027                        // Invalid install. Return error code
11028                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11029                    }
11030                }
11031            }
11032            // All the special cases have been taken care of.
11033            // Return result based on recommended install location.
11034            if (onSd) {
11035                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11036            }
11037            return pkgLite.recommendedInstallLocation;
11038        }
11039
11040        /*
11041         * Invoke remote method to get package information and install
11042         * location values. Override install location based on default
11043         * policy if needed and then create install arguments based
11044         * on the install location.
11045         */
11046        public void handleStartCopy() throws RemoteException {
11047            int ret = PackageManager.INSTALL_SUCCEEDED;
11048
11049            // If we're already staged, we've firmly committed to an install location
11050            if (origin.staged) {
11051                if (origin.file != null) {
11052                    installFlags |= PackageManager.INSTALL_INTERNAL;
11053                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11054                } else if (origin.cid != null) {
11055                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11056                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11057                } else {
11058                    throw new IllegalStateException("Invalid stage location");
11059                }
11060            }
11061
11062            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11063            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11064            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11065            PackageInfoLite pkgLite = null;
11066
11067            if (onInt && onSd) {
11068                // Check if both bits are set.
11069                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11070                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11071            } else if (onSd && ephemeral) {
11072                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11073                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11074            } else {
11075                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11076                        packageAbiOverride);
11077
11078                if (DEBUG_EPHEMERAL && ephemeral) {
11079                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11080                }
11081
11082                /*
11083                 * If we have too little free space, try to free cache
11084                 * before giving up.
11085                 */
11086                if (!origin.staged && pkgLite.recommendedInstallLocation
11087                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11088                    // TODO: focus freeing disk space on the target device
11089                    final StorageManager storage = StorageManager.from(mContext);
11090                    final long lowThreshold = storage.getStorageLowBytes(
11091                            Environment.getDataDirectory());
11092
11093                    final long sizeBytes = mContainerService.calculateInstalledSize(
11094                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11095
11096                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11097                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11098                                installFlags, packageAbiOverride);
11099                    }
11100
11101                    /*
11102                     * The cache free must have deleted the file we
11103                     * downloaded to install.
11104                     *
11105                     * TODO: fix the "freeCache" call to not delete
11106                     *       the file we care about.
11107                     */
11108                    if (pkgLite.recommendedInstallLocation
11109                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11110                        pkgLite.recommendedInstallLocation
11111                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11112                    }
11113                }
11114            }
11115
11116            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11117                int loc = pkgLite.recommendedInstallLocation;
11118                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11119                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11120                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11121                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11122                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11123                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11124                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11125                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11126                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11127                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11128                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11129                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11130                } else {
11131                    // Override with defaults if needed.
11132                    loc = installLocationPolicy(pkgLite);
11133                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11134                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11135                    } else if (!onSd && !onInt) {
11136                        // Override install location with flags
11137                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11138                            // Set the flag to install on external media.
11139                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11140                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11141                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11142                            if (DEBUG_EPHEMERAL) {
11143                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11144                            }
11145                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11146                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11147                                    |PackageManager.INSTALL_INTERNAL);
11148                        } else {
11149                            // Make sure the flag for installing on external
11150                            // media is unset
11151                            installFlags |= PackageManager.INSTALL_INTERNAL;
11152                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11153                        }
11154                    }
11155                }
11156            }
11157
11158            final InstallArgs args = createInstallArgs(this);
11159            mArgs = args;
11160
11161            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11162                // TODO: http://b/22976637
11163                // Apps installed for "all" users use the device owner to verify the app
11164                UserHandle verifierUser = getUser();
11165                if (verifierUser == UserHandle.ALL) {
11166                    verifierUser = UserHandle.SYSTEM;
11167                }
11168
11169                /*
11170                 * Determine if we have any installed package verifiers. If we
11171                 * do, then we'll defer to them to verify the packages.
11172                 */
11173                final int requiredUid = mRequiredVerifierPackage == null ? -1
11174                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11175                if (!origin.existing && requiredUid != -1
11176                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11177                    final Intent verification = new Intent(
11178                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11179                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11180                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11181                            PACKAGE_MIME_TYPE);
11182                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11183
11184                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11185                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11186                            verifierUser.getIdentifier());
11187
11188                    if (DEBUG_VERIFY) {
11189                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11190                                + verification.toString() + " with " + pkgLite.verifiers.length
11191                                + " optional verifiers");
11192                    }
11193
11194                    final int verificationId = mPendingVerificationToken++;
11195
11196                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11197
11198                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11199                            installerPackageName);
11200
11201                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11202                            installFlags);
11203
11204                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11205                            pkgLite.packageName);
11206
11207                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11208                            pkgLite.versionCode);
11209
11210                    if (verificationParams != null) {
11211                        if (verificationParams.getVerificationURI() != null) {
11212                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11213                                 verificationParams.getVerificationURI());
11214                        }
11215                        if (verificationParams.getOriginatingURI() != null) {
11216                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11217                                  verificationParams.getOriginatingURI());
11218                        }
11219                        if (verificationParams.getReferrer() != null) {
11220                            verification.putExtra(Intent.EXTRA_REFERRER,
11221                                  verificationParams.getReferrer());
11222                        }
11223                        if (verificationParams.getOriginatingUid() >= 0) {
11224                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11225                                  verificationParams.getOriginatingUid());
11226                        }
11227                        if (verificationParams.getInstallerUid() >= 0) {
11228                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11229                                  verificationParams.getInstallerUid());
11230                        }
11231                    }
11232
11233                    final PackageVerificationState verificationState = new PackageVerificationState(
11234                            requiredUid, args);
11235
11236                    mPendingVerification.append(verificationId, verificationState);
11237
11238                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11239                            receivers, verificationState);
11240
11241                    /*
11242                     * If any sufficient verifiers were listed in the package
11243                     * manifest, attempt to ask them.
11244                     */
11245                    if (sufficientVerifiers != null) {
11246                        final int N = sufficientVerifiers.size();
11247                        if (N == 0) {
11248                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11249                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11250                        } else {
11251                            for (int i = 0; i < N; i++) {
11252                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11253
11254                                final Intent sufficientIntent = new Intent(verification);
11255                                sufficientIntent.setComponent(verifierComponent);
11256                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11257                            }
11258                        }
11259                    }
11260
11261                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11262                            mRequiredVerifierPackage, receivers);
11263                    if (ret == PackageManager.INSTALL_SUCCEEDED
11264                            && mRequiredVerifierPackage != null) {
11265                        Trace.asyncTraceBegin(
11266                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11267                        /*
11268                         * Send the intent to the required verification agent,
11269                         * but only start the verification timeout after the
11270                         * target BroadcastReceivers have run.
11271                         */
11272                        verification.setComponent(requiredVerifierComponent);
11273                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11274                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11275                                new BroadcastReceiver() {
11276                                    @Override
11277                                    public void onReceive(Context context, Intent intent) {
11278                                        final Message msg = mHandler
11279                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11280                                        msg.arg1 = verificationId;
11281                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11282                                    }
11283                                }, null, 0, null, null);
11284
11285                        /*
11286                         * We don't want the copy to proceed until verification
11287                         * succeeds, so null out this field.
11288                         */
11289                        mArgs = null;
11290                    }
11291                } else {
11292                    /*
11293                     * No package verification is enabled, so immediately start
11294                     * the remote call to initiate copy using temporary file.
11295                     */
11296                    ret = args.copyApk(mContainerService, true);
11297                }
11298            }
11299
11300            mRet = ret;
11301        }
11302
11303        @Override
11304        void handleReturnCode() {
11305            // If mArgs is null, then MCS couldn't be reached. When it
11306            // reconnects, it will try again to install. At that point, this
11307            // will succeed.
11308            if (mArgs != null) {
11309                processPendingInstall(mArgs, mRet);
11310            }
11311        }
11312
11313        @Override
11314        void handleServiceError() {
11315            mArgs = createInstallArgs(this);
11316            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11317        }
11318
11319        public boolean isForwardLocked() {
11320            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11321        }
11322    }
11323
11324    /**
11325     * Used during creation of InstallArgs
11326     *
11327     * @param installFlags package installation flags
11328     * @return true if should be installed on external storage
11329     */
11330    private static boolean installOnExternalAsec(int installFlags) {
11331        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11332            return false;
11333        }
11334        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11335            return true;
11336        }
11337        return false;
11338    }
11339
11340    /**
11341     * Used during creation of InstallArgs
11342     *
11343     * @param installFlags package installation flags
11344     * @return true if should be installed as forward locked
11345     */
11346    private static boolean installForwardLocked(int installFlags) {
11347        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11348    }
11349
11350    private InstallArgs createInstallArgs(InstallParams params) {
11351        if (params.move != null) {
11352            return new MoveInstallArgs(params);
11353        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11354            return new AsecInstallArgs(params);
11355        } else {
11356            return new FileInstallArgs(params);
11357        }
11358    }
11359
11360    /**
11361     * Create args that describe an existing installed package. Typically used
11362     * when cleaning up old installs, or used as a move source.
11363     */
11364    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11365            String resourcePath, String[] instructionSets) {
11366        final boolean isInAsec;
11367        if (installOnExternalAsec(installFlags)) {
11368            /* Apps on SD card are always in ASEC containers. */
11369            isInAsec = true;
11370        } else if (installForwardLocked(installFlags)
11371                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11372            /*
11373             * Forward-locked apps are only in ASEC containers if they're the
11374             * new style
11375             */
11376            isInAsec = true;
11377        } else {
11378            isInAsec = false;
11379        }
11380
11381        if (isInAsec) {
11382            return new AsecInstallArgs(codePath, instructionSets,
11383                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11384        } else {
11385            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11386        }
11387    }
11388
11389    static abstract class InstallArgs {
11390        /** @see InstallParams#origin */
11391        final OriginInfo origin;
11392        /** @see InstallParams#move */
11393        final MoveInfo move;
11394
11395        final IPackageInstallObserver2 observer;
11396        // Always refers to PackageManager flags only
11397        final int installFlags;
11398        final String installerPackageName;
11399        final String volumeUuid;
11400        final ManifestDigest manifestDigest;
11401        final UserHandle user;
11402        final String abiOverride;
11403        final String[] installGrantPermissions;
11404        /** If non-null, drop an async trace when the install completes */
11405        final String traceMethod;
11406        final int traceCookie;
11407
11408        // The list of instruction sets supported by this app. This is currently
11409        // only used during the rmdex() phase to clean up resources. We can get rid of this
11410        // if we move dex files under the common app path.
11411        /* nullable */ String[] instructionSets;
11412
11413        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11414                int installFlags, String installerPackageName, String volumeUuid,
11415                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11416                String abiOverride, String[] installGrantPermissions,
11417                String traceMethod, int traceCookie) {
11418            this.origin = origin;
11419            this.move = move;
11420            this.installFlags = installFlags;
11421            this.observer = observer;
11422            this.installerPackageName = installerPackageName;
11423            this.volumeUuid = volumeUuid;
11424            this.manifestDigest = manifestDigest;
11425            this.user = user;
11426            this.instructionSets = instructionSets;
11427            this.abiOverride = abiOverride;
11428            this.installGrantPermissions = installGrantPermissions;
11429            this.traceMethod = traceMethod;
11430            this.traceCookie = traceCookie;
11431        }
11432
11433        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11434        abstract int doPreInstall(int status);
11435
11436        /**
11437         * Rename package into final resting place. All paths on the given
11438         * scanned package should be updated to reflect the rename.
11439         */
11440        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11441        abstract int doPostInstall(int status, int uid);
11442
11443        /** @see PackageSettingBase#codePathString */
11444        abstract String getCodePath();
11445        /** @see PackageSettingBase#resourcePathString */
11446        abstract String getResourcePath();
11447
11448        // Need installer lock especially for dex file removal.
11449        abstract void cleanUpResourcesLI();
11450        abstract boolean doPostDeleteLI(boolean delete);
11451
11452        /**
11453         * Called before the source arguments are copied. This is used mostly
11454         * for MoveParams when it needs to read the source file to put it in the
11455         * destination.
11456         */
11457        int doPreCopy() {
11458            return PackageManager.INSTALL_SUCCEEDED;
11459        }
11460
11461        /**
11462         * Called after the source arguments are copied. This is used mostly for
11463         * MoveParams when it needs to read the source file to put it in the
11464         * destination.
11465         *
11466         * @return
11467         */
11468        int doPostCopy(int uid) {
11469            return PackageManager.INSTALL_SUCCEEDED;
11470        }
11471
11472        protected boolean isFwdLocked() {
11473            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11474        }
11475
11476        protected boolean isExternalAsec() {
11477            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11478        }
11479
11480        protected boolean isEphemeral() {
11481            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11482        }
11483
11484        UserHandle getUser() {
11485            return user;
11486        }
11487    }
11488
11489    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11490        if (!allCodePaths.isEmpty()) {
11491            if (instructionSets == null) {
11492                throw new IllegalStateException("instructionSet == null");
11493            }
11494            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11495            for (String codePath : allCodePaths) {
11496                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11497                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11498                    if (retCode < 0) {
11499                        Slog.w(TAG, "Couldn't remove dex file for package: "
11500                                + " at location " + codePath + ", retcode=" + retCode);
11501                        // we don't consider this to be a failure of the core package deletion
11502                    }
11503                }
11504            }
11505        }
11506    }
11507
11508    /**
11509     * Logic to handle installation of non-ASEC applications, including copying
11510     * and renaming logic.
11511     */
11512    class FileInstallArgs extends InstallArgs {
11513        private File codeFile;
11514        private File resourceFile;
11515
11516        // Example topology:
11517        // /data/app/com.example/base.apk
11518        // /data/app/com.example/split_foo.apk
11519        // /data/app/com.example/lib/arm/libfoo.so
11520        // /data/app/com.example/lib/arm64/libfoo.so
11521        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11522
11523        /** New install */
11524        FileInstallArgs(InstallParams params) {
11525            super(params.origin, params.move, params.observer, params.installFlags,
11526                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11527                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11528                    params.grantedRuntimePermissions,
11529                    params.traceMethod, params.traceCookie);
11530            if (isFwdLocked()) {
11531                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11532            }
11533        }
11534
11535        /** Existing install */
11536        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11537            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11538                    null, null, null, 0);
11539            this.codeFile = (codePath != null) ? new File(codePath) : null;
11540            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11541        }
11542
11543        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11544            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11545            try {
11546                return doCopyApk(imcs, temp);
11547            } finally {
11548                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11549            }
11550        }
11551
11552        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11553            if (origin.staged) {
11554                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11555                codeFile = origin.file;
11556                resourceFile = origin.file;
11557                return PackageManager.INSTALL_SUCCEEDED;
11558            }
11559
11560            try {
11561                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11562                final File tempDir =
11563                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11564                codeFile = tempDir;
11565                resourceFile = tempDir;
11566            } catch (IOException e) {
11567                Slog.w(TAG, "Failed to create copy file: " + e);
11568                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11569            }
11570
11571            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11572                @Override
11573                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11574                    if (!FileUtils.isValidExtFilename(name)) {
11575                        throw new IllegalArgumentException("Invalid filename: " + name);
11576                    }
11577                    try {
11578                        final File file = new File(codeFile, name);
11579                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11580                                O_RDWR | O_CREAT, 0644);
11581                        Os.chmod(file.getAbsolutePath(), 0644);
11582                        return new ParcelFileDescriptor(fd);
11583                    } catch (ErrnoException e) {
11584                        throw new RemoteException("Failed to open: " + e.getMessage());
11585                    }
11586                }
11587            };
11588
11589            int ret = PackageManager.INSTALL_SUCCEEDED;
11590            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11591            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11592                Slog.e(TAG, "Failed to copy package");
11593                return ret;
11594            }
11595
11596            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11597            NativeLibraryHelper.Handle handle = null;
11598            try {
11599                handle = NativeLibraryHelper.Handle.create(codeFile);
11600                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11601                        abiOverride);
11602            } catch (IOException e) {
11603                Slog.e(TAG, "Copying native libraries failed", e);
11604                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11605            } finally {
11606                IoUtils.closeQuietly(handle);
11607            }
11608
11609            return ret;
11610        }
11611
11612        int doPreInstall(int status) {
11613            if (status != PackageManager.INSTALL_SUCCEEDED) {
11614                cleanUp();
11615            }
11616            return status;
11617        }
11618
11619        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11620            if (status != PackageManager.INSTALL_SUCCEEDED) {
11621                cleanUp();
11622                return false;
11623            }
11624
11625            final File targetDir = codeFile.getParentFile();
11626            final File beforeCodeFile = codeFile;
11627            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11628
11629            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11630            try {
11631                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11632            } catch (ErrnoException e) {
11633                Slog.w(TAG, "Failed to rename", e);
11634                return false;
11635            }
11636
11637            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11638                Slog.w(TAG, "Failed to restorecon");
11639                return false;
11640            }
11641
11642            // Reflect the rename internally
11643            codeFile = afterCodeFile;
11644            resourceFile = afterCodeFile;
11645
11646            // Reflect the rename in scanned details
11647            pkg.codePath = afterCodeFile.getAbsolutePath();
11648            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11649                    pkg.baseCodePath);
11650            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11651                    pkg.splitCodePaths);
11652
11653            // Reflect the rename in app info
11654            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11655            pkg.applicationInfo.setCodePath(pkg.codePath);
11656            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11657            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11658            pkg.applicationInfo.setResourcePath(pkg.codePath);
11659            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11660            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11661
11662            return true;
11663        }
11664
11665        int doPostInstall(int status, int uid) {
11666            if (status != PackageManager.INSTALL_SUCCEEDED) {
11667                cleanUp();
11668            }
11669            return status;
11670        }
11671
11672        @Override
11673        String getCodePath() {
11674            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11675        }
11676
11677        @Override
11678        String getResourcePath() {
11679            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11680        }
11681
11682        private boolean cleanUp() {
11683            if (codeFile == null || !codeFile.exists()) {
11684                return false;
11685            }
11686
11687            if (codeFile.isDirectory()) {
11688                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11689            } else {
11690                codeFile.delete();
11691            }
11692
11693            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11694                resourceFile.delete();
11695            }
11696
11697            return true;
11698        }
11699
11700        void cleanUpResourcesLI() {
11701            // Try enumerating all code paths before deleting
11702            List<String> allCodePaths = Collections.EMPTY_LIST;
11703            if (codeFile != null && codeFile.exists()) {
11704                try {
11705                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11706                    allCodePaths = pkg.getAllCodePaths();
11707                } catch (PackageParserException e) {
11708                    // Ignored; we tried our best
11709                }
11710            }
11711
11712            cleanUp();
11713            removeDexFiles(allCodePaths, instructionSets);
11714        }
11715
11716        boolean doPostDeleteLI(boolean delete) {
11717            // XXX err, shouldn't we respect the delete flag?
11718            cleanUpResourcesLI();
11719            return true;
11720        }
11721    }
11722
11723    private boolean isAsecExternal(String cid) {
11724        final String asecPath = PackageHelper.getSdFilesystem(cid);
11725        return !asecPath.startsWith(mAsecInternalPath);
11726    }
11727
11728    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11729            PackageManagerException {
11730        if (copyRet < 0) {
11731            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11732                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11733                throw new PackageManagerException(copyRet, message);
11734            }
11735        }
11736    }
11737
11738    /**
11739     * Extract the MountService "container ID" from the full code path of an
11740     * .apk.
11741     */
11742    static String cidFromCodePath(String fullCodePath) {
11743        int eidx = fullCodePath.lastIndexOf("/");
11744        String subStr1 = fullCodePath.substring(0, eidx);
11745        int sidx = subStr1.lastIndexOf("/");
11746        return subStr1.substring(sidx+1, eidx);
11747    }
11748
11749    /**
11750     * Logic to handle installation of ASEC applications, including copying and
11751     * renaming logic.
11752     */
11753    class AsecInstallArgs extends InstallArgs {
11754        static final String RES_FILE_NAME = "pkg.apk";
11755        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11756
11757        String cid;
11758        String packagePath;
11759        String resourcePath;
11760
11761        /** New install */
11762        AsecInstallArgs(InstallParams params) {
11763            super(params.origin, params.move, params.observer, params.installFlags,
11764                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11765                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11766                    params.grantedRuntimePermissions,
11767                    params.traceMethod, params.traceCookie);
11768        }
11769
11770        /** Existing install */
11771        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11772                        boolean isExternal, boolean isForwardLocked) {
11773            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11774                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11775                    instructionSets, null, null, null, 0);
11776            // Hackily pretend we're still looking at a full code path
11777            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11778                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11779            }
11780
11781            // Extract cid from fullCodePath
11782            int eidx = fullCodePath.lastIndexOf("/");
11783            String subStr1 = fullCodePath.substring(0, eidx);
11784            int sidx = subStr1.lastIndexOf("/");
11785            cid = subStr1.substring(sidx+1, eidx);
11786            setMountPath(subStr1);
11787        }
11788
11789        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11790            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11791                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11792                    instructionSets, null, null, null, 0);
11793            this.cid = cid;
11794            setMountPath(PackageHelper.getSdDir(cid));
11795        }
11796
11797        void createCopyFile() {
11798            cid = mInstallerService.allocateExternalStageCidLegacy();
11799        }
11800
11801        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11802            if (origin.staged && origin.cid != null) {
11803                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11804                cid = origin.cid;
11805                setMountPath(PackageHelper.getSdDir(cid));
11806                return PackageManager.INSTALL_SUCCEEDED;
11807            }
11808
11809            if (temp) {
11810                createCopyFile();
11811            } else {
11812                /*
11813                 * Pre-emptively destroy the container since it's destroyed if
11814                 * copying fails due to it existing anyway.
11815                 */
11816                PackageHelper.destroySdDir(cid);
11817            }
11818
11819            final String newMountPath = imcs.copyPackageToContainer(
11820                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11821                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11822
11823            if (newMountPath != null) {
11824                setMountPath(newMountPath);
11825                return PackageManager.INSTALL_SUCCEEDED;
11826            } else {
11827                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11828            }
11829        }
11830
11831        @Override
11832        String getCodePath() {
11833            return packagePath;
11834        }
11835
11836        @Override
11837        String getResourcePath() {
11838            return resourcePath;
11839        }
11840
11841        int doPreInstall(int status) {
11842            if (status != PackageManager.INSTALL_SUCCEEDED) {
11843                // Destroy container
11844                PackageHelper.destroySdDir(cid);
11845            } else {
11846                boolean mounted = PackageHelper.isContainerMounted(cid);
11847                if (!mounted) {
11848                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11849                            Process.SYSTEM_UID);
11850                    if (newMountPath != null) {
11851                        setMountPath(newMountPath);
11852                    } else {
11853                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11854                    }
11855                }
11856            }
11857            return status;
11858        }
11859
11860        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11861            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11862            String newMountPath = null;
11863            if (PackageHelper.isContainerMounted(cid)) {
11864                // Unmount the container
11865                if (!PackageHelper.unMountSdDir(cid)) {
11866                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11867                    return false;
11868                }
11869            }
11870            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11871                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11872                        " which might be stale. Will try to clean up.");
11873                // Clean up the stale container and proceed to recreate.
11874                if (!PackageHelper.destroySdDir(newCacheId)) {
11875                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11876                    return false;
11877                }
11878                // Successfully cleaned up stale container. Try to rename again.
11879                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11880                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11881                            + " inspite of cleaning it up.");
11882                    return false;
11883                }
11884            }
11885            if (!PackageHelper.isContainerMounted(newCacheId)) {
11886                Slog.w(TAG, "Mounting container " + newCacheId);
11887                newMountPath = PackageHelper.mountSdDir(newCacheId,
11888                        getEncryptKey(), Process.SYSTEM_UID);
11889            } else {
11890                newMountPath = PackageHelper.getSdDir(newCacheId);
11891            }
11892            if (newMountPath == null) {
11893                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11894                return false;
11895            }
11896            Log.i(TAG, "Succesfully renamed " + cid +
11897                    " to " + newCacheId +
11898                    " at new path: " + newMountPath);
11899            cid = newCacheId;
11900
11901            final File beforeCodeFile = new File(packagePath);
11902            setMountPath(newMountPath);
11903            final File afterCodeFile = new File(packagePath);
11904
11905            // Reflect the rename in scanned details
11906            pkg.codePath = afterCodeFile.getAbsolutePath();
11907            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11908                    pkg.baseCodePath);
11909            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11910                    pkg.splitCodePaths);
11911
11912            // Reflect the rename in app info
11913            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11914            pkg.applicationInfo.setCodePath(pkg.codePath);
11915            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11916            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11917            pkg.applicationInfo.setResourcePath(pkg.codePath);
11918            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11919            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11920
11921            return true;
11922        }
11923
11924        private void setMountPath(String mountPath) {
11925            final File mountFile = new File(mountPath);
11926
11927            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11928            if (monolithicFile.exists()) {
11929                packagePath = monolithicFile.getAbsolutePath();
11930                if (isFwdLocked()) {
11931                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11932                } else {
11933                    resourcePath = packagePath;
11934                }
11935            } else {
11936                packagePath = mountFile.getAbsolutePath();
11937                resourcePath = packagePath;
11938            }
11939        }
11940
11941        int doPostInstall(int status, int uid) {
11942            if (status != PackageManager.INSTALL_SUCCEEDED) {
11943                cleanUp();
11944            } else {
11945                final int groupOwner;
11946                final String protectedFile;
11947                if (isFwdLocked()) {
11948                    groupOwner = UserHandle.getSharedAppGid(uid);
11949                    protectedFile = RES_FILE_NAME;
11950                } else {
11951                    groupOwner = -1;
11952                    protectedFile = null;
11953                }
11954
11955                if (uid < Process.FIRST_APPLICATION_UID
11956                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11957                    Slog.e(TAG, "Failed to finalize " + cid);
11958                    PackageHelper.destroySdDir(cid);
11959                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11960                }
11961
11962                boolean mounted = PackageHelper.isContainerMounted(cid);
11963                if (!mounted) {
11964                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11965                }
11966            }
11967            return status;
11968        }
11969
11970        private void cleanUp() {
11971            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11972
11973            // Destroy secure container
11974            PackageHelper.destroySdDir(cid);
11975        }
11976
11977        private List<String> getAllCodePaths() {
11978            final File codeFile = new File(getCodePath());
11979            if (codeFile != null && codeFile.exists()) {
11980                try {
11981                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11982                    return pkg.getAllCodePaths();
11983                } catch (PackageParserException e) {
11984                    // Ignored; we tried our best
11985                }
11986            }
11987            return Collections.EMPTY_LIST;
11988        }
11989
11990        void cleanUpResourcesLI() {
11991            // Enumerate all code paths before deleting
11992            cleanUpResourcesLI(getAllCodePaths());
11993        }
11994
11995        private void cleanUpResourcesLI(List<String> allCodePaths) {
11996            cleanUp();
11997            removeDexFiles(allCodePaths, instructionSets);
11998        }
11999
12000        String getPackageName() {
12001            return getAsecPackageName(cid);
12002        }
12003
12004        boolean doPostDeleteLI(boolean delete) {
12005            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12006            final List<String> allCodePaths = getAllCodePaths();
12007            boolean mounted = PackageHelper.isContainerMounted(cid);
12008            if (mounted) {
12009                // Unmount first
12010                if (PackageHelper.unMountSdDir(cid)) {
12011                    mounted = false;
12012                }
12013            }
12014            if (!mounted && delete) {
12015                cleanUpResourcesLI(allCodePaths);
12016            }
12017            return !mounted;
12018        }
12019
12020        @Override
12021        int doPreCopy() {
12022            if (isFwdLocked()) {
12023                if (!PackageHelper.fixSdPermissions(cid,
12024                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12025                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12026                }
12027            }
12028
12029            return PackageManager.INSTALL_SUCCEEDED;
12030        }
12031
12032        @Override
12033        int doPostCopy(int uid) {
12034            if (isFwdLocked()) {
12035                if (uid < Process.FIRST_APPLICATION_UID
12036                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12037                                RES_FILE_NAME)) {
12038                    Slog.e(TAG, "Failed to finalize " + cid);
12039                    PackageHelper.destroySdDir(cid);
12040                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12041                }
12042            }
12043
12044            return PackageManager.INSTALL_SUCCEEDED;
12045        }
12046    }
12047
12048    /**
12049     * Logic to handle movement of existing installed applications.
12050     */
12051    class MoveInstallArgs extends InstallArgs {
12052        private File codeFile;
12053        private File resourceFile;
12054
12055        /** New install */
12056        MoveInstallArgs(InstallParams params) {
12057            super(params.origin, params.move, params.observer, params.installFlags,
12058                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
12059                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12060                    params.grantedRuntimePermissions,
12061                    params.traceMethod, params.traceCookie);
12062        }
12063
12064        int copyApk(IMediaContainerService imcs, boolean temp) {
12065            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12066                    + move.fromUuid + " to " + move.toUuid);
12067            synchronized (mInstaller) {
12068                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12069                        move.dataAppName, move.appId, move.seinfo) != 0) {
12070                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12071                }
12072            }
12073
12074            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12075            resourceFile = codeFile;
12076            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12077
12078            return PackageManager.INSTALL_SUCCEEDED;
12079        }
12080
12081        int doPreInstall(int status) {
12082            if (status != PackageManager.INSTALL_SUCCEEDED) {
12083                cleanUp(move.toUuid);
12084            }
12085            return status;
12086        }
12087
12088        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12089            if (status != PackageManager.INSTALL_SUCCEEDED) {
12090                cleanUp(move.toUuid);
12091                return false;
12092            }
12093
12094            // Reflect the move in app info
12095            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12096            pkg.applicationInfo.setCodePath(pkg.codePath);
12097            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12098            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12099            pkg.applicationInfo.setResourcePath(pkg.codePath);
12100            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12101            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12102
12103            return true;
12104        }
12105
12106        int doPostInstall(int status, int uid) {
12107            if (status == PackageManager.INSTALL_SUCCEEDED) {
12108                cleanUp(move.fromUuid);
12109            } else {
12110                cleanUp(move.toUuid);
12111            }
12112            return status;
12113        }
12114
12115        @Override
12116        String getCodePath() {
12117            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12118        }
12119
12120        @Override
12121        String getResourcePath() {
12122            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12123        }
12124
12125        private boolean cleanUp(String volumeUuid) {
12126            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12127                    move.dataAppName);
12128            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12129            synchronized (mInstallLock) {
12130                // Clean up both app data and code
12131                removeDataDirsLI(volumeUuid, move.packageName);
12132                if (codeFile.isDirectory()) {
12133                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12134                } else {
12135                    codeFile.delete();
12136                }
12137            }
12138            return true;
12139        }
12140
12141        void cleanUpResourcesLI() {
12142            throw new UnsupportedOperationException();
12143        }
12144
12145        boolean doPostDeleteLI(boolean delete) {
12146            throw new UnsupportedOperationException();
12147        }
12148    }
12149
12150    static String getAsecPackageName(String packageCid) {
12151        int idx = packageCid.lastIndexOf("-");
12152        if (idx == -1) {
12153            return packageCid;
12154        }
12155        return packageCid.substring(0, idx);
12156    }
12157
12158    // Utility method used to create code paths based on package name and available index.
12159    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12160        String idxStr = "";
12161        int idx = 1;
12162        // Fall back to default value of idx=1 if prefix is not
12163        // part of oldCodePath
12164        if (oldCodePath != null) {
12165            String subStr = oldCodePath;
12166            // Drop the suffix right away
12167            if (suffix != null && subStr.endsWith(suffix)) {
12168                subStr = subStr.substring(0, subStr.length() - suffix.length());
12169            }
12170            // If oldCodePath already contains prefix find out the
12171            // ending index to either increment or decrement.
12172            int sidx = subStr.lastIndexOf(prefix);
12173            if (sidx != -1) {
12174                subStr = subStr.substring(sidx + prefix.length());
12175                if (subStr != null) {
12176                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12177                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12178                    }
12179                    try {
12180                        idx = Integer.parseInt(subStr);
12181                        if (idx <= 1) {
12182                            idx++;
12183                        } else {
12184                            idx--;
12185                        }
12186                    } catch(NumberFormatException e) {
12187                    }
12188                }
12189            }
12190        }
12191        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12192        return prefix + idxStr;
12193    }
12194
12195    private File getNextCodePath(File targetDir, String packageName) {
12196        int suffix = 1;
12197        File result;
12198        do {
12199            result = new File(targetDir, packageName + "-" + suffix);
12200            suffix++;
12201        } while (result.exists());
12202        return result;
12203    }
12204
12205    // Utility method that returns the relative package path with respect
12206    // to the installation directory. Like say for /data/data/com.test-1.apk
12207    // string com.test-1 is returned.
12208    static String deriveCodePathName(String codePath) {
12209        if (codePath == null) {
12210            return null;
12211        }
12212        final File codeFile = new File(codePath);
12213        final String name = codeFile.getName();
12214        if (codeFile.isDirectory()) {
12215            return name;
12216        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12217            final int lastDot = name.lastIndexOf('.');
12218            return name.substring(0, lastDot);
12219        } else {
12220            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12221            return null;
12222        }
12223    }
12224
12225    class PackageInstalledInfo {
12226        String name;
12227        int uid;
12228        // The set of users that originally had this package installed.
12229        int[] origUsers;
12230        // The set of users that now have this package installed.
12231        int[] newUsers;
12232        PackageParser.Package pkg;
12233        int returnCode;
12234        String returnMsg;
12235        PackageRemovedInfo removedInfo;
12236
12237        public void setError(int code, String msg) {
12238            returnCode = code;
12239            returnMsg = msg;
12240            Slog.w(TAG, msg);
12241        }
12242
12243        public void setError(String msg, PackageParserException e) {
12244            returnCode = e.error;
12245            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12246            Slog.w(TAG, msg, e);
12247        }
12248
12249        public void setError(String msg, PackageManagerException e) {
12250            returnCode = e.error;
12251            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12252            Slog.w(TAG, msg, e);
12253        }
12254
12255        // In some error cases we want to convey more info back to the observer
12256        String origPackage;
12257        String origPermission;
12258    }
12259
12260    /*
12261     * Install a non-existing package.
12262     */
12263    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12264            UserHandle user, String installerPackageName, String volumeUuid,
12265            PackageInstalledInfo res) {
12266        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12267
12268        // Remember this for later, in case we need to rollback this install
12269        String pkgName = pkg.packageName;
12270
12271        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12272        // TODO: b/23350563
12273        final boolean dataDirExists = Environment
12274                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12275
12276        synchronized(mPackages) {
12277            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12278                // A package with the same name is already installed, though
12279                // it has been renamed to an older name.  The package we
12280                // are trying to install should be installed as an update to
12281                // the existing one, but that has not been requested, so bail.
12282                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12283                        + " without first uninstalling package running as "
12284                        + mSettings.mRenamedPackages.get(pkgName));
12285                return;
12286            }
12287            if (mPackages.containsKey(pkgName)) {
12288                // Don't allow installation over an existing package with the same name.
12289                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12290                        + " without first uninstalling.");
12291                return;
12292            }
12293        }
12294
12295        try {
12296            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12297                    System.currentTimeMillis(), user);
12298
12299            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12300            // delete the partially installed application. the data directory will have to be
12301            // restored if it was already existing
12302            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12303                // remove package from internal structures.  Note that we want deletePackageX to
12304                // delete the package data and cache directories that it created in
12305                // scanPackageLocked, unless those directories existed before we even tried to
12306                // install.
12307                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12308                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12309                                res.removedInfo, true);
12310            }
12311
12312        } catch (PackageManagerException e) {
12313            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12314        }
12315
12316        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12317    }
12318
12319    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12320        // Can't rotate keys during boot or if sharedUser.
12321        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12322                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12323            return false;
12324        }
12325        // app is using upgradeKeySets; make sure all are valid
12326        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12327        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12328        for (int i = 0; i < upgradeKeySets.length; i++) {
12329            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12330                Slog.wtf(TAG, "Package "
12331                         + (oldPs.name != null ? oldPs.name : "<null>")
12332                         + " contains upgrade-key-set reference to unknown key-set: "
12333                         + upgradeKeySets[i]
12334                         + " reverting to signatures check.");
12335                return false;
12336            }
12337        }
12338        return true;
12339    }
12340
12341    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12342        // Upgrade keysets are being used.  Determine if new package has a superset of the
12343        // required keys.
12344        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12345        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12346        for (int i = 0; i < upgradeKeySets.length; i++) {
12347            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12348            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12349                return true;
12350            }
12351        }
12352        return false;
12353    }
12354
12355    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12356            UserHandle user, String installerPackageName, String volumeUuid,
12357            PackageInstalledInfo res) {
12358        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12359
12360        final PackageParser.Package oldPackage;
12361        final String pkgName = pkg.packageName;
12362        final int[] allUsers;
12363        final boolean[] perUserInstalled;
12364
12365        // First find the old package info and check signatures
12366        synchronized(mPackages) {
12367            oldPackage = mPackages.get(pkgName);
12368            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12369            if (isEphemeral && !oldIsEphemeral) {
12370                // can't downgrade from full to ephemeral
12371                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12372                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12373                return;
12374            }
12375            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12376            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12377            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12378                if(!checkUpgradeKeySetLP(ps, pkg)) {
12379                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12380                            "New package not signed by keys specified by upgrade-keysets: "
12381                            + pkgName);
12382                    return;
12383                }
12384            } else {
12385                // default to original signature matching
12386                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12387                    != PackageManager.SIGNATURE_MATCH) {
12388                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12389                            "New package has a different signature: " + pkgName);
12390                    return;
12391                }
12392            }
12393
12394            // In case of rollback, remember per-user/profile install state
12395            allUsers = sUserManager.getUserIds();
12396            perUserInstalled = new boolean[allUsers.length];
12397            for (int i = 0; i < allUsers.length; i++) {
12398                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12399            }
12400        }
12401
12402        boolean sysPkg = (isSystemApp(oldPackage));
12403        if (sysPkg) {
12404            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12405                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12406        } else {
12407            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12408                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12409        }
12410    }
12411
12412    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12413            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12414            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12415            String volumeUuid, PackageInstalledInfo res) {
12416        String pkgName = deletedPackage.packageName;
12417        boolean deletedPkg = true;
12418        boolean updatedSettings = false;
12419
12420        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12421                + deletedPackage);
12422        long origUpdateTime;
12423        if (pkg.mExtras != null) {
12424            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12425        } else {
12426            origUpdateTime = 0;
12427        }
12428
12429        // First delete the existing package while retaining the data directory
12430        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12431                res.removedInfo, true)) {
12432            // If the existing package wasn't successfully deleted
12433            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12434            deletedPkg = false;
12435        } else {
12436            // Successfully deleted the old package; proceed with replace.
12437
12438            // If deleted package lived in a container, give users a chance to
12439            // relinquish resources before killing.
12440            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12441                if (DEBUG_INSTALL) {
12442                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12443                }
12444                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12445                final ArrayList<String> pkgList = new ArrayList<String>(1);
12446                pkgList.add(deletedPackage.applicationInfo.packageName);
12447                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12448            }
12449
12450            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12451            try {
12452                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12453                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12454                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12455                        perUserInstalled, res, user);
12456                updatedSettings = true;
12457            } catch (PackageManagerException e) {
12458                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12459            }
12460        }
12461
12462        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12463            // remove package from internal structures.  Note that we want deletePackageX to
12464            // delete the package data and cache directories that it created in
12465            // scanPackageLocked, unless those directories existed before we even tried to
12466            // install.
12467            if(updatedSettings) {
12468                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12469                deletePackageLI(
12470                        pkgName, null, true, allUsers, perUserInstalled,
12471                        PackageManager.DELETE_KEEP_DATA,
12472                                res.removedInfo, true);
12473            }
12474            // Since we failed to install the new package we need to restore the old
12475            // package that we deleted.
12476            if (deletedPkg) {
12477                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12478                File restoreFile = new File(deletedPackage.codePath);
12479                // Parse old package
12480                boolean oldExternal = isExternal(deletedPackage);
12481                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12482                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12483                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12484                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12485                try {
12486                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12487                            null);
12488                } catch (PackageManagerException e) {
12489                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12490                            + e.getMessage());
12491                    return;
12492                }
12493                // Restore of old package succeeded. Update permissions.
12494                // writer
12495                synchronized (mPackages) {
12496                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12497                            UPDATE_PERMISSIONS_ALL);
12498                    // can downgrade to reader
12499                    mSettings.writeLPr();
12500                }
12501                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12502            }
12503        }
12504    }
12505
12506    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12507            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12508            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12509            String volumeUuid, PackageInstalledInfo res) {
12510        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12511                + ", old=" + deletedPackage);
12512        boolean disabledSystem = false;
12513        boolean updatedSettings = false;
12514        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12515        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12516                != 0) {
12517            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12518        }
12519        String packageName = deletedPackage.packageName;
12520        if (packageName == null) {
12521            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12522                    "Attempt to delete null packageName.");
12523            return;
12524        }
12525        PackageParser.Package oldPkg;
12526        PackageSetting oldPkgSetting;
12527        // reader
12528        synchronized (mPackages) {
12529            oldPkg = mPackages.get(packageName);
12530            oldPkgSetting = mSettings.mPackages.get(packageName);
12531            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12532                    (oldPkgSetting == null)) {
12533                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12534                        "Couldn't find package:" + packageName + " information");
12535                return;
12536            }
12537        }
12538
12539        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12540
12541        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12542        res.removedInfo.removedPackage = packageName;
12543        // Remove existing system package
12544        removePackageLI(oldPkgSetting, true);
12545        // writer
12546        synchronized (mPackages) {
12547            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12548            if (!disabledSystem && deletedPackage != null) {
12549                // We didn't need to disable the .apk as a current system package,
12550                // which means we are replacing another update that is already
12551                // installed.  We need to make sure to delete the older one's .apk.
12552                res.removedInfo.args = createInstallArgsForExisting(0,
12553                        deletedPackage.applicationInfo.getCodePath(),
12554                        deletedPackage.applicationInfo.getResourcePath(),
12555                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12556            } else {
12557                res.removedInfo.args = null;
12558            }
12559        }
12560
12561        // Successfully disabled the old package. Now proceed with re-installation
12562        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12563
12564        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12565        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12566
12567        PackageParser.Package newPackage = null;
12568        try {
12569            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12570            if (newPackage.mExtras != null) {
12571                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12572                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12573                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12574
12575                // is the update attempting to change shared user? that isn't going to work...
12576                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12577                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12578                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12579                            + " to " + newPkgSetting.sharedUser);
12580                    updatedSettings = true;
12581                }
12582            }
12583
12584            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12585                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12586                        perUserInstalled, res, user);
12587                updatedSettings = true;
12588            }
12589
12590        } catch (PackageManagerException e) {
12591            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12592        }
12593
12594        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12595            // Re installation failed. Restore old information
12596            // Remove new pkg information
12597            if (newPackage != null) {
12598                removeInstalledPackageLI(newPackage, true);
12599            }
12600            // Add back the old system package
12601            try {
12602                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12603            } catch (PackageManagerException e) {
12604                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12605            }
12606            // Restore the old system information in Settings
12607            synchronized (mPackages) {
12608                if (disabledSystem) {
12609                    mSettings.enableSystemPackageLPw(packageName);
12610                }
12611                if (updatedSettings) {
12612                    mSettings.setInstallerPackageName(packageName,
12613                            oldPkgSetting.installerPackageName);
12614                }
12615                mSettings.writeLPr();
12616            }
12617        }
12618    }
12619
12620    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12621        // Collect all used permissions in the UID
12622        ArraySet<String> usedPermissions = new ArraySet<>();
12623        final int packageCount = su.packages.size();
12624        for (int i = 0; i < packageCount; i++) {
12625            PackageSetting ps = su.packages.valueAt(i);
12626            if (ps.pkg == null) {
12627                continue;
12628            }
12629            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12630            for (int j = 0; j < requestedPermCount; j++) {
12631                String permission = ps.pkg.requestedPermissions.get(j);
12632                BasePermission bp = mSettings.mPermissions.get(permission);
12633                if (bp != null) {
12634                    usedPermissions.add(permission);
12635                }
12636            }
12637        }
12638
12639        PermissionsState permissionsState = su.getPermissionsState();
12640        // Prune install permissions
12641        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12642        final int installPermCount = installPermStates.size();
12643        for (int i = installPermCount - 1; i >= 0;  i--) {
12644            PermissionState permissionState = installPermStates.get(i);
12645            if (!usedPermissions.contains(permissionState.getName())) {
12646                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12647                if (bp != null) {
12648                    permissionsState.revokeInstallPermission(bp);
12649                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12650                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12651                }
12652            }
12653        }
12654
12655        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12656
12657        // Prune runtime permissions
12658        for (int userId : allUserIds) {
12659            List<PermissionState> runtimePermStates = permissionsState
12660                    .getRuntimePermissionStates(userId);
12661            final int runtimePermCount = runtimePermStates.size();
12662            for (int i = runtimePermCount - 1; i >= 0; i--) {
12663                PermissionState permissionState = runtimePermStates.get(i);
12664                if (!usedPermissions.contains(permissionState.getName())) {
12665                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12666                    if (bp != null) {
12667                        permissionsState.revokeRuntimePermission(bp, userId);
12668                        permissionsState.updatePermissionFlags(bp, userId,
12669                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12670                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12671                                runtimePermissionChangedUserIds, userId);
12672                    }
12673                }
12674            }
12675        }
12676
12677        return runtimePermissionChangedUserIds;
12678    }
12679
12680    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12681            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12682            UserHandle user) {
12683        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12684
12685        String pkgName = newPackage.packageName;
12686        synchronized (mPackages) {
12687            //write settings. the installStatus will be incomplete at this stage.
12688            //note that the new package setting would have already been
12689            //added to mPackages. It hasn't been persisted yet.
12690            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12691            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12692            mSettings.writeLPr();
12693            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12694        }
12695
12696        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12697        synchronized (mPackages) {
12698            updatePermissionsLPw(newPackage.packageName, newPackage,
12699                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12700                            ? UPDATE_PERMISSIONS_ALL : 0));
12701            // For system-bundled packages, we assume that installing an upgraded version
12702            // of the package implies that the user actually wants to run that new code,
12703            // so we enable the package.
12704            PackageSetting ps = mSettings.mPackages.get(pkgName);
12705            if (ps != null) {
12706                if (isSystemApp(newPackage)) {
12707                    // NB: implicit assumption that system package upgrades apply to all users
12708                    if (DEBUG_INSTALL) {
12709                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12710                    }
12711                    if (res.origUsers != null) {
12712                        for (int userHandle : res.origUsers) {
12713                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12714                                    userHandle, installerPackageName);
12715                        }
12716                    }
12717                    // Also convey the prior install/uninstall state
12718                    if (allUsers != null && perUserInstalled != null) {
12719                        for (int i = 0; i < allUsers.length; i++) {
12720                            if (DEBUG_INSTALL) {
12721                                Slog.d(TAG, "    user " + allUsers[i]
12722                                        + " => " + perUserInstalled[i]);
12723                            }
12724                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12725                        }
12726                        // these install state changes will be persisted in the
12727                        // upcoming call to mSettings.writeLPr().
12728                    }
12729                }
12730                // It's implied that when a user requests installation, they want the app to be
12731                // installed and enabled.
12732                int userId = user.getIdentifier();
12733                if (userId != UserHandle.USER_ALL) {
12734                    ps.setInstalled(true, userId);
12735                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12736                }
12737            }
12738            res.name = pkgName;
12739            res.uid = newPackage.applicationInfo.uid;
12740            res.pkg = newPackage;
12741            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12742            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12743            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12744            //to update install status
12745            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12746            mSettings.writeLPr();
12747            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12748        }
12749
12750        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12751    }
12752
12753    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12754        try {
12755            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12756            installPackageLI(args, res);
12757        } finally {
12758            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12759        }
12760    }
12761
12762    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12763        final int installFlags = args.installFlags;
12764        final String installerPackageName = args.installerPackageName;
12765        final String volumeUuid = args.volumeUuid;
12766        final File tmpPackageFile = new File(args.getCodePath());
12767        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12768        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12769                || (args.volumeUuid != null));
12770        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12771        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12772        boolean replace = false;
12773        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12774        if (args.move != null) {
12775            // moving a complete application; perfom an initial scan on the new install location
12776            scanFlags |= SCAN_INITIAL;
12777        }
12778        // Result object to be returned
12779        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12780
12781        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12782
12783        // Sanity check
12784        if (ephemeral && (forwardLocked || onExternal)) {
12785            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12786                    + " external=" + onExternal);
12787            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12788            return;
12789        }
12790
12791        // Retrieve PackageSettings and parse package
12792        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12793                | PackageParser.PARSE_ENFORCE_CODE
12794                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12795                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12796                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0)
12797                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12798        PackageParser pp = new PackageParser();
12799        pp.setSeparateProcesses(mSeparateProcesses);
12800        pp.setDisplayMetrics(mMetrics);
12801
12802        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12803        final PackageParser.Package pkg;
12804        try {
12805            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12806        } catch (PackageParserException e) {
12807            res.setError("Failed parse during installPackageLI", e);
12808            return;
12809        } finally {
12810            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12811        }
12812
12813        // Mark that we have an install time CPU ABI override.
12814        pkg.cpuAbiOverride = args.abiOverride;
12815
12816        String pkgName = res.name = pkg.packageName;
12817        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12818            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12819                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12820                return;
12821            }
12822        }
12823
12824        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12825        try {
12826            pp.collectCertificates(pkg, parseFlags);
12827        } catch (PackageParserException e) {
12828            res.setError("Failed collect during installPackageLI", e);
12829            return;
12830        } finally {
12831            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12832        }
12833
12834        /* If the installer passed in a manifest digest, compare it now. */
12835        if (args.manifestDigest != null) {
12836            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12837            try {
12838                pp.collectManifestDigest(pkg);
12839            } catch (PackageParserException e) {
12840                res.setError("Failed collect during installPackageLI", e);
12841                return;
12842            } finally {
12843                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12844            }
12845
12846            if (DEBUG_INSTALL) {
12847                final String parsedManifest = pkg.manifestDigest == null ? "null"
12848                        : pkg.manifestDigest.toString();
12849                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12850                        + parsedManifest);
12851            }
12852
12853            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12854                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12855                return;
12856            }
12857        } else if (DEBUG_INSTALL) {
12858            final String parsedManifest = pkg.manifestDigest == null
12859                    ? "null" : pkg.manifestDigest.toString();
12860            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12861        }
12862
12863        // Get rid of all references to package scan path via parser.
12864        pp = null;
12865        String oldCodePath = null;
12866        boolean systemApp = false;
12867        synchronized (mPackages) {
12868            // Check if installing already existing package
12869            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12870                String oldName = mSettings.mRenamedPackages.get(pkgName);
12871                if (pkg.mOriginalPackages != null
12872                        && pkg.mOriginalPackages.contains(oldName)
12873                        && mPackages.containsKey(oldName)) {
12874                    // This package is derived from an original package,
12875                    // and this device has been updating from that original
12876                    // name.  We must continue using the original name, so
12877                    // rename the new package here.
12878                    pkg.setPackageName(oldName);
12879                    pkgName = pkg.packageName;
12880                    replace = true;
12881                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12882                            + oldName + " pkgName=" + pkgName);
12883                } else if (mPackages.containsKey(pkgName)) {
12884                    // This package, under its official name, already exists
12885                    // on the device; we should replace it.
12886                    replace = true;
12887                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12888                }
12889
12890                // Prevent apps opting out from runtime permissions
12891                if (replace) {
12892                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12893                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12894                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12895                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12896                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12897                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12898                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12899                                        + " doesn't support runtime permissions but the old"
12900                                        + " target SDK " + oldTargetSdk + " does.");
12901                        return;
12902                    }
12903                }
12904            }
12905
12906            PackageSetting ps = mSettings.mPackages.get(pkgName);
12907            if (ps != null) {
12908                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12909
12910                // Quick sanity check that we're signed correctly if updating;
12911                // we'll check this again later when scanning, but we want to
12912                // bail early here before tripping over redefined permissions.
12913                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12914                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12915                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12916                                + pkg.packageName + " upgrade keys do not match the "
12917                                + "previously installed version");
12918                        return;
12919                    }
12920                } else {
12921                    try {
12922                        verifySignaturesLP(ps, pkg);
12923                    } catch (PackageManagerException e) {
12924                        res.setError(e.error, e.getMessage());
12925                        return;
12926                    }
12927                }
12928
12929                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12930                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12931                    systemApp = (ps.pkg.applicationInfo.flags &
12932                            ApplicationInfo.FLAG_SYSTEM) != 0;
12933                }
12934                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12935            }
12936
12937            // Check whether the newly-scanned package wants to define an already-defined perm
12938            int N = pkg.permissions.size();
12939            for (int i = N-1; i >= 0; i--) {
12940                PackageParser.Permission perm = pkg.permissions.get(i);
12941                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12942                if (bp != null) {
12943                    // If the defining package is signed with our cert, it's okay.  This
12944                    // also includes the "updating the same package" case, of course.
12945                    // "updating same package" could also involve key-rotation.
12946                    final boolean sigsOk;
12947                    if (bp.sourcePackage.equals(pkg.packageName)
12948                            && (bp.packageSetting instanceof PackageSetting)
12949                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12950                                    scanFlags))) {
12951                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12952                    } else {
12953                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12954                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12955                    }
12956                    if (!sigsOk) {
12957                        // If the owning package is the system itself, we log but allow
12958                        // install to proceed; we fail the install on all other permission
12959                        // redefinitions.
12960                        if (!bp.sourcePackage.equals("android")) {
12961                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12962                                    + pkg.packageName + " attempting to redeclare permission "
12963                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12964                            res.origPermission = perm.info.name;
12965                            res.origPackage = bp.sourcePackage;
12966                            return;
12967                        } else {
12968                            Slog.w(TAG, "Package " + pkg.packageName
12969                                    + " attempting to redeclare system permission "
12970                                    + perm.info.name + "; ignoring new declaration");
12971                            pkg.permissions.remove(i);
12972                        }
12973                    }
12974                }
12975            }
12976
12977        }
12978
12979        if (systemApp) {
12980            if (onExternal) {
12981                // Abort update; system app can't be replaced with app on sdcard
12982                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12983                        "Cannot install updates to system apps on sdcard");
12984                return;
12985            } else if (ephemeral) {
12986                // Abort update; system app can't be replaced with an ephemeral app
12987                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12988                        "Cannot update a system app with an ephemeral app");
12989                return;
12990            }
12991        }
12992
12993        if (args.move != null) {
12994            // We did an in-place move, so dex is ready to roll
12995            scanFlags |= SCAN_NO_DEX;
12996            scanFlags |= SCAN_MOVE;
12997
12998            synchronized (mPackages) {
12999                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13000                if (ps == null) {
13001                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13002                            "Missing settings for moved package " + pkgName);
13003                }
13004
13005                // We moved the entire application as-is, so bring over the
13006                // previously derived ABI information.
13007                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13008                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13009            }
13010
13011        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13012            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13013            scanFlags |= SCAN_NO_DEX;
13014
13015            try {
13016                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13017                        true /* extract libs */);
13018            } catch (PackageManagerException pme) {
13019                Slog.e(TAG, "Error deriving application ABI", pme);
13020                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13021                return;
13022            }
13023        }
13024
13025        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13026            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13027            return;
13028        }
13029
13030        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13031
13032        if (replace) {
13033            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13034                    installerPackageName, volumeUuid, res);
13035        } else {
13036            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13037                    args.user, installerPackageName, volumeUuid, res);
13038        }
13039        synchronized (mPackages) {
13040            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13041            if (ps != null) {
13042                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13043            }
13044        }
13045    }
13046
13047    private void startIntentFilterVerifications(int userId, boolean replacing,
13048            PackageParser.Package pkg) {
13049        if (mIntentFilterVerifierComponent == null) {
13050            Slog.w(TAG, "No IntentFilter verification will not be done as "
13051                    + "there is no IntentFilterVerifier available!");
13052            return;
13053        }
13054
13055        final int verifierUid = getPackageUid(
13056                mIntentFilterVerifierComponent.getPackageName(),
13057                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13058
13059        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13060        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13061        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13062        mHandler.sendMessage(msg);
13063    }
13064
13065    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13066            PackageParser.Package pkg) {
13067        int size = pkg.activities.size();
13068        if (size == 0) {
13069            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13070                    "No activity, so no need to verify any IntentFilter!");
13071            return;
13072        }
13073
13074        final boolean hasDomainURLs = hasDomainURLs(pkg);
13075        if (!hasDomainURLs) {
13076            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13077                    "No domain URLs, so no need to verify any IntentFilter!");
13078            return;
13079        }
13080
13081        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13082                + " if any IntentFilter from the " + size
13083                + " Activities needs verification ...");
13084
13085        int count = 0;
13086        final String packageName = pkg.packageName;
13087
13088        synchronized (mPackages) {
13089            // If this is a new install and we see that we've already run verification for this
13090            // package, we have nothing to do: it means the state was restored from backup.
13091            if (!replacing) {
13092                IntentFilterVerificationInfo ivi =
13093                        mSettings.getIntentFilterVerificationLPr(packageName);
13094                if (ivi != null) {
13095                    if (DEBUG_DOMAIN_VERIFICATION) {
13096                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13097                                + ivi.getStatusString());
13098                    }
13099                    return;
13100                }
13101            }
13102
13103            // If any filters need to be verified, then all need to be.
13104            boolean needToVerify = false;
13105            for (PackageParser.Activity a : pkg.activities) {
13106                for (ActivityIntentInfo filter : a.intents) {
13107                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13108                        if (DEBUG_DOMAIN_VERIFICATION) {
13109                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13110                        }
13111                        needToVerify = true;
13112                        break;
13113                    }
13114                }
13115            }
13116
13117            if (needToVerify) {
13118                final int verificationId = mIntentFilterVerificationToken++;
13119                for (PackageParser.Activity a : pkg.activities) {
13120                    for (ActivityIntentInfo filter : a.intents) {
13121                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13122                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13123                                    "Verification needed for IntentFilter:" + filter.toString());
13124                            mIntentFilterVerifier.addOneIntentFilterVerification(
13125                                    verifierUid, userId, verificationId, filter, packageName);
13126                            count++;
13127                        }
13128                    }
13129                }
13130            }
13131        }
13132
13133        if (count > 0) {
13134            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13135                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13136                    +  " for userId:" + userId);
13137            mIntentFilterVerifier.startVerifications(userId);
13138        } else {
13139            if (DEBUG_DOMAIN_VERIFICATION) {
13140                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13141            }
13142        }
13143    }
13144
13145    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13146        final ComponentName cn  = filter.activity.getComponentName();
13147        final String packageName = cn.getPackageName();
13148
13149        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13150                packageName);
13151        if (ivi == null) {
13152            return true;
13153        }
13154        int status = ivi.getStatus();
13155        switch (status) {
13156            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13157            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13158                return true;
13159
13160            default:
13161                // Nothing to do
13162                return false;
13163        }
13164    }
13165
13166    private static boolean isMultiArch(PackageSetting ps) {
13167        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13168    }
13169
13170    private static boolean isMultiArch(ApplicationInfo info) {
13171        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13172    }
13173
13174    private static boolean isExternal(PackageParser.Package pkg) {
13175        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13176    }
13177
13178    private static boolean isExternal(PackageSetting ps) {
13179        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13180    }
13181
13182    private static boolean isExternal(ApplicationInfo info) {
13183        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13184    }
13185
13186    private static boolean isEphemeral(PackageParser.Package pkg) {
13187        return pkg.applicationInfo.isEphemeralApp();
13188    }
13189
13190    private static boolean isEphemeral(PackageSetting ps) {
13191        return ps.pkg != null && isEphemeral(ps.pkg);
13192    }
13193
13194    private static boolean isSystemApp(PackageParser.Package pkg) {
13195        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13196    }
13197
13198    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13199        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13200    }
13201
13202    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13203        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13204    }
13205
13206    private static boolean isSystemApp(PackageSetting ps) {
13207        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13208    }
13209
13210    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13211        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13212    }
13213
13214    private int packageFlagsToInstallFlags(PackageSetting ps) {
13215        int installFlags = 0;
13216        if (isEphemeral(ps)) {
13217            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13218        }
13219        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13220            // This existing package was an external ASEC install when we have
13221            // the external flag without a UUID
13222            installFlags |= PackageManager.INSTALL_EXTERNAL;
13223        }
13224        if (ps.isForwardLocked()) {
13225            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13226        }
13227        return installFlags;
13228    }
13229
13230    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13231        if (isExternal(pkg)) {
13232            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13233                return StorageManager.UUID_PRIMARY_PHYSICAL;
13234            } else {
13235                return pkg.volumeUuid;
13236            }
13237        } else {
13238            return StorageManager.UUID_PRIVATE_INTERNAL;
13239        }
13240    }
13241
13242    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13243        if (isExternal(pkg)) {
13244            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13245                return mSettings.getExternalVersion();
13246            } else {
13247                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13248            }
13249        } else {
13250            return mSettings.getInternalVersion();
13251        }
13252    }
13253
13254    private void deleteTempPackageFiles() {
13255        final FilenameFilter filter = new FilenameFilter() {
13256            public boolean accept(File dir, String name) {
13257                return name.startsWith("vmdl") && name.endsWith(".tmp");
13258            }
13259        };
13260        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13261            file.delete();
13262        }
13263    }
13264
13265    @Override
13266    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13267            int flags) {
13268        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13269                flags);
13270    }
13271
13272    @Override
13273    public void deletePackage(final String packageName,
13274            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13275        mContext.enforceCallingOrSelfPermission(
13276                android.Manifest.permission.DELETE_PACKAGES, null);
13277        Preconditions.checkNotNull(packageName);
13278        Preconditions.checkNotNull(observer);
13279        final int uid = Binder.getCallingUid();
13280        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13281        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13282        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13283            mContext.enforceCallingOrSelfPermission(
13284                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13285                    "deletePackage for user " + userId);
13286        }
13287
13288        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13289            try {
13290                observer.onPackageDeleted(packageName,
13291                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13292            } catch (RemoteException re) {
13293            }
13294            return;
13295        }
13296
13297        for (int currentUserId : users) {
13298            if (getBlockUninstallForUser(packageName, currentUserId)) {
13299                try {
13300                    observer.onPackageDeleted(packageName,
13301                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13302                } catch (RemoteException re) {
13303                }
13304                return;
13305            }
13306        }
13307
13308        if (DEBUG_REMOVE) {
13309            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13310        }
13311        // Queue up an async operation since the package deletion may take a little while.
13312        mHandler.post(new Runnable() {
13313            public void run() {
13314                mHandler.removeCallbacks(this);
13315                final int returnCode = deletePackageX(packageName, userId, flags);
13316                try {
13317                    observer.onPackageDeleted(packageName, returnCode, null);
13318                } catch (RemoteException e) {
13319                    Log.i(TAG, "Observer no longer exists.");
13320                } //end catch
13321            } //end run
13322        });
13323    }
13324
13325    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13326        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13327                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13328        try {
13329            if (dpm != null) {
13330                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13331                        /* callingUserOnly =*/ false);
13332                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13333                        : deviceOwnerComponentName.getPackageName();
13334                // Does the package contains the device owner?
13335                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13336                // this check is probably not needed, since DO should be registered as a device
13337                // admin on some user too. (Original bug for this: b/17657954)
13338                if (packageName.equals(deviceOwnerPackageName)) {
13339                    return true;
13340                }
13341                // Does it contain a device admin for any user?
13342                int[] users;
13343                if (userId == UserHandle.USER_ALL) {
13344                    users = sUserManager.getUserIds();
13345                } else {
13346                    users = new int[]{userId};
13347                }
13348                for (int i = 0; i < users.length; ++i) {
13349                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13350                        return true;
13351                    }
13352                }
13353            }
13354        } catch (RemoteException e) {
13355        }
13356        return false;
13357    }
13358
13359    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13360        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13361    }
13362
13363    /**
13364     *  This method is an internal method that could be get invoked either
13365     *  to delete an installed package or to clean up a failed installation.
13366     *  After deleting an installed package, a broadcast is sent to notify any
13367     *  listeners that the package has been installed. For cleaning up a failed
13368     *  installation, the broadcast is not necessary since the package's
13369     *  installation wouldn't have sent the initial broadcast either
13370     *  The key steps in deleting a package are
13371     *  deleting the package information in internal structures like mPackages,
13372     *  deleting the packages base directories through installd
13373     *  updating mSettings to reflect current status
13374     *  persisting settings for later use
13375     *  sending a broadcast if necessary
13376     */
13377    private int deletePackageX(String packageName, int userId, int flags) {
13378        final PackageRemovedInfo info = new PackageRemovedInfo();
13379        final boolean res;
13380
13381        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13382                ? UserHandle.ALL : new UserHandle(userId);
13383
13384        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13385            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13386            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13387        }
13388
13389        boolean removedForAllUsers = false;
13390        boolean systemUpdate = false;
13391
13392        PackageParser.Package uninstalledPkg;
13393
13394        // for the uninstall-updates case and restricted profiles, remember the per-
13395        // userhandle installed state
13396        int[] allUsers;
13397        boolean[] perUserInstalled;
13398        synchronized (mPackages) {
13399            uninstalledPkg = mPackages.get(packageName);
13400            PackageSetting ps = mSettings.mPackages.get(packageName);
13401            allUsers = sUserManager.getUserIds();
13402            perUserInstalled = new boolean[allUsers.length];
13403            for (int i = 0; i < allUsers.length; i++) {
13404                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13405            }
13406        }
13407
13408        synchronized (mInstallLock) {
13409            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13410            res = deletePackageLI(packageName, removeForUser,
13411                    true, allUsers, perUserInstalled,
13412                    flags | REMOVE_CHATTY, info, true);
13413            systemUpdate = info.isRemovedPackageSystemUpdate;
13414            synchronized (mPackages) {
13415                if (res) {
13416                    if (!systemUpdate && mPackages.get(packageName) == null) {
13417                        removedForAllUsers = true;
13418                    }
13419                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13420                }
13421            }
13422            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13423                    + " removedForAllUsers=" + removedForAllUsers);
13424        }
13425
13426        if (res) {
13427            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13428
13429            // If the removed package was a system update, the old system package
13430            // was re-enabled; we need to broadcast this information
13431            if (systemUpdate) {
13432                Bundle extras = new Bundle(1);
13433                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13434                        ? info.removedAppId : info.uid);
13435                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13436
13437                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13438                        extras, 0, null, null, null);
13439                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13440                        extras, 0, null, null, null);
13441                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13442                        null, 0, packageName, null, null);
13443            }
13444        }
13445        // Force a gc here.
13446        Runtime.getRuntime().gc();
13447        // Delete the resources here after sending the broadcast to let
13448        // other processes clean up before deleting resources.
13449        if (info.args != null) {
13450            synchronized (mInstallLock) {
13451                info.args.doPostDeleteLI(true);
13452            }
13453        }
13454
13455        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13456    }
13457
13458    class PackageRemovedInfo {
13459        String removedPackage;
13460        int uid = -1;
13461        int removedAppId = -1;
13462        int[] removedUsers = null;
13463        boolean isRemovedPackageSystemUpdate = false;
13464        // Clean up resources deleted packages.
13465        InstallArgs args = null;
13466
13467        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13468            Bundle extras = new Bundle(1);
13469            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13470            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13471            if (replacing) {
13472                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13473            }
13474            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13475            if (removedPackage != null) {
13476                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13477                        extras, 0, null, null, removedUsers);
13478                if (fullRemove && !replacing) {
13479                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13480                            extras, 0, null, null, removedUsers);
13481                }
13482            }
13483            if (removedAppId >= 0) {
13484                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13485                        removedUsers);
13486            }
13487        }
13488    }
13489
13490    /*
13491     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13492     * flag is not set, the data directory is removed as well.
13493     * make sure this flag is set for partially installed apps. If not its meaningless to
13494     * delete a partially installed application.
13495     */
13496    private void removePackageDataLI(PackageSetting ps,
13497            int[] allUserHandles, boolean[] perUserInstalled,
13498            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13499        String packageName = ps.name;
13500        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13501        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13502        // Retrieve object to delete permissions for shared user later on
13503        final PackageSetting deletedPs;
13504        // reader
13505        synchronized (mPackages) {
13506            deletedPs = mSettings.mPackages.get(packageName);
13507            if (outInfo != null) {
13508                outInfo.removedPackage = packageName;
13509                outInfo.removedUsers = deletedPs != null
13510                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13511                        : null;
13512            }
13513        }
13514        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13515            removeDataDirsLI(ps.volumeUuid, packageName);
13516            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13517        }
13518        // writer
13519        synchronized (mPackages) {
13520            if (deletedPs != null) {
13521                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13522                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13523                    clearDefaultBrowserIfNeeded(packageName);
13524                    if (outInfo != null) {
13525                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13526                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13527                    }
13528                    updatePermissionsLPw(deletedPs.name, null, 0);
13529                    if (deletedPs.sharedUser != null) {
13530                        // Remove permissions associated with package. Since runtime
13531                        // permissions are per user we have to kill the removed package
13532                        // or packages running under the shared user of the removed
13533                        // package if revoking the permissions requested only by the removed
13534                        // package is successful and this causes a change in gids.
13535                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13536                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13537                                    userId);
13538                            if (userIdToKill == UserHandle.USER_ALL
13539                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13540                                // If gids changed for this user, kill all affected packages.
13541                                mHandler.post(new Runnable() {
13542                                    @Override
13543                                    public void run() {
13544                                        // This has to happen with no lock held.
13545                                        killApplication(deletedPs.name, deletedPs.appId,
13546                                                KILL_APP_REASON_GIDS_CHANGED);
13547                                    }
13548                                });
13549                                break;
13550                            }
13551                        }
13552                    }
13553                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13554                }
13555                // make sure to preserve per-user disabled state if this removal was just
13556                // a downgrade of a system app to the factory package
13557                if (allUserHandles != null && perUserInstalled != null) {
13558                    if (DEBUG_REMOVE) {
13559                        Slog.d(TAG, "Propagating install state across downgrade");
13560                    }
13561                    for (int i = 0; i < allUserHandles.length; i++) {
13562                        if (DEBUG_REMOVE) {
13563                            Slog.d(TAG, "    user " + allUserHandles[i]
13564                                    + " => " + perUserInstalled[i]);
13565                        }
13566                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13567                    }
13568                }
13569            }
13570            // can downgrade to reader
13571            if (writeSettings) {
13572                // Save settings now
13573                mSettings.writeLPr();
13574            }
13575        }
13576        if (outInfo != null) {
13577            // A user ID was deleted here. Go through all users and remove it
13578            // from KeyStore.
13579            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13580        }
13581    }
13582
13583    static boolean locationIsPrivileged(File path) {
13584        try {
13585            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13586                    .getCanonicalPath();
13587            return path.getCanonicalPath().startsWith(privilegedAppDir);
13588        } catch (IOException e) {
13589            Slog.e(TAG, "Unable to access code path " + path);
13590        }
13591        return false;
13592    }
13593
13594    /*
13595     * Tries to delete system package.
13596     */
13597    private boolean deleteSystemPackageLI(PackageSetting newPs,
13598            int[] allUserHandles, boolean[] perUserInstalled,
13599            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13600        final boolean applyUserRestrictions
13601                = (allUserHandles != null) && (perUserInstalled != null);
13602        PackageSetting disabledPs = null;
13603        // Confirm if the system package has been updated
13604        // An updated system app can be deleted. This will also have to restore
13605        // the system pkg from system partition
13606        // reader
13607        synchronized (mPackages) {
13608            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13609        }
13610        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13611                + " disabledPs=" + disabledPs);
13612        if (disabledPs == null) {
13613            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13614            return false;
13615        } else if (DEBUG_REMOVE) {
13616            Slog.d(TAG, "Deleting system pkg from data partition");
13617        }
13618        if (DEBUG_REMOVE) {
13619            if (applyUserRestrictions) {
13620                Slog.d(TAG, "Remembering install states:");
13621                for (int i = 0; i < allUserHandles.length; i++) {
13622                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13623                }
13624            }
13625        }
13626        // Delete the updated package
13627        outInfo.isRemovedPackageSystemUpdate = true;
13628        if (disabledPs.versionCode < newPs.versionCode) {
13629            // Delete data for downgrades
13630            flags &= ~PackageManager.DELETE_KEEP_DATA;
13631        } else {
13632            // Preserve data by setting flag
13633            flags |= PackageManager.DELETE_KEEP_DATA;
13634        }
13635        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13636                allUserHandles, perUserInstalled, outInfo, writeSettings);
13637        if (!ret) {
13638            return false;
13639        }
13640        // writer
13641        synchronized (mPackages) {
13642            // Reinstate the old system package
13643            mSettings.enableSystemPackageLPw(newPs.name);
13644            // Remove any native libraries from the upgraded package.
13645            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13646        }
13647        // Install the system package
13648        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13649        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13650        if (locationIsPrivileged(disabledPs.codePath)) {
13651            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13652        }
13653
13654        final PackageParser.Package newPkg;
13655        try {
13656            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13657        } catch (PackageManagerException e) {
13658            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13659            return false;
13660        }
13661
13662        // writer
13663        synchronized (mPackages) {
13664            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13665
13666            // Propagate the permissions state as we do not want to drop on the floor
13667            // runtime permissions. The update permissions method below will take
13668            // care of removing obsolete permissions and grant install permissions.
13669            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13670            updatePermissionsLPw(newPkg.packageName, newPkg,
13671                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13672
13673            if (applyUserRestrictions) {
13674                if (DEBUG_REMOVE) {
13675                    Slog.d(TAG, "Propagating install state across reinstall");
13676                }
13677                for (int i = 0; i < allUserHandles.length; i++) {
13678                    if (DEBUG_REMOVE) {
13679                        Slog.d(TAG, "    user " + allUserHandles[i]
13680                                + " => " + perUserInstalled[i]);
13681                    }
13682                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13683
13684                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13685                }
13686                // Regardless of writeSettings we need to ensure that this restriction
13687                // state propagation is persisted
13688                mSettings.writeAllUsersPackageRestrictionsLPr();
13689            }
13690            // can downgrade to reader here
13691            if (writeSettings) {
13692                mSettings.writeLPr();
13693            }
13694        }
13695        return true;
13696    }
13697
13698    private boolean deleteInstalledPackageLI(PackageSetting ps,
13699            boolean deleteCodeAndResources, int flags,
13700            int[] allUserHandles, boolean[] perUserInstalled,
13701            PackageRemovedInfo outInfo, boolean writeSettings) {
13702        if (outInfo != null) {
13703            outInfo.uid = ps.appId;
13704        }
13705
13706        // Delete package data from internal structures and also remove data if flag is set
13707        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13708
13709        // Delete application code and resources
13710        if (deleteCodeAndResources && (outInfo != null)) {
13711            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13712                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13713            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13714        }
13715        return true;
13716    }
13717
13718    @Override
13719    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13720            int userId) {
13721        mContext.enforceCallingOrSelfPermission(
13722                android.Manifest.permission.DELETE_PACKAGES, null);
13723        synchronized (mPackages) {
13724            PackageSetting ps = mSettings.mPackages.get(packageName);
13725            if (ps == null) {
13726                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13727                return false;
13728            }
13729            if (!ps.getInstalled(userId)) {
13730                // Can't block uninstall for an app that is not installed or enabled.
13731                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13732                return false;
13733            }
13734            ps.setBlockUninstall(blockUninstall, userId);
13735            mSettings.writePackageRestrictionsLPr(userId);
13736        }
13737        return true;
13738    }
13739
13740    @Override
13741    public boolean getBlockUninstallForUser(String packageName, int userId) {
13742        synchronized (mPackages) {
13743            PackageSetting ps = mSettings.mPackages.get(packageName);
13744            if (ps == null) {
13745                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13746                return false;
13747            }
13748            return ps.getBlockUninstall(userId);
13749        }
13750    }
13751
13752    /*
13753     * This method handles package deletion in general
13754     */
13755    private boolean deletePackageLI(String packageName, UserHandle user,
13756            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13757            int flags, PackageRemovedInfo outInfo,
13758            boolean writeSettings) {
13759        if (packageName == null) {
13760            Slog.w(TAG, "Attempt to delete null packageName.");
13761            return false;
13762        }
13763        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13764        PackageSetting ps;
13765        boolean dataOnly = false;
13766        int removeUser = -1;
13767        int appId = -1;
13768        synchronized (mPackages) {
13769            ps = mSettings.mPackages.get(packageName);
13770            if (ps == null) {
13771                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13772                return false;
13773            }
13774            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13775                    && user.getIdentifier() != UserHandle.USER_ALL) {
13776                // The caller is asking that the package only be deleted for a single
13777                // user.  To do this, we just mark its uninstalled state and delete
13778                // its data.  If this is a system app, we only allow this to happen if
13779                // they have set the special DELETE_SYSTEM_APP which requests different
13780                // semantics than normal for uninstalling system apps.
13781                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13782                final int userId = user.getIdentifier();
13783                ps.setUserState(userId,
13784                        COMPONENT_ENABLED_STATE_DEFAULT,
13785                        false, //installed
13786                        true,  //stopped
13787                        true,  //notLaunched
13788                        false, //hidden
13789                        null, null, null,
13790                        false, // blockUninstall
13791                        ps.readUserState(userId).domainVerificationStatus, 0);
13792                if (!isSystemApp(ps)) {
13793                    // Do not uninstall the APK if an app should be cached
13794                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13795                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13796                        // Other user still have this package installed, so all
13797                        // we need to do is clear this user's data and save that
13798                        // it is uninstalled.
13799                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13800                        removeUser = user.getIdentifier();
13801                        appId = ps.appId;
13802                        scheduleWritePackageRestrictionsLocked(removeUser);
13803                    } else {
13804                        // We need to set it back to 'installed' so the uninstall
13805                        // broadcasts will be sent correctly.
13806                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13807                        ps.setInstalled(true, user.getIdentifier());
13808                    }
13809                } else {
13810                    // This is a system app, so we assume that the
13811                    // other users still have this package installed, so all
13812                    // we need to do is clear this user's data and save that
13813                    // it is uninstalled.
13814                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13815                    removeUser = user.getIdentifier();
13816                    appId = ps.appId;
13817                    scheduleWritePackageRestrictionsLocked(removeUser);
13818                }
13819            }
13820        }
13821
13822        if (removeUser >= 0) {
13823            // From above, we determined that we are deleting this only
13824            // for a single user.  Continue the work here.
13825            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13826            if (outInfo != null) {
13827                outInfo.removedPackage = packageName;
13828                outInfo.removedAppId = appId;
13829                outInfo.removedUsers = new int[] {removeUser};
13830            }
13831            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13832            removeKeystoreDataIfNeeded(removeUser, appId);
13833            schedulePackageCleaning(packageName, removeUser, false);
13834            synchronized (mPackages) {
13835                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13836                    scheduleWritePackageRestrictionsLocked(removeUser);
13837                }
13838                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13839            }
13840            return true;
13841        }
13842
13843        if (dataOnly) {
13844            // Delete application data first
13845            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13846            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13847            return true;
13848        }
13849
13850        boolean ret = false;
13851        if (isSystemApp(ps)) {
13852            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13853            // When an updated system application is deleted we delete the existing resources as well and
13854            // fall back to existing code in system partition
13855            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13856                    flags, outInfo, writeSettings);
13857        } else {
13858            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13859            // Kill application pre-emptively especially for apps on sd.
13860            killApplication(packageName, ps.appId, "uninstall pkg");
13861            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13862                    allUserHandles, perUserInstalled,
13863                    outInfo, writeSettings);
13864        }
13865
13866        return ret;
13867    }
13868
13869    private final class ClearStorageConnection implements ServiceConnection {
13870        IMediaContainerService mContainerService;
13871
13872        @Override
13873        public void onServiceConnected(ComponentName name, IBinder service) {
13874            synchronized (this) {
13875                mContainerService = IMediaContainerService.Stub.asInterface(service);
13876                notifyAll();
13877            }
13878        }
13879
13880        @Override
13881        public void onServiceDisconnected(ComponentName name) {
13882        }
13883    }
13884
13885    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13886        final boolean mounted;
13887        if (Environment.isExternalStorageEmulated()) {
13888            mounted = true;
13889        } else {
13890            final String status = Environment.getExternalStorageState();
13891
13892            mounted = status.equals(Environment.MEDIA_MOUNTED)
13893                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13894        }
13895
13896        if (!mounted) {
13897            return;
13898        }
13899
13900        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13901        int[] users;
13902        if (userId == UserHandle.USER_ALL) {
13903            users = sUserManager.getUserIds();
13904        } else {
13905            users = new int[] { userId };
13906        }
13907        final ClearStorageConnection conn = new ClearStorageConnection();
13908        if (mContext.bindServiceAsUser(
13909                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13910            try {
13911                for (int curUser : users) {
13912                    long timeout = SystemClock.uptimeMillis() + 5000;
13913                    synchronized (conn) {
13914                        long now = SystemClock.uptimeMillis();
13915                        while (conn.mContainerService == null && now < timeout) {
13916                            try {
13917                                conn.wait(timeout - now);
13918                            } catch (InterruptedException e) {
13919                            }
13920                        }
13921                    }
13922                    if (conn.mContainerService == null) {
13923                        return;
13924                    }
13925
13926                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13927                    clearDirectory(conn.mContainerService,
13928                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13929                    if (allData) {
13930                        clearDirectory(conn.mContainerService,
13931                                userEnv.buildExternalStorageAppDataDirs(packageName));
13932                        clearDirectory(conn.mContainerService,
13933                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13934                    }
13935                }
13936            } finally {
13937                mContext.unbindService(conn);
13938            }
13939        }
13940    }
13941
13942    @Override
13943    public void clearApplicationUserData(final String packageName,
13944            final IPackageDataObserver observer, final int userId) {
13945        mContext.enforceCallingOrSelfPermission(
13946                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13947        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13948        // Queue up an async operation since the package deletion may take a little while.
13949        mHandler.post(new Runnable() {
13950            public void run() {
13951                mHandler.removeCallbacks(this);
13952                final boolean succeeded;
13953                synchronized (mInstallLock) {
13954                    succeeded = clearApplicationUserDataLI(packageName, userId);
13955                }
13956                clearExternalStorageDataSync(packageName, userId, true);
13957                if (succeeded) {
13958                    // invoke DeviceStorageMonitor's update method to clear any notifications
13959                    DeviceStorageMonitorInternal
13960                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13961                    if (dsm != null) {
13962                        dsm.checkMemory();
13963                    }
13964                }
13965                if(observer != null) {
13966                    try {
13967                        observer.onRemoveCompleted(packageName, succeeded);
13968                    } catch (RemoteException e) {
13969                        Log.i(TAG, "Observer no longer exists.");
13970                    }
13971                } //end if observer
13972            } //end run
13973        });
13974    }
13975
13976    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13977        if (packageName == null) {
13978            Slog.w(TAG, "Attempt to delete null packageName.");
13979            return false;
13980        }
13981
13982        // Try finding details about the requested package
13983        PackageParser.Package pkg;
13984        synchronized (mPackages) {
13985            pkg = mPackages.get(packageName);
13986            if (pkg == null) {
13987                final PackageSetting ps = mSettings.mPackages.get(packageName);
13988                if (ps != null) {
13989                    pkg = ps.pkg;
13990                }
13991            }
13992
13993            if (pkg == null) {
13994                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13995                return false;
13996            }
13997
13998            PackageSetting ps = (PackageSetting) pkg.mExtras;
13999            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14000        }
14001
14002        // Always delete data directories for package, even if we found no other
14003        // record of app. This helps users recover from UID mismatches without
14004        // resorting to a full data wipe.
14005        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14006        if (retCode < 0) {
14007            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
14008            return false;
14009        }
14010
14011        final int appId = pkg.applicationInfo.uid;
14012        removeKeystoreDataIfNeeded(userId, appId);
14013
14014        // Create a native library symlink only if we have native libraries
14015        // and if the native libraries are 32 bit libraries. We do not provide
14016        // this symlink for 64 bit libraries.
14017        if (pkg.applicationInfo.primaryCpuAbi != null &&
14018                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14019            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14020            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14021                    nativeLibPath, userId) < 0) {
14022                Slog.w(TAG, "Failed linking native library dir");
14023                return false;
14024            }
14025        }
14026
14027        return true;
14028    }
14029
14030    /**
14031     * Reverts user permission state changes (permissions and flags) in
14032     * all packages for a given user.
14033     *
14034     * @param userId The device user for which to do a reset.
14035     */
14036    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14037        final int packageCount = mPackages.size();
14038        for (int i = 0; i < packageCount; i++) {
14039            PackageParser.Package pkg = mPackages.valueAt(i);
14040            PackageSetting ps = (PackageSetting) pkg.mExtras;
14041            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14042        }
14043    }
14044
14045    /**
14046     * Reverts user permission state changes (permissions and flags).
14047     *
14048     * @param ps The package for which to reset.
14049     * @param userId The device user for which to do a reset.
14050     */
14051    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14052            final PackageSetting ps, final int userId) {
14053        if (ps.pkg == null) {
14054            return;
14055        }
14056
14057        // These are flags that can change base on user actions.
14058        final int userSettableMask = FLAG_PERMISSION_USER_SET
14059                | FLAG_PERMISSION_USER_FIXED
14060                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14061                | FLAG_PERMISSION_REVIEW_REQUIRED;
14062
14063        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14064                | FLAG_PERMISSION_POLICY_FIXED;
14065
14066        boolean writeInstallPermissions = false;
14067        boolean writeRuntimePermissions = false;
14068
14069        final int permissionCount = ps.pkg.requestedPermissions.size();
14070        for (int i = 0; i < permissionCount; i++) {
14071            String permission = ps.pkg.requestedPermissions.get(i);
14072
14073            BasePermission bp = mSettings.mPermissions.get(permission);
14074            if (bp == null) {
14075                continue;
14076            }
14077
14078            // If shared user we just reset the state to which only this app contributed.
14079            if (ps.sharedUser != null) {
14080                boolean used = false;
14081                final int packageCount = ps.sharedUser.packages.size();
14082                for (int j = 0; j < packageCount; j++) {
14083                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14084                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14085                            && pkg.pkg.requestedPermissions.contains(permission)) {
14086                        used = true;
14087                        break;
14088                    }
14089                }
14090                if (used) {
14091                    continue;
14092                }
14093            }
14094
14095            PermissionsState permissionsState = ps.getPermissionsState();
14096
14097            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14098
14099            // Always clear the user settable flags.
14100            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14101                    bp.name) != null;
14102            // If permission review is enabled and this is a legacy app, mark the
14103            // permission as requiring a review as this is the initial state.
14104            int flags = 0;
14105            if (Build.PERMISSIONS_REVIEW_REQUIRED
14106                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14107                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14108            }
14109            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14110                if (hasInstallState) {
14111                    writeInstallPermissions = true;
14112                } else {
14113                    writeRuntimePermissions = true;
14114                }
14115            }
14116
14117            // Below is only runtime permission handling.
14118            if (!bp.isRuntime()) {
14119                continue;
14120            }
14121
14122            // Never clobber system or policy.
14123            if ((oldFlags & policyOrSystemFlags) != 0) {
14124                continue;
14125            }
14126
14127            // If this permission was granted by default, make sure it is.
14128            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14129                if (permissionsState.grantRuntimePermission(bp, userId)
14130                        != PERMISSION_OPERATION_FAILURE) {
14131                    writeRuntimePermissions = true;
14132                }
14133            // If permission review is enabled the permissions for a legacy apps
14134            // are represented as constantly granted runtime ones, so don't revoke.
14135            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14136                // Otherwise, reset the permission.
14137                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14138                switch (revokeResult) {
14139                    case PERMISSION_OPERATION_SUCCESS: {
14140                        writeRuntimePermissions = true;
14141                    } break;
14142
14143                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14144                        writeRuntimePermissions = true;
14145                        final int appId = ps.appId;
14146                        mHandler.post(new Runnable() {
14147                            @Override
14148                            public void run() {
14149                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14150                            }
14151                        });
14152                    } break;
14153                }
14154            }
14155        }
14156
14157        // Synchronously write as we are taking permissions away.
14158        if (writeRuntimePermissions) {
14159            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14160        }
14161
14162        // Synchronously write as we are taking permissions away.
14163        if (writeInstallPermissions) {
14164            mSettings.writeLPr();
14165        }
14166    }
14167
14168    /**
14169     * Remove entries from the keystore daemon. Will only remove it if the
14170     * {@code appId} is valid.
14171     */
14172    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14173        if (appId < 0) {
14174            return;
14175        }
14176
14177        final KeyStore keyStore = KeyStore.getInstance();
14178        if (keyStore != null) {
14179            if (userId == UserHandle.USER_ALL) {
14180                for (final int individual : sUserManager.getUserIds()) {
14181                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14182                }
14183            } else {
14184                keyStore.clearUid(UserHandle.getUid(userId, appId));
14185            }
14186        } else {
14187            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14188        }
14189    }
14190
14191    @Override
14192    public void deleteApplicationCacheFiles(final String packageName,
14193            final IPackageDataObserver observer) {
14194        mContext.enforceCallingOrSelfPermission(
14195                android.Manifest.permission.DELETE_CACHE_FILES, null);
14196        // Queue up an async operation since the package deletion may take a little while.
14197        final int userId = UserHandle.getCallingUserId();
14198        mHandler.post(new Runnable() {
14199            public void run() {
14200                mHandler.removeCallbacks(this);
14201                final boolean succeded;
14202                synchronized (mInstallLock) {
14203                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14204                }
14205                clearExternalStorageDataSync(packageName, userId, false);
14206                if (observer != null) {
14207                    try {
14208                        observer.onRemoveCompleted(packageName, succeded);
14209                    } catch (RemoteException e) {
14210                        Log.i(TAG, "Observer no longer exists.");
14211                    }
14212                } //end if observer
14213            } //end run
14214        });
14215    }
14216
14217    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14218        if (packageName == null) {
14219            Slog.w(TAG, "Attempt to delete null packageName.");
14220            return false;
14221        }
14222        PackageParser.Package p;
14223        synchronized (mPackages) {
14224            p = mPackages.get(packageName);
14225        }
14226        if (p == null) {
14227            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14228            return false;
14229        }
14230        final ApplicationInfo applicationInfo = p.applicationInfo;
14231        if (applicationInfo == null) {
14232            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14233            return false;
14234        }
14235        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14236        if (retCode < 0) {
14237            Slog.w(TAG, "Couldn't remove cache files for package: "
14238                       + packageName + " u" + userId);
14239            return false;
14240        }
14241        return true;
14242    }
14243
14244    @Override
14245    public void getPackageSizeInfo(final String packageName, int userHandle,
14246            final IPackageStatsObserver observer) {
14247        mContext.enforceCallingOrSelfPermission(
14248                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14249        if (packageName == null) {
14250            throw new IllegalArgumentException("Attempt to get size of null packageName");
14251        }
14252
14253        PackageStats stats = new PackageStats(packageName, userHandle);
14254
14255        /*
14256         * Queue up an async operation since the package measurement may take a
14257         * little while.
14258         */
14259        Message msg = mHandler.obtainMessage(INIT_COPY);
14260        msg.obj = new MeasureParams(stats, observer);
14261        mHandler.sendMessage(msg);
14262    }
14263
14264    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14265            PackageStats pStats) {
14266        if (packageName == null) {
14267            Slog.w(TAG, "Attempt to get size of null packageName.");
14268            return false;
14269        }
14270        PackageParser.Package p;
14271        boolean dataOnly = false;
14272        String libDirRoot = null;
14273        String asecPath = null;
14274        PackageSetting ps = null;
14275        synchronized (mPackages) {
14276            p = mPackages.get(packageName);
14277            ps = mSettings.mPackages.get(packageName);
14278            if(p == null) {
14279                dataOnly = true;
14280                if((ps == null) || (ps.pkg == null)) {
14281                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14282                    return false;
14283                }
14284                p = ps.pkg;
14285            }
14286            if (ps != null) {
14287                libDirRoot = ps.legacyNativeLibraryPathString;
14288            }
14289            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14290                final long token = Binder.clearCallingIdentity();
14291                try {
14292                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14293                    if (secureContainerId != null) {
14294                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14295                    }
14296                } finally {
14297                    Binder.restoreCallingIdentity(token);
14298                }
14299            }
14300        }
14301        String publicSrcDir = null;
14302        if(!dataOnly) {
14303            final ApplicationInfo applicationInfo = p.applicationInfo;
14304            if (applicationInfo == null) {
14305                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14306                return false;
14307            }
14308            if (p.isForwardLocked()) {
14309                publicSrcDir = applicationInfo.getBaseResourcePath();
14310            }
14311        }
14312        // TODO: extend to measure size of split APKs
14313        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14314        // not just the first level.
14315        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14316        // just the primary.
14317        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14318
14319        String apkPath;
14320        File packageDir = new File(p.codePath);
14321
14322        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14323            apkPath = packageDir.getAbsolutePath();
14324            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14325            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14326                libDirRoot = null;
14327            }
14328        } else {
14329            apkPath = p.baseCodePath;
14330        }
14331
14332        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14333                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14334        if (res < 0) {
14335            return false;
14336        }
14337
14338        // Fix-up for forward-locked applications in ASEC containers.
14339        if (!isExternal(p)) {
14340            pStats.codeSize += pStats.externalCodeSize;
14341            pStats.externalCodeSize = 0L;
14342        }
14343
14344        return true;
14345    }
14346
14347
14348    @Override
14349    public void addPackageToPreferred(String packageName) {
14350        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14351    }
14352
14353    @Override
14354    public void removePackageFromPreferred(String packageName) {
14355        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14356    }
14357
14358    @Override
14359    public List<PackageInfo> getPreferredPackages(int flags) {
14360        return new ArrayList<PackageInfo>();
14361    }
14362
14363    private int getUidTargetSdkVersionLockedLPr(int uid) {
14364        Object obj = mSettings.getUserIdLPr(uid);
14365        if (obj instanceof SharedUserSetting) {
14366            final SharedUserSetting sus = (SharedUserSetting) obj;
14367            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14368            final Iterator<PackageSetting> it = sus.packages.iterator();
14369            while (it.hasNext()) {
14370                final PackageSetting ps = it.next();
14371                if (ps.pkg != null) {
14372                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14373                    if (v < vers) vers = v;
14374                }
14375            }
14376            return vers;
14377        } else if (obj instanceof PackageSetting) {
14378            final PackageSetting ps = (PackageSetting) obj;
14379            if (ps.pkg != null) {
14380                return ps.pkg.applicationInfo.targetSdkVersion;
14381            }
14382        }
14383        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14384    }
14385
14386    @Override
14387    public void addPreferredActivity(IntentFilter filter, int match,
14388            ComponentName[] set, ComponentName activity, int userId) {
14389        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14390                "Adding preferred");
14391    }
14392
14393    private void addPreferredActivityInternal(IntentFilter filter, int match,
14394            ComponentName[] set, ComponentName activity, boolean always, int userId,
14395            String opname) {
14396        // writer
14397        int callingUid = Binder.getCallingUid();
14398        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14399        if (filter.countActions() == 0) {
14400            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14401            return;
14402        }
14403        synchronized (mPackages) {
14404            if (mContext.checkCallingOrSelfPermission(
14405                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14406                    != PackageManager.PERMISSION_GRANTED) {
14407                if (getUidTargetSdkVersionLockedLPr(callingUid)
14408                        < Build.VERSION_CODES.FROYO) {
14409                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14410                            + callingUid);
14411                    return;
14412                }
14413                mContext.enforceCallingOrSelfPermission(
14414                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14415            }
14416
14417            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14418            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14419                    + userId + ":");
14420            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14421            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14422            scheduleWritePackageRestrictionsLocked(userId);
14423        }
14424    }
14425
14426    @Override
14427    public void replacePreferredActivity(IntentFilter filter, int match,
14428            ComponentName[] set, ComponentName activity, int userId) {
14429        if (filter.countActions() != 1) {
14430            throw new IllegalArgumentException(
14431                    "replacePreferredActivity expects filter to have only 1 action.");
14432        }
14433        if (filter.countDataAuthorities() != 0
14434                || filter.countDataPaths() != 0
14435                || filter.countDataSchemes() > 1
14436                || filter.countDataTypes() != 0) {
14437            throw new IllegalArgumentException(
14438                    "replacePreferredActivity expects filter to have no data authorities, " +
14439                    "paths, or types; and at most one scheme.");
14440        }
14441
14442        final int callingUid = Binder.getCallingUid();
14443        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14444        synchronized (mPackages) {
14445            if (mContext.checkCallingOrSelfPermission(
14446                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14447                    != PackageManager.PERMISSION_GRANTED) {
14448                if (getUidTargetSdkVersionLockedLPr(callingUid)
14449                        < Build.VERSION_CODES.FROYO) {
14450                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14451                            + Binder.getCallingUid());
14452                    return;
14453                }
14454                mContext.enforceCallingOrSelfPermission(
14455                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14456            }
14457
14458            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14459            if (pir != null) {
14460                // Get all of the existing entries that exactly match this filter.
14461                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14462                if (existing != null && existing.size() == 1) {
14463                    PreferredActivity cur = existing.get(0);
14464                    if (DEBUG_PREFERRED) {
14465                        Slog.i(TAG, "Checking replace of preferred:");
14466                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14467                        if (!cur.mPref.mAlways) {
14468                            Slog.i(TAG, "  -- CUR; not mAlways!");
14469                        } else {
14470                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14471                            Slog.i(TAG, "  -- CUR: mSet="
14472                                    + Arrays.toString(cur.mPref.mSetComponents));
14473                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14474                            Slog.i(TAG, "  -- NEW: mMatch="
14475                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14476                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14477                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14478                        }
14479                    }
14480                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14481                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14482                            && cur.mPref.sameSet(set)) {
14483                        // Setting the preferred activity to what it happens to be already
14484                        if (DEBUG_PREFERRED) {
14485                            Slog.i(TAG, "Replacing with same preferred activity "
14486                                    + cur.mPref.mShortComponent + " for user "
14487                                    + userId + ":");
14488                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14489                        }
14490                        return;
14491                    }
14492                }
14493
14494                if (existing != null) {
14495                    if (DEBUG_PREFERRED) {
14496                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14497                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14498                    }
14499                    for (int i = 0; i < existing.size(); i++) {
14500                        PreferredActivity pa = existing.get(i);
14501                        if (DEBUG_PREFERRED) {
14502                            Slog.i(TAG, "Removing existing preferred activity "
14503                                    + pa.mPref.mComponent + ":");
14504                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14505                        }
14506                        pir.removeFilter(pa);
14507                    }
14508                }
14509            }
14510            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14511                    "Replacing preferred");
14512        }
14513    }
14514
14515    @Override
14516    public void clearPackagePreferredActivities(String packageName) {
14517        final int uid = Binder.getCallingUid();
14518        // writer
14519        synchronized (mPackages) {
14520            PackageParser.Package pkg = mPackages.get(packageName);
14521            if (pkg == null || pkg.applicationInfo.uid != uid) {
14522                if (mContext.checkCallingOrSelfPermission(
14523                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14524                        != PackageManager.PERMISSION_GRANTED) {
14525                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14526                            < Build.VERSION_CODES.FROYO) {
14527                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14528                                + Binder.getCallingUid());
14529                        return;
14530                    }
14531                    mContext.enforceCallingOrSelfPermission(
14532                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14533                }
14534            }
14535
14536            int user = UserHandle.getCallingUserId();
14537            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14538                scheduleWritePackageRestrictionsLocked(user);
14539            }
14540        }
14541    }
14542
14543    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14544    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14545        ArrayList<PreferredActivity> removed = null;
14546        boolean changed = false;
14547        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14548            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14549            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14550            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14551                continue;
14552            }
14553            Iterator<PreferredActivity> it = pir.filterIterator();
14554            while (it.hasNext()) {
14555                PreferredActivity pa = it.next();
14556                // Mark entry for removal only if it matches the package name
14557                // and the entry is of type "always".
14558                if (packageName == null ||
14559                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14560                                && pa.mPref.mAlways)) {
14561                    if (removed == null) {
14562                        removed = new ArrayList<PreferredActivity>();
14563                    }
14564                    removed.add(pa);
14565                }
14566            }
14567            if (removed != null) {
14568                for (int j=0; j<removed.size(); j++) {
14569                    PreferredActivity pa = removed.get(j);
14570                    pir.removeFilter(pa);
14571                }
14572                changed = true;
14573            }
14574        }
14575        return changed;
14576    }
14577
14578    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14579    private void clearIntentFilterVerificationsLPw(int userId) {
14580        final int packageCount = mPackages.size();
14581        for (int i = 0; i < packageCount; i++) {
14582            PackageParser.Package pkg = mPackages.valueAt(i);
14583            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14584        }
14585    }
14586
14587    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14588    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14589        if (userId == UserHandle.USER_ALL) {
14590            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14591                    sUserManager.getUserIds())) {
14592                for (int oneUserId : sUserManager.getUserIds()) {
14593                    scheduleWritePackageRestrictionsLocked(oneUserId);
14594                }
14595            }
14596        } else {
14597            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14598                scheduleWritePackageRestrictionsLocked(userId);
14599            }
14600        }
14601    }
14602
14603    void clearDefaultBrowserIfNeeded(String packageName) {
14604        for (int oneUserId : sUserManager.getUserIds()) {
14605            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14606            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14607            if (packageName.equals(defaultBrowserPackageName)) {
14608                setDefaultBrowserPackageName(null, oneUserId);
14609            }
14610        }
14611    }
14612
14613    @Override
14614    public void resetApplicationPreferences(int userId) {
14615        mContext.enforceCallingOrSelfPermission(
14616                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14617        // writer
14618        synchronized (mPackages) {
14619            final long identity = Binder.clearCallingIdentity();
14620            try {
14621                clearPackagePreferredActivitiesLPw(null, userId);
14622                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14623                // TODO: We have to reset the default SMS and Phone. This requires
14624                // significant refactoring to keep all default apps in the package
14625                // manager (cleaner but more work) or have the services provide
14626                // callbacks to the package manager to request a default app reset.
14627                applyFactoryDefaultBrowserLPw(userId);
14628                clearIntentFilterVerificationsLPw(userId);
14629                primeDomainVerificationsLPw(userId);
14630                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14631                scheduleWritePackageRestrictionsLocked(userId);
14632            } finally {
14633                Binder.restoreCallingIdentity(identity);
14634            }
14635        }
14636    }
14637
14638    @Override
14639    public int getPreferredActivities(List<IntentFilter> outFilters,
14640            List<ComponentName> outActivities, String packageName) {
14641
14642        int num = 0;
14643        final int userId = UserHandle.getCallingUserId();
14644        // reader
14645        synchronized (mPackages) {
14646            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14647            if (pir != null) {
14648                final Iterator<PreferredActivity> it = pir.filterIterator();
14649                while (it.hasNext()) {
14650                    final PreferredActivity pa = it.next();
14651                    if (packageName == null
14652                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14653                                    && pa.mPref.mAlways)) {
14654                        if (outFilters != null) {
14655                            outFilters.add(new IntentFilter(pa));
14656                        }
14657                        if (outActivities != null) {
14658                            outActivities.add(pa.mPref.mComponent);
14659                        }
14660                    }
14661                }
14662            }
14663        }
14664
14665        return num;
14666    }
14667
14668    @Override
14669    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14670            int userId) {
14671        int callingUid = Binder.getCallingUid();
14672        if (callingUid != Process.SYSTEM_UID) {
14673            throw new SecurityException(
14674                    "addPersistentPreferredActivity can only be run by the system");
14675        }
14676        if (filter.countActions() == 0) {
14677            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14678            return;
14679        }
14680        synchronized (mPackages) {
14681            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14682                    " :");
14683            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14684            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14685                    new PersistentPreferredActivity(filter, activity));
14686            scheduleWritePackageRestrictionsLocked(userId);
14687        }
14688    }
14689
14690    @Override
14691    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14692        int callingUid = Binder.getCallingUid();
14693        if (callingUid != Process.SYSTEM_UID) {
14694            throw new SecurityException(
14695                    "clearPackagePersistentPreferredActivities can only be run by the system");
14696        }
14697        ArrayList<PersistentPreferredActivity> removed = null;
14698        boolean changed = false;
14699        synchronized (mPackages) {
14700            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14701                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14702                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14703                        .valueAt(i);
14704                if (userId != thisUserId) {
14705                    continue;
14706                }
14707                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14708                while (it.hasNext()) {
14709                    PersistentPreferredActivity ppa = it.next();
14710                    // Mark entry for removal only if it matches the package name.
14711                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14712                        if (removed == null) {
14713                            removed = new ArrayList<PersistentPreferredActivity>();
14714                        }
14715                        removed.add(ppa);
14716                    }
14717                }
14718                if (removed != null) {
14719                    for (int j=0; j<removed.size(); j++) {
14720                        PersistentPreferredActivity ppa = removed.get(j);
14721                        ppir.removeFilter(ppa);
14722                    }
14723                    changed = true;
14724                }
14725            }
14726
14727            if (changed) {
14728                scheduleWritePackageRestrictionsLocked(userId);
14729            }
14730        }
14731    }
14732
14733    /**
14734     * Common machinery for picking apart a restored XML blob and passing
14735     * it to a caller-supplied functor to be applied to the running system.
14736     */
14737    private void restoreFromXml(XmlPullParser parser, int userId,
14738            String expectedStartTag, BlobXmlRestorer functor)
14739            throws IOException, XmlPullParserException {
14740        int type;
14741        while ((type = parser.next()) != XmlPullParser.START_TAG
14742                && type != XmlPullParser.END_DOCUMENT) {
14743        }
14744        if (type != XmlPullParser.START_TAG) {
14745            // oops didn't find a start tag?!
14746            if (DEBUG_BACKUP) {
14747                Slog.e(TAG, "Didn't find start tag during restore");
14748            }
14749            return;
14750        }
14751
14752        // this is supposed to be TAG_PREFERRED_BACKUP
14753        if (!expectedStartTag.equals(parser.getName())) {
14754            if (DEBUG_BACKUP) {
14755                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14756            }
14757            return;
14758        }
14759
14760        // skip interfering stuff, then we're aligned with the backing implementation
14761        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14762        functor.apply(parser, userId);
14763    }
14764
14765    private interface BlobXmlRestorer {
14766        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14767    }
14768
14769    /**
14770     * Non-Binder method, support for the backup/restore mechanism: write the
14771     * full set of preferred activities in its canonical XML format.  Returns the
14772     * XML output as a byte array, or null if there is none.
14773     */
14774    @Override
14775    public byte[] getPreferredActivityBackup(int userId) {
14776        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14777            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14778        }
14779
14780        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14781        try {
14782            final XmlSerializer serializer = new FastXmlSerializer();
14783            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14784            serializer.startDocument(null, true);
14785            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14786
14787            synchronized (mPackages) {
14788                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14789            }
14790
14791            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14792            serializer.endDocument();
14793            serializer.flush();
14794        } catch (Exception e) {
14795            if (DEBUG_BACKUP) {
14796                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14797            }
14798            return null;
14799        }
14800
14801        return dataStream.toByteArray();
14802    }
14803
14804    @Override
14805    public void restorePreferredActivities(byte[] backup, int userId) {
14806        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14807            throw new SecurityException("Only the system may call restorePreferredActivities()");
14808        }
14809
14810        try {
14811            final XmlPullParser parser = Xml.newPullParser();
14812            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14813            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14814                    new BlobXmlRestorer() {
14815                        @Override
14816                        public void apply(XmlPullParser parser, int userId)
14817                                throws XmlPullParserException, IOException {
14818                            synchronized (mPackages) {
14819                                mSettings.readPreferredActivitiesLPw(parser, userId);
14820                            }
14821                        }
14822                    } );
14823        } catch (Exception e) {
14824            if (DEBUG_BACKUP) {
14825                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14826            }
14827        }
14828    }
14829
14830    /**
14831     * Non-Binder method, support for the backup/restore mechanism: write the
14832     * default browser (etc) settings in its canonical XML format.  Returns the default
14833     * browser XML representation as a byte array, or null if there is none.
14834     */
14835    @Override
14836    public byte[] getDefaultAppsBackup(int userId) {
14837        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14838            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14839        }
14840
14841        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14842        try {
14843            final XmlSerializer serializer = new FastXmlSerializer();
14844            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14845            serializer.startDocument(null, true);
14846            serializer.startTag(null, TAG_DEFAULT_APPS);
14847
14848            synchronized (mPackages) {
14849                mSettings.writeDefaultAppsLPr(serializer, userId);
14850            }
14851
14852            serializer.endTag(null, TAG_DEFAULT_APPS);
14853            serializer.endDocument();
14854            serializer.flush();
14855        } catch (Exception e) {
14856            if (DEBUG_BACKUP) {
14857                Slog.e(TAG, "Unable to write default apps for backup", e);
14858            }
14859            return null;
14860        }
14861
14862        return dataStream.toByteArray();
14863    }
14864
14865    @Override
14866    public void restoreDefaultApps(byte[] backup, int userId) {
14867        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14868            throw new SecurityException("Only the system may call restoreDefaultApps()");
14869        }
14870
14871        try {
14872            final XmlPullParser parser = Xml.newPullParser();
14873            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14874            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14875                    new BlobXmlRestorer() {
14876                        @Override
14877                        public void apply(XmlPullParser parser, int userId)
14878                                throws XmlPullParserException, IOException {
14879                            synchronized (mPackages) {
14880                                mSettings.readDefaultAppsLPw(parser, userId);
14881                            }
14882                        }
14883                    } );
14884        } catch (Exception e) {
14885            if (DEBUG_BACKUP) {
14886                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14887            }
14888        }
14889    }
14890
14891    @Override
14892    public byte[] getIntentFilterVerificationBackup(int userId) {
14893        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14894            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14895        }
14896
14897        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14898        try {
14899            final XmlSerializer serializer = new FastXmlSerializer();
14900            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14901            serializer.startDocument(null, true);
14902            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14903
14904            synchronized (mPackages) {
14905                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14906            }
14907
14908            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14909            serializer.endDocument();
14910            serializer.flush();
14911        } catch (Exception e) {
14912            if (DEBUG_BACKUP) {
14913                Slog.e(TAG, "Unable to write default apps for backup", e);
14914            }
14915            return null;
14916        }
14917
14918        return dataStream.toByteArray();
14919    }
14920
14921    @Override
14922    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14923        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14924            throw new SecurityException("Only the system may call restorePreferredActivities()");
14925        }
14926
14927        try {
14928            final XmlPullParser parser = Xml.newPullParser();
14929            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14930            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14931                    new BlobXmlRestorer() {
14932                        @Override
14933                        public void apply(XmlPullParser parser, int userId)
14934                                throws XmlPullParserException, IOException {
14935                            synchronized (mPackages) {
14936                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14937                                mSettings.writeLPr();
14938                            }
14939                        }
14940                    } );
14941        } catch (Exception e) {
14942            if (DEBUG_BACKUP) {
14943                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14944            }
14945        }
14946    }
14947
14948    @Override
14949    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14950            int sourceUserId, int targetUserId, int flags) {
14951        mContext.enforceCallingOrSelfPermission(
14952                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14953        int callingUid = Binder.getCallingUid();
14954        enforceOwnerRights(ownerPackage, callingUid);
14955        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14956        if (intentFilter.countActions() == 0) {
14957            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14958            return;
14959        }
14960        synchronized (mPackages) {
14961            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14962                    ownerPackage, targetUserId, flags);
14963            CrossProfileIntentResolver resolver =
14964                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14965            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14966            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14967            if (existing != null) {
14968                int size = existing.size();
14969                for (int i = 0; i < size; i++) {
14970                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14971                        return;
14972                    }
14973                }
14974            }
14975            resolver.addFilter(newFilter);
14976            scheduleWritePackageRestrictionsLocked(sourceUserId);
14977        }
14978    }
14979
14980    @Override
14981    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14982        mContext.enforceCallingOrSelfPermission(
14983                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14984        int callingUid = Binder.getCallingUid();
14985        enforceOwnerRights(ownerPackage, callingUid);
14986        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14987        synchronized (mPackages) {
14988            CrossProfileIntentResolver resolver =
14989                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14990            ArraySet<CrossProfileIntentFilter> set =
14991                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14992            for (CrossProfileIntentFilter filter : set) {
14993                if (filter.getOwnerPackage().equals(ownerPackage)) {
14994                    resolver.removeFilter(filter);
14995                }
14996            }
14997            scheduleWritePackageRestrictionsLocked(sourceUserId);
14998        }
14999    }
15000
15001    // Enforcing that callingUid is owning pkg on userId
15002    private void enforceOwnerRights(String pkg, int callingUid) {
15003        // The system owns everything.
15004        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15005            return;
15006        }
15007        int callingUserId = UserHandle.getUserId(callingUid);
15008        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15009        if (pi == null) {
15010            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15011                    + callingUserId);
15012        }
15013        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15014            throw new SecurityException("Calling uid " + callingUid
15015                    + " does not own package " + pkg);
15016        }
15017    }
15018
15019    @Override
15020    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15021        Intent intent = new Intent(Intent.ACTION_MAIN);
15022        intent.addCategory(Intent.CATEGORY_HOME);
15023
15024        final int callingUserId = UserHandle.getCallingUserId();
15025        List<ResolveInfo> list = queryIntentActivities(intent, null,
15026                PackageManager.GET_META_DATA, callingUserId);
15027        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15028                true, false, false, callingUserId);
15029
15030        allHomeCandidates.clear();
15031        if (list != null) {
15032            for (ResolveInfo ri : list) {
15033                allHomeCandidates.add(ri);
15034            }
15035        }
15036        return (preferred == null || preferred.activityInfo == null)
15037                ? null
15038                : new ComponentName(preferred.activityInfo.packageName,
15039                        preferred.activityInfo.name);
15040    }
15041
15042    @Override
15043    public void setApplicationEnabledSetting(String appPackageName,
15044            int newState, int flags, int userId, String callingPackage) {
15045        if (!sUserManager.exists(userId)) return;
15046        if (callingPackage == null) {
15047            callingPackage = Integer.toString(Binder.getCallingUid());
15048        }
15049        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15050    }
15051
15052    @Override
15053    public void setComponentEnabledSetting(ComponentName componentName,
15054            int newState, int flags, int userId) {
15055        if (!sUserManager.exists(userId)) return;
15056        setEnabledSetting(componentName.getPackageName(),
15057                componentName.getClassName(), newState, flags, userId, null);
15058    }
15059
15060    private void setEnabledSetting(final String packageName, String className, int newState,
15061            final int flags, int userId, String callingPackage) {
15062        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15063              || newState == COMPONENT_ENABLED_STATE_ENABLED
15064              || newState == COMPONENT_ENABLED_STATE_DISABLED
15065              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15066              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15067            throw new IllegalArgumentException("Invalid new component state: "
15068                    + newState);
15069        }
15070        PackageSetting pkgSetting;
15071        final int uid = Binder.getCallingUid();
15072        final int permission = mContext.checkCallingOrSelfPermission(
15073                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15074        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15075        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15076        boolean sendNow = false;
15077        boolean isApp = (className == null);
15078        String componentName = isApp ? packageName : className;
15079        int packageUid = -1;
15080        ArrayList<String> components;
15081
15082        // writer
15083        synchronized (mPackages) {
15084            pkgSetting = mSettings.mPackages.get(packageName);
15085            if (pkgSetting == null) {
15086                if (className == null) {
15087                    throw new IllegalArgumentException(
15088                            "Unknown package: " + packageName);
15089                }
15090                throw new IllegalArgumentException(
15091                        "Unknown component: " + packageName
15092                        + "/" + className);
15093            }
15094            // Allow root and verify that userId is not being specified by a different user
15095            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15096                throw new SecurityException(
15097                        "Permission Denial: attempt to change component state from pid="
15098                        + Binder.getCallingPid()
15099                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15100            }
15101            if (className == null) {
15102                // We're dealing with an application/package level state change
15103                if (pkgSetting.getEnabled(userId) == newState) {
15104                    // Nothing to do
15105                    return;
15106                }
15107                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15108                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15109                    // Don't care about who enables an app.
15110                    callingPackage = null;
15111                }
15112                pkgSetting.setEnabled(newState, userId, callingPackage);
15113                // pkgSetting.pkg.mSetEnabled = newState;
15114            } else {
15115                // We're dealing with a component level state change
15116                // First, verify that this is a valid class name.
15117                PackageParser.Package pkg = pkgSetting.pkg;
15118                if (pkg == null || !pkg.hasComponentClassName(className)) {
15119                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
15120                        throw new IllegalArgumentException("Component class " + className
15121                                + " does not exist in " + packageName);
15122                    } else {
15123                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15124                                + className + " does not exist in " + packageName);
15125                    }
15126                }
15127                switch (newState) {
15128                case COMPONENT_ENABLED_STATE_ENABLED:
15129                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15130                        return;
15131                    }
15132                    break;
15133                case COMPONENT_ENABLED_STATE_DISABLED:
15134                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15135                        return;
15136                    }
15137                    break;
15138                case COMPONENT_ENABLED_STATE_DEFAULT:
15139                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15140                        return;
15141                    }
15142                    break;
15143                default:
15144                    Slog.e(TAG, "Invalid new component state: " + newState);
15145                    return;
15146                }
15147            }
15148            scheduleWritePackageRestrictionsLocked(userId);
15149            components = mPendingBroadcasts.get(userId, packageName);
15150            final boolean newPackage = components == null;
15151            if (newPackage) {
15152                components = new ArrayList<String>();
15153            }
15154            if (!components.contains(componentName)) {
15155                components.add(componentName);
15156            }
15157            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15158                sendNow = true;
15159                // Purge entry from pending broadcast list if another one exists already
15160                // since we are sending one right away.
15161                mPendingBroadcasts.remove(userId, packageName);
15162            } else {
15163                if (newPackage) {
15164                    mPendingBroadcasts.put(userId, packageName, components);
15165                }
15166                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15167                    // Schedule a message
15168                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15169                }
15170            }
15171        }
15172
15173        long callingId = Binder.clearCallingIdentity();
15174        try {
15175            if (sendNow) {
15176                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15177                sendPackageChangedBroadcast(packageName,
15178                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15179            }
15180        } finally {
15181            Binder.restoreCallingIdentity(callingId);
15182        }
15183    }
15184
15185    private void sendPackageChangedBroadcast(String packageName,
15186            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15187        if (DEBUG_INSTALL)
15188            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15189                    + componentNames);
15190        Bundle extras = new Bundle(4);
15191        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15192        String nameList[] = new String[componentNames.size()];
15193        componentNames.toArray(nameList);
15194        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15195        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15196        extras.putInt(Intent.EXTRA_UID, packageUid);
15197        // If this is not reporting a change of the overall package, then only send it
15198        // to registered receivers.  We don't want to launch a swath of apps for every
15199        // little component state change.
15200        final int flags = !componentNames.contains(packageName)
15201                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15202        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15203                new int[] {UserHandle.getUserId(packageUid)});
15204    }
15205
15206    @Override
15207    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15208        if (!sUserManager.exists(userId)) return;
15209        final int uid = Binder.getCallingUid();
15210        final int permission = mContext.checkCallingOrSelfPermission(
15211                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15212        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15213        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15214        // writer
15215        synchronized (mPackages) {
15216            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15217                    allowedByPermission, uid, userId)) {
15218                scheduleWritePackageRestrictionsLocked(userId);
15219            }
15220        }
15221    }
15222
15223    @Override
15224    public String getInstallerPackageName(String packageName) {
15225        // reader
15226        synchronized (mPackages) {
15227            return mSettings.getInstallerPackageNameLPr(packageName);
15228        }
15229    }
15230
15231    @Override
15232    public int getApplicationEnabledSetting(String packageName, int userId) {
15233        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15234        int uid = Binder.getCallingUid();
15235        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15236        // reader
15237        synchronized (mPackages) {
15238            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15239        }
15240    }
15241
15242    @Override
15243    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15244        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15245        int uid = Binder.getCallingUid();
15246        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15247        // reader
15248        synchronized (mPackages) {
15249            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15250        }
15251    }
15252
15253    @Override
15254    public void enterSafeMode() {
15255        enforceSystemOrRoot("Only the system can request entering safe mode");
15256
15257        if (!mSystemReady) {
15258            mSafeMode = true;
15259        }
15260    }
15261
15262    @Override
15263    public void systemReady() {
15264        mSystemReady = true;
15265
15266        // Read the compatibilty setting when the system is ready.
15267        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15268                mContext.getContentResolver(),
15269                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15270        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15271        if (DEBUG_SETTINGS) {
15272            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15273        }
15274
15275        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15276
15277        synchronized (mPackages) {
15278            // Verify that all of the preferred activity components actually
15279            // exist.  It is possible for applications to be updated and at
15280            // that point remove a previously declared activity component that
15281            // had been set as a preferred activity.  We try to clean this up
15282            // the next time we encounter that preferred activity, but it is
15283            // possible for the user flow to never be able to return to that
15284            // situation so here we do a sanity check to make sure we haven't
15285            // left any junk around.
15286            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15287            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15288                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15289                removed.clear();
15290                for (PreferredActivity pa : pir.filterSet()) {
15291                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15292                        removed.add(pa);
15293                    }
15294                }
15295                if (removed.size() > 0) {
15296                    for (int r=0; r<removed.size(); r++) {
15297                        PreferredActivity pa = removed.get(r);
15298                        Slog.w(TAG, "Removing dangling preferred activity: "
15299                                + pa.mPref.mComponent);
15300                        pir.removeFilter(pa);
15301                    }
15302                    mSettings.writePackageRestrictionsLPr(
15303                            mSettings.mPreferredActivities.keyAt(i));
15304                }
15305            }
15306
15307            for (int userId : UserManagerService.getInstance().getUserIds()) {
15308                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15309                    grantPermissionsUserIds = ArrayUtils.appendInt(
15310                            grantPermissionsUserIds, userId);
15311                }
15312            }
15313        }
15314        sUserManager.systemReady();
15315
15316        // If we upgraded grant all default permissions before kicking off.
15317        for (int userId : grantPermissionsUserIds) {
15318            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15319        }
15320
15321        // Kick off any messages waiting for system ready
15322        if (mPostSystemReadyMessages != null) {
15323            for (Message msg : mPostSystemReadyMessages) {
15324                msg.sendToTarget();
15325            }
15326            mPostSystemReadyMessages = null;
15327        }
15328
15329        // Watch for external volumes that come and go over time
15330        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15331        storage.registerListener(mStorageListener);
15332
15333        mInstallerService.systemReady();
15334        mPackageDexOptimizer.systemReady();
15335
15336        MountServiceInternal mountServiceInternal = LocalServices.getService(
15337                MountServiceInternal.class);
15338        mountServiceInternal.addExternalStoragePolicy(
15339                new MountServiceInternal.ExternalStorageMountPolicy() {
15340            @Override
15341            public int getMountMode(int uid, String packageName) {
15342                if (Process.isIsolated(uid)) {
15343                    return Zygote.MOUNT_EXTERNAL_NONE;
15344                }
15345                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15346                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15347                }
15348                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15349                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15350                }
15351                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15352                    return Zygote.MOUNT_EXTERNAL_READ;
15353                }
15354                return Zygote.MOUNT_EXTERNAL_WRITE;
15355            }
15356
15357            @Override
15358            public boolean hasExternalStorage(int uid, String packageName) {
15359                return true;
15360            }
15361        });
15362    }
15363
15364    @Override
15365    public boolean isSafeMode() {
15366        return mSafeMode;
15367    }
15368
15369    @Override
15370    public boolean hasSystemUidErrors() {
15371        return mHasSystemUidErrors;
15372    }
15373
15374    static String arrayToString(int[] array) {
15375        StringBuffer buf = new StringBuffer(128);
15376        buf.append('[');
15377        if (array != null) {
15378            for (int i=0; i<array.length; i++) {
15379                if (i > 0) buf.append(", ");
15380                buf.append(array[i]);
15381            }
15382        }
15383        buf.append(']');
15384        return buf.toString();
15385    }
15386
15387    static class DumpState {
15388        public static final int DUMP_LIBS = 1 << 0;
15389        public static final int DUMP_FEATURES = 1 << 1;
15390        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15391        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15392        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15393        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15394        public static final int DUMP_PERMISSIONS = 1 << 6;
15395        public static final int DUMP_PACKAGES = 1 << 7;
15396        public static final int DUMP_SHARED_USERS = 1 << 8;
15397        public static final int DUMP_MESSAGES = 1 << 9;
15398        public static final int DUMP_PROVIDERS = 1 << 10;
15399        public static final int DUMP_VERIFIERS = 1 << 11;
15400        public static final int DUMP_PREFERRED = 1 << 12;
15401        public static final int DUMP_PREFERRED_XML = 1 << 13;
15402        public static final int DUMP_KEYSETS = 1 << 14;
15403        public static final int DUMP_VERSION = 1 << 15;
15404        public static final int DUMP_INSTALLS = 1 << 16;
15405        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15406        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15407
15408        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15409
15410        private int mTypes;
15411
15412        private int mOptions;
15413
15414        private boolean mTitlePrinted;
15415
15416        private SharedUserSetting mSharedUser;
15417
15418        public boolean isDumping(int type) {
15419            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15420                return true;
15421            }
15422
15423            return (mTypes & type) != 0;
15424        }
15425
15426        public void setDump(int type) {
15427            mTypes |= type;
15428        }
15429
15430        public boolean isOptionEnabled(int option) {
15431            return (mOptions & option) != 0;
15432        }
15433
15434        public void setOptionEnabled(int option) {
15435            mOptions |= option;
15436        }
15437
15438        public boolean onTitlePrinted() {
15439            final boolean printed = mTitlePrinted;
15440            mTitlePrinted = true;
15441            return printed;
15442        }
15443
15444        public boolean getTitlePrinted() {
15445            return mTitlePrinted;
15446        }
15447
15448        public void setTitlePrinted(boolean enabled) {
15449            mTitlePrinted = enabled;
15450        }
15451
15452        public SharedUserSetting getSharedUser() {
15453            return mSharedUser;
15454        }
15455
15456        public void setSharedUser(SharedUserSetting user) {
15457            mSharedUser = user;
15458        }
15459    }
15460
15461    @Override
15462    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15463            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15464        (new PackageManagerShellCommand(this)).exec(
15465                this, in, out, err, args, resultReceiver);
15466    }
15467
15468    @Override
15469    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15470        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15471                != PackageManager.PERMISSION_GRANTED) {
15472            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15473                    + Binder.getCallingPid()
15474                    + ", uid=" + Binder.getCallingUid()
15475                    + " without permission "
15476                    + android.Manifest.permission.DUMP);
15477            return;
15478        }
15479
15480        DumpState dumpState = new DumpState();
15481        boolean fullPreferred = false;
15482        boolean checkin = false;
15483
15484        String packageName = null;
15485        ArraySet<String> permissionNames = null;
15486
15487        int opti = 0;
15488        while (opti < args.length) {
15489            String opt = args[opti];
15490            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15491                break;
15492            }
15493            opti++;
15494
15495            if ("-a".equals(opt)) {
15496                // Right now we only know how to print all.
15497            } else if ("-h".equals(opt)) {
15498                pw.println("Package manager dump options:");
15499                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15500                pw.println("    --checkin: dump for a checkin");
15501                pw.println("    -f: print details of intent filters");
15502                pw.println("    -h: print this help");
15503                pw.println("  cmd may be one of:");
15504                pw.println("    l[ibraries]: list known shared libraries");
15505                pw.println("    f[eatures]: list device features");
15506                pw.println("    k[eysets]: print known keysets");
15507                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15508                pw.println("    perm[issions]: dump permissions");
15509                pw.println("    permission [name ...]: dump declaration and use of given permission");
15510                pw.println("    pref[erred]: print preferred package settings");
15511                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15512                pw.println("    prov[iders]: dump content providers");
15513                pw.println("    p[ackages]: dump installed packages");
15514                pw.println("    s[hared-users]: dump shared user IDs");
15515                pw.println("    m[essages]: print collected runtime messages");
15516                pw.println("    v[erifiers]: print package verifier info");
15517                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15518                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15519                pw.println("    version: print database version info");
15520                pw.println("    write: write current settings now");
15521                pw.println("    installs: details about install sessions");
15522                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15523                pw.println("    <package.name>: info about given package");
15524                return;
15525            } else if ("--checkin".equals(opt)) {
15526                checkin = true;
15527            } else if ("-f".equals(opt)) {
15528                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15529            } else {
15530                pw.println("Unknown argument: " + opt + "; use -h for help");
15531            }
15532        }
15533
15534        // Is the caller requesting to dump a particular piece of data?
15535        if (opti < args.length) {
15536            String cmd = args[opti];
15537            opti++;
15538            // Is this a package name?
15539            if ("android".equals(cmd) || cmd.contains(".")) {
15540                packageName = cmd;
15541                // When dumping a single package, we always dump all of its
15542                // filter information since the amount of data will be reasonable.
15543                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15544            } else if ("check-permission".equals(cmd)) {
15545                if (opti >= args.length) {
15546                    pw.println("Error: check-permission missing permission argument");
15547                    return;
15548                }
15549                String perm = args[opti];
15550                opti++;
15551                if (opti >= args.length) {
15552                    pw.println("Error: check-permission missing package argument");
15553                    return;
15554                }
15555                String pkg = args[opti];
15556                opti++;
15557                int user = UserHandle.getUserId(Binder.getCallingUid());
15558                if (opti < args.length) {
15559                    try {
15560                        user = Integer.parseInt(args[opti]);
15561                    } catch (NumberFormatException e) {
15562                        pw.println("Error: check-permission user argument is not a number: "
15563                                + args[opti]);
15564                        return;
15565                    }
15566                }
15567                pw.println(checkPermission(perm, pkg, user));
15568                return;
15569            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15570                dumpState.setDump(DumpState.DUMP_LIBS);
15571            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15572                dumpState.setDump(DumpState.DUMP_FEATURES);
15573            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15574                if (opti >= args.length) {
15575                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15576                            | DumpState.DUMP_SERVICE_RESOLVERS
15577                            | DumpState.DUMP_RECEIVER_RESOLVERS
15578                            | DumpState.DUMP_CONTENT_RESOLVERS);
15579                } else {
15580                    while (opti < args.length) {
15581                        String name = args[opti];
15582                        if ("a".equals(name) || "activity".equals(name)) {
15583                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15584                        } else if ("s".equals(name) || "service".equals(name)) {
15585                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15586                        } else if ("r".equals(name) || "receiver".equals(name)) {
15587                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15588                        } else if ("c".equals(name) || "content".equals(name)) {
15589                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15590                        } else {
15591                            pw.println("Error: unknown resolver table type: " + name);
15592                            return;
15593                        }
15594                        opti++;
15595                    }
15596                }
15597            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15598                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15599            } else if ("permission".equals(cmd)) {
15600                if (opti >= args.length) {
15601                    pw.println("Error: permission requires permission name");
15602                    return;
15603                }
15604                permissionNames = new ArraySet<>();
15605                while (opti < args.length) {
15606                    permissionNames.add(args[opti]);
15607                    opti++;
15608                }
15609                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15610                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15611            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15612                dumpState.setDump(DumpState.DUMP_PREFERRED);
15613            } else if ("preferred-xml".equals(cmd)) {
15614                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15615                if (opti < args.length && "--full".equals(args[opti])) {
15616                    fullPreferred = true;
15617                    opti++;
15618                }
15619            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15620                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15621            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15622                dumpState.setDump(DumpState.DUMP_PACKAGES);
15623            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15624                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15625            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15626                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15627            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15628                dumpState.setDump(DumpState.DUMP_MESSAGES);
15629            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15630                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15631            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15632                    || "intent-filter-verifiers".equals(cmd)) {
15633                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15634            } else if ("version".equals(cmd)) {
15635                dumpState.setDump(DumpState.DUMP_VERSION);
15636            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15637                dumpState.setDump(DumpState.DUMP_KEYSETS);
15638            } else if ("installs".equals(cmd)) {
15639                dumpState.setDump(DumpState.DUMP_INSTALLS);
15640            } else if ("write".equals(cmd)) {
15641                synchronized (mPackages) {
15642                    mSettings.writeLPr();
15643                    pw.println("Settings written.");
15644                    return;
15645                }
15646            }
15647        }
15648
15649        if (checkin) {
15650            pw.println("vers,1");
15651        }
15652
15653        // reader
15654        synchronized (mPackages) {
15655            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15656                if (!checkin) {
15657                    if (dumpState.onTitlePrinted())
15658                        pw.println();
15659                    pw.println("Database versions:");
15660                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15661                }
15662            }
15663
15664            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15665                if (!checkin) {
15666                    if (dumpState.onTitlePrinted())
15667                        pw.println();
15668                    pw.println("Verifiers:");
15669                    pw.print("  Required: ");
15670                    pw.print(mRequiredVerifierPackage);
15671                    pw.print(" (uid=");
15672                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15673                    pw.println(")");
15674                } else if (mRequiredVerifierPackage != null) {
15675                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15676                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15677                }
15678            }
15679
15680            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15681                    packageName == null) {
15682                if (mIntentFilterVerifierComponent != null) {
15683                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15684                    if (!checkin) {
15685                        if (dumpState.onTitlePrinted())
15686                            pw.println();
15687                        pw.println("Intent Filter Verifier:");
15688                        pw.print("  Using: ");
15689                        pw.print(verifierPackageName);
15690                        pw.print(" (uid=");
15691                        pw.print(getPackageUid(verifierPackageName, 0));
15692                        pw.println(")");
15693                    } else if (verifierPackageName != null) {
15694                        pw.print("ifv,"); pw.print(verifierPackageName);
15695                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15696                    }
15697                } else {
15698                    pw.println();
15699                    pw.println("No Intent Filter Verifier available!");
15700                }
15701            }
15702
15703            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15704                boolean printedHeader = false;
15705                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15706                while (it.hasNext()) {
15707                    String name = it.next();
15708                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15709                    if (!checkin) {
15710                        if (!printedHeader) {
15711                            if (dumpState.onTitlePrinted())
15712                                pw.println();
15713                            pw.println("Libraries:");
15714                            printedHeader = true;
15715                        }
15716                        pw.print("  ");
15717                    } else {
15718                        pw.print("lib,");
15719                    }
15720                    pw.print(name);
15721                    if (!checkin) {
15722                        pw.print(" -> ");
15723                    }
15724                    if (ent.path != null) {
15725                        if (!checkin) {
15726                            pw.print("(jar) ");
15727                            pw.print(ent.path);
15728                        } else {
15729                            pw.print(",jar,");
15730                            pw.print(ent.path);
15731                        }
15732                    } else {
15733                        if (!checkin) {
15734                            pw.print("(apk) ");
15735                            pw.print(ent.apk);
15736                        } else {
15737                            pw.print(",apk,");
15738                            pw.print(ent.apk);
15739                        }
15740                    }
15741                    pw.println();
15742                }
15743            }
15744
15745            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15746                if (dumpState.onTitlePrinted())
15747                    pw.println();
15748                if (!checkin) {
15749                    pw.println("Features:");
15750                }
15751                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15752                while (it.hasNext()) {
15753                    String name = it.next();
15754                    if (!checkin) {
15755                        pw.print("  ");
15756                    } else {
15757                        pw.print("feat,");
15758                    }
15759                    pw.println(name);
15760                }
15761            }
15762
15763            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15764                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15765                        : "Activity Resolver Table:", "  ", packageName,
15766                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15767                    dumpState.setTitlePrinted(true);
15768                }
15769            }
15770            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15771                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15772                        : "Receiver Resolver Table:", "  ", packageName,
15773                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15774                    dumpState.setTitlePrinted(true);
15775                }
15776            }
15777            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15778                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15779                        : "Service Resolver Table:", "  ", packageName,
15780                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15781                    dumpState.setTitlePrinted(true);
15782                }
15783            }
15784            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15785                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15786                        : "Provider Resolver Table:", "  ", packageName,
15787                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15788                    dumpState.setTitlePrinted(true);
15789                }
15790            }
15791
15792            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15793                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15794                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15795                    int user = mSettings.mPreferredActivities.keyAt(i);
15796                    if (pir.dump(pw,
15797                            dumpState.getTitlePrinted()
15798                                ? "\nPreferred Activities User " + user + ":"
15799                                : "Preferred Activities User " + user + ":", "  ",
15800                            packageName, true, false)) {
15801                        dumpState.setTitlePrinted(true);
15802                    }
15803                }
15804            }
15805
15806            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15807                pw.flush();
15808                FileOutputStream fout = new FileOutputStream(fd);
15809                BufferedOutputStream str = new BufferedOutputStream(fout);
15810                XmlSerializer serializer = new FastXmlSerializer();
15811                try {
15812                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15813                    serializer.startDocument(null, true);
15814                    serializer.setFeature(
15815                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15816                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15817                    serializer.endDocument();
15818                    serializer.flush();
15819                } catch (IllegalArgumentException e) {
15820                    pw.println("Failed writing: " + e);
15821                } catch (IllegalStateException e) {
15822                    pw.println("Failed writing: " + e);
15823                } catch (IOException e) {
15824                    pw.println("Failed writing: " + e);
15825                }
15826            }
15827
15828            if (!checkin
15829                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15830                    && packageName == null) {
15831                pw.println();
15832                int count = mSettings.mPackages.size();
15833                if (count == 0) {
15834                    pw.println("No applications!");
15835                    pw.println();
15836                } else {
15837                    final String prefix = "  ";
15838                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15839                    if (allPackageSettings.size() == 0) {
15840                        pw.println("No domain preferred apps!");
15841                        pw.println();
15842                    } else {
15843                        pw.println("App verification status:");
15844                        pw.println();
15845                        count = 0;
15846                        for (PackageSetting ps : allPackageSettings) {
15847                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15848                            if (ivi == null || ivi.getPackageName() == null) continue;
15849                            pw.println(prefix + "Package: " + ivi.getPackageName());
15850                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15851                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15852                            pw.println();
15853                            count++;
15854                        }
15855                        if (count == 0) {
15856                            pw.println(prefix + "No app verification established.");
15857                            pw.println();
15858                        }
15859                        for (int userId : sUserManager.getUserIds()) {
15860                            pw.println("App linkages for user " + userId + ":");
15861                            pw.println();
15862                            count = 0;
15863                            for (PackageSetting ps : allPackageSettings) {
15864                                final long status = ps.getDomainVerificationStatusForUser(userId);
15865                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15866                                    continue;
15867                                }
15868                                pw.println(prefix + "Package: " + ps.name);
15869                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15870                                String statusStr = IntentFilterVerificationInfo.
15871                                        getStatusStringFromValue(status);
15872                                pw.println(prefix + "Status:  " + statusStr);
15873                                pw.println();
15874                                count++;
15875                            }
15876                            if (count == 0) {
15877                                pw.println(prefix + "No configured app linkages.");
15878                                pw.println();
15879                            }
15880                        }
15881                    }
15882                }
15883            }
15884
15885            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15886                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15887                if (packageName == null && permissionNames == null) {
15888                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15889                        if (iperm == 0) {
15890                            if (dumpState.onTitlePrinted())
15891                                pw.println();
15892                            pw.println("AppOp Permissions:");
15893                        }
15894                        pw.print("  AppOp Permission ");
15895                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15896                        pw.println(":");
15897                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15898                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15899                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15900                        }
15901                    }
15902                }
15903            }
15904
15905            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15906                boolean printedSomething = false;
15907                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15908                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15909                        continue;
15910                    }
15911                    if (!printedSomething) {
15912                        if (dumpState.onTitlePrinted())
15913                            pw.println();
15914                        pw.println("Registered ContentProviders:");
15915                        printedSomething = true;
15916                    }
15917                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15918                    pw.print("    "); pw.println(p.toString());
15919                }
15920                printedSomething = false;
15921                for (Map.Entry<String, PackageParser.Provider> entry :
15922                        mProvidersByAuthority.entrySet()) {
15923                    PackageParser.Provider p = entry.getValue();
15924                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15925                        continue;
15926                    }
15927                    if (!printedSomething) {
15928                        if (dumpState.onTitlePrinted())
15929                            pw.println();
15930                        pw.println("ContentProvider Authorities:");
15931                        printedSomething = true;
15932                    }
15933                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15934                    pw.print("    "); pw.println(p.toString());
15935                    if (p.info != null && p.info.applicationInfo != null) {
15936                        final String appInfo = p.info.applicationInfo.toString();
15937                        pw.print("      applicationInfo="); pw.println(appInfo);
15938                    }
15939                }
15940            }
15941
15942            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15943                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15944            }
15945
15946            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15947                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15948            }
15949
15950            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15951                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15952            }
15953
15954            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15955                // XXX should handle packageName != null by dumping only install data that
15956                // the given package is involved with.
15957                if (dumpState.onTitlePrinted()) pw.println();
15958                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15959            }
15960
15961            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15962                if (dumpState.onTitlePrinted()) pw.println();
15963                mSettings.dumpReadMessagesLPr(pw, dumpState);
15964
15965                pw.println();
15966                pw.println("Package warning messages:");
15967                BufferedReader in = null;
15968                String line = null;
15969                try {
15970                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15971                    while ((line = in.readLine()) != null) {
15972                        if (line.contains("ignored: updated version")) continue;
15973                        pw.println(line);
15974                    }
15975                } catch (IOException ignored) {
15976                } finally {
15977                    IoUtils.closeQuietly(in);
15978                }
15979            }
15980
15981            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15982                BufferedReader in = null;
15983                String line = null;
15984                try {
15985                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15986                    while ((line = in.readLine()) != null) {
15987                        if (line.contains("ignored: updated version")) continue;
15988                        pw.print("msg,");
15989                        pw.println(line);
15990                    }
15991                } catch (IOException ignored) {
15992                } finally {
15993                    IoUtils.closeQuietly(in);
15994                }
15995            }
15996        }
15997    }
15998
15999    private String dumpDomainString(String packageName) {
16000        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16001        List<IntentFilter> filters = getAllIntentFilters(packageName);
16002
16003        ArraySet<String> result = new ArraySet<>();
16004        if (iviList.size() > 0) {
16005            for (IntentFilterVerificationInfo ivi : iviList) {
16006                for (String host : ivi.getDomains()) {
16007                    result.add(host);
16008                }
16009            }
16010        }
16011        if (filters != null && filters.size() > 0) {
16012            for (IntentFilter filter : filters) {
16013                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16014                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16015                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16016                    result.addAll(filter.getHostsList());
16017                }
16018            }
16019        }
16020
16021        StringBuilder sb = new StringBuilder(result.size() * 16);
16022        for (String domain : result) {
16023            if (sb.length() > 0) sb.append(" ");
16024            sb.append(domain);
16025        }
16026        return sb.toString();
16027    }
16028
16029    // ------- apps on sdcard specific code -------
16030    static final boolean DEBUG_SD_INSTALL = false;
16031
16032    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16033
16034    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16035
16036    private boolean mMediaMounted = false;
16037
16038    static String getEncryptKey() {
16039        try {
16040            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16041                    SD_ENCRYPTION_KEYSTORE_NAME);
16042            if (sdEncKey == null) {
16043                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16044                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16045                if (sdEncKey == null) {
16046                    Slog.e(TAG, "Failed to create encryption keys");
16047                    return null;
16048                }
16049            }
16050            return sdEncKey;
16051        } catch (NoSuchAlgorithmException nsae) {
16052            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16053            return null;
16054        } catch (IOException ioe) {
16055            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16056            return null;
16057        }
16058    }
16059
16060    /*
16061     * Update media status on PackageManager.
16062     */
16063    @Override
16064    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16065        int callingUid = Binder.getCallingUid();
16066        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16067            throw new SecurityException("Media status can only be updated by the system");
16068        }
16069        // reader; this apparently protects mMediaMounted, but should probably
16070        // be a different lock in that case.
16071        synchronized (mPackages) {
16072            Log.i(TAG, "Updating external media status from "
16073                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16074                    + (mediaStatus ? "mounted" : "unmounted"));
16075            if (DEBUG_SD_INSTALL)
16076                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16077                        + ", mMediaMounted=" + mMediaMounted);
16078            if (mediaStatus == mMediaMounted) {
16079                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16080                        : 0, -1);
16081                mHandler.sendMessage(msg);
16082                return;
16083            }
16084            mMediaMounted = mediaStatus;
16085        }
16086        // Queue up an async operation since the package installation may take a
16087        // little while.
16088        mHandler.post(new Runnable() {
16089            public void run() {
16090                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16091            }
16092        });
16093    }
16094
16095    /**
16096     * Called by MountService when the initial ASECs to scan are available.
16097     * Should block until all the ASEC containers are finished being scanned.
16098     */
16099    public void scanAvailableAsecs() {
16100        updateExternalMediaStatusInner(true, false, false);
16101        if (mShouldRestoreconData) {
16102            SELinuxMMAC.setRestoreconDone();
16103            mShouldRestoreconData = false;
16104        }
16105    }
16106
16107    /*
16108     * Collect information of applications on external media, map them against
16109     * existing containers and update information based on current mount status.
16110     * Please note that we always have to report status if reportStatus has been
16111     * set to true especially when unloading packages.
16112     */
16113    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16114            boolean externalStorage) {
16115        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16116        int[] uidArr = EmptyArray.INT;
16117
16118        final String[] list = PackageHelper.getSecureContainerList();
16119        if (ArrayUtils.isEmpty(list)) {
16120            Log.i(TAG, "No secure containers found");
16121        } else {
16122            // Process list of secure containers and categorize them
16123            // as active or stale based on their package internal state.
16124
16125            // reader
16126            synchronized (mPackages) {
16127                for (String cid : list) {
16128                    // Leave stages untouched for now; installer service owns them
16129                    if (PackageInstallerService.isStageName(cid)) continue;
16130
16131                    if (DEBUG_SD_INSTALL)
16132                        Log.i(TAG, "Processing container " + cid);
16133                    String pkgName = getAsecPackageName(cid);
16134                    if (pkgName == null) {
16135                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16136                        continue;
16137                    }
16138                    if (DEBUG_SD_INSTALL)
16139                        Log.i(TAG, "Looking for pkg : " + pkgName);
16140
16141                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16142                    if (ps == null) {
16143                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16144                        continue;
16145                    }
16146
16147                    /*
16148                     * Skip packages that are not external if we're unmounting
16149                     * external storage.
16150                     */
16151                    if (externalStorage && !isMounted && !isExternal(ps)) {
16152                        continue;
16153                    }
16154
16155                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16156                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16157                    // The package status is changed only if the code path
16158                    // matches between settings and the container id.
16159                    if (ps.codePathString != null
16160                            && ps.codePathString.startsWith(args.getCodePath())) {
16161                        if (DEBUG_SD_INSTALL) {
16162                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16163                                    + " at code path: " + ps.codePathString);
16164                        }
16165
16166                        // We do have a valid package installed on sdcard
16167                        processCids.put(args, ps.codePathString);
16168                        final int uid = ps.appId;
16169                        if (uid != -1) {
16170                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16171                        }
16172                    } else {
16173                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16174                                + ps.codePathString);
16175                    }
16176                }
16177            }
16178
16179            Arrays.sort(uidArr);
16180        }
16181
16182        // Process packages with valid entries.
16183        if (isMounted) {
16184            if (DEBUG_SD_INSTALL)
16185                Log.i(TAG, "Loading packages");
16186            loadMediaPackages(processCids, uidArr, externalStorage);
16187            startCleaningPackages();
16188            mInstallerService.onSecureContainersAvailable();
16189        } else {
16190            if (DEBUG_SD_INSTALL)
16191                Log.i(TAG, "Unloading packages");
16192            unloadMediaPackages(processCids, uidArr, reportStatus);
16193        }
16194    }
16195
16196    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16197            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16198        final int size = infos.size();
16199        final String[] packageNames = new String[size];
16200        final int[] packageUids = new int[size];
16201        for (int i = 0; i < size; i++) {
16202            final ApplicationInfo info = infos.get(i);
16203            packageNames[i] = info.packageName;
16204            packageUids[i] = info.uid;
16205        }
16206        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16207                finishedReceiver);
16208    }
16209
16210    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16211            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16212        sendResourcesChangedBroadcast(mediaStatus, replacing,
16213                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16214    }
16215
16216    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16217            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16218        int size = pkgList.length;
16219        if (size > 0) {
16220            // Send broadcasts here
16221            Bundle extras = new Bundle();
16222            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16223            if (uidArr != null) {
16224                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16225            }
16226            if (replacing) {
16227                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16228            }
16229            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16230                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16231            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16232        }
16233    }
16234
16235   /*
16236     * Look at potentially valid container ids from processCids If package
16237     * information doesn't match the one on record or package scanning fails,
16238     * the cid is added to list of removeCids. We currently don't delete stale
16239     * containers.
16240     */
16241    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16242            boolean externalStorage) {
16243        ArrayList<String> pkgList = new ArrayList<String>();
16244        Set<AsecInstallArgs> keys = processCids.keySet();
16245
16246        for (AsecInstallArgs args : keys) {
16247            String codePath = processCids.get(args);
16248            if (DEBUG_SD_INSTALL)
16249                Log.i(TAG, "Loading container : " + args.cid);
16250            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16251            try {
16252                // Make sure there are no container errors first.
16253                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16254                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16255                            + " when installing from sdcard");
16256                    continue;
16257                }
16258                // Check code path here.
16259                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16260                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16261                            + " does not match one in settings " + codePath);
16262                    continue;
16263                }
16264                // Parse package
16265                int parseFlags = mDefParseFlags;
16266                if (args.isExternalAsec()) {
16267                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16268                }
16269                if (args.isFwdLocked()) {
16270                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16271                }
16272
16273                synchronized (mInstallLock) {
16274                    PackageParser.Package pkg = null;
16275                    try {
16276                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16277                    } catch (PackageManagerException e) {
16278                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16279                    }
16280                    // Scan the package
16281                    if (pkg != null) {
16282                        /*
16283                         * TODO why is the lock being held? doPostInstall is
16284                         * called in other places without the lock. This needs
16285                         * to be straightened out.
16286                         */
16287                        // writer
16288                        synchronized (mPackages) {
16289                            retCode = PackageManager.INSTALL_SUCCEEDED;
16290                            pkgList.add(pkg.packageName);
16291                            // Post process args
16292                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16293                                    pkg.applicationInfo.uid);
16294                        }
16295                    } else {
16296                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16297                    }
16298                }
16299
16300            } finally {
16301                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16302                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16303                }
16304            }
16305        }
16306        // writer
16307        synchronized (mPackages) {
16308            // If the platform SDK has changed since the last time we booted,
16309            // we need to re-grant app permission to catch any new ones that
16310            // appear. This is really a hack, and means that apps can in some
16311            // cases get permissions that the user didn't initially explicitly
16312            // allow... it would be nice to have some better way to handle
16313            // this situation.
16314            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16315                    : mSettings.getInternalVersion();
16316            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16317                    : StorageManager.UUID_PRIVATE_INTERNAL;
16318
16319            int updateFlags = UPDATE_PERMISSIONS_ALL;
16320            if (ver.sdkVersion != mSdkVersion) {
16321                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16322                        + mSdkVersion + "; regranting permissions for external");
16323                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16324            }
16325            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16326
16327            // Yay, everything is now upgraded
16328            ver.forceCurrent();
16329
16330            // can downgrade to reader
16331            // Persist settings
16332            mSettings.writeLPr();
16333        }
16334        // Send a broadcast to let everyone know we are done processing
16335        if (pkgList.size() > 0) {
16336            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16337        }
16338    }
16339
16340   /*
16341     * Utility method to unload a list of specified containers
16342     */
16343    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16344        // Just unmount all valid containers.
16345        for (AsecInstallArgs arg : cidArgs) {
16346            synchronized (mInstallLock) {
16347                arg.doPostDeleteLI(false);
16348           }
16349       }
16350   }
16351
16352    /*
16353     * Unload packages mounted on external media. This involves deleting package
16354     * data from internal structures, sending broadcasts about diabled packages,
16355     * gc'ing to free up references, unmounting all secure containers
16356     * corresponding to packages on external media, and posting a
16357     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16358     * that we always have to post this message if status has been requested no
16359     * matter what.
16360     */
16361    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16362            final boolean reportStatus) {
16363        if (DEBUG_SD_INSTALL)
16364            Log.i(TAG, "unloading media packages");
16365        ArrayList<String> pkgList = new ArrayList<String>();
16366        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16367        final Set<AsecInstallArgs> keys = processCids.keySet();
16368        for (AsecInstallArgs args : keys) {
16369            String pkgName = args.getPackageName();
16370            if (DEBUG_SD_INSTALL)
16371                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16372            // Delete package internally
16373            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16374            synchronized (mInstallLock) {
16375                boolean res = deletePackageLI(pkgName, null, false, null, null,
16376                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16377                if (res) {
16378                    pkgList.add(pkgName);
16379                } else {
16380                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16381                    failedList.add(args);
16382                }
16383            }
16384        }
16385
16386        // reader
16387        synchronized (mPackages) {
16388            // We didn't update the settings after removing each package;
16389            // write them now for all packages.
16390            mSettings.writeLPr();
16391        }
16392
16393        // We have to absolutely send UPDATED_MEDIA_STATUS only
16394        // after confirming that all the receivers processed the ordered
16395        // broadcast when packages get disabled, force a gc to clean things up.
16396        // and unload all the containers.
16397        if (pkgList.size() > 0) {
16398            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16399                    new IIntentReceiver.Stub() {
16400                public void performReceive(Intent intent, int resultCode, String data,
16401                        Bundle extras, boolean ordered, boolean sticky,
16402                        int sendingUser) throws RemoteException {
16403                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16404                            reportStatus ? 1 : 0, 1, keys);
16405                    mHandler.sendMessage(msg);
16406                }
16407            });
16408        } else {
16409            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16410                    keys);
16411            mHandler.sendMessage(msg);
16412        }
16413    }
16414
16415    private void loadPrivatePackages(final VolumeInfo vol) {
16416        mHandler.post(new Runnable() {
16417            @Override
16418            public void run() {
16419                loadPrivatePackagesInner(vol);
16420            }
16421        });
16422    }
16423
16424    private void loadPrivatePackagesInner(VolumeInfo vol) {
16425        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16426        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16427
16428        final VersionInfo ver;
16429        final List<PackageSetting> packages;
16430        synchronized (mPackages) {
16431            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16432            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16433        }
16434
16435        for (PackageSetting ps : packages) {
16436            synchronized (mInstallLock) {
16437                final PackageParser.Package pkg;
16438                try {
16439                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16440                    loaded.add(pkg.applicationInfo);
16441                } catch (PackageManagerException e) {
16442                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16443                }
16444
16445                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16446                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16447                }
16448            }
16449        }
16450
16451        synchronized (mPackages) {
16452            int updateFlags = UPDATE_PERMISSIONS_ALL;
16453            if (ver.sdkVersion != mSdkVersion) {
16454                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16455                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16456                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16457            }
16458            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16459
16460            // Yay, everything is now upgraded
16461            ver.forceCurrent();
16462
16463            mSettings.writeLPr();
16464        }
16465
16466        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16467        sendResourcesChangedBroadcast(true, false, loaded, null);
16468    }
16469
16470    private void unloadPrivatePackages(final VolumeInfo vol) {
16471        mHandler.post(new Runnable() {
16472            @Override
16473            public void run() {
16474                unloadPrivatePackagesInner(vol);
16475            }
16476        });
16477    }
16478
16479    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16480        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16481        synchronized (mInstallLock) {
16482        synchronized (mPackages) {
16483            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16484            for (PackageSetting ps : packages) {
16485                if (ps.pkg == null) continue;
16486
16487                final ApplicationInfo info = ps.pkg.applicationInfo;
16488                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16489                if (deletePackageLI(ps.name, null, false, null, null,
16490                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16491                    unloaded.add(info);
16492                } else {
16493                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16494                }
16495            }
16496
16497            mSettings.writeLPr();
16498        }
16499        }
16500
16501        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16502        sendResourcesChangedBroadcast(false, false, unloaded, null);
16503    }
16504
16505    /**
16506     * Examine all users present on given mounted volume, and destroy data
16507     * belonging to users that are no longer valid, or whose user ID has been
16508     * recycled.
16509     */
16510    private void reconcileUsers(String volumeUuid) {
16511        final File[] files = FileUtils
16512                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16513        for (File file : files) {
16514            if (!file.isDirectory()) continue;
16515
16516            final int userId;
16517            final UserInfo info;
16518            try {
16519                userId = Integer.parseInt(file.getName());
16520                info = sUserManager.getUserInfo(userId);
16521            } catch (NumberFormatException e) {
16522                Slog.w(TAG, "Invalid user directory " + file);
16523                continue;
16524            }
16525
16526            boolean destroyUser = false;
16527            if (info == null) {
16528                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16529                        + " because no matching user was found");
16530                destroyUser = true;
16531            } else {
16532                try {
16533                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16534                } catch (IOException e) {
16535                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16536                            + " because we failed to enforce serial number: " + e);
16537                    destroyUser = true;
16538                }
16539            }
16540
16541            if (destroyUser) {
16542                synchronized (mInstallLock) {
16543                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16544                }
16545            }
16546        }
16547
16548        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16549        final UserManager um = mContext.getSystemService(UserManager.class);
16550        for (UserInfo user : um.getUsers()) {
16551            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16552            if (userDir.exists()) continue;
16553
16554            try {
16555                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16556                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16557            } catch (IOException e) {
16558                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16559            }
16560        }
16561    }
16562
16563    /**
16564     * Examine all apps present on given mounted volume, and destroy apps that
16565     * aren't expected, either due to uninstallation or reinstallation on
16566     * another volume.
16567     */
16568    private void reconcileApps(String volumeUuid) {
16569        final File[] files = FileUtils
16570                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16571        for (File file : files) {
16572            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16573                    && !PackageInstallerService.isStageName(file.getName());
16574            if (!isPackage) {
16575                // Ignore entries which are not packages
16576                continue;
16577            }
16578
16579            boolean destroyApp = false;
16580            String packageName = null;
16581            try {
16582                final PackageLite pkg = PackageParser.parsePackageLite(file,
16583                        PackageParser.PARSE_MUST_BE_APK);
16584                packageName = pkg.packageName;
16585
16586                synchronized (mPackages) {
16587                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16588                    if (ps == null) {
16589                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16590                                + volumeUuid + " because we found no install record");
16591                        destroyApp = true;
16592                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16593                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16594                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16595                        destroyApp = true;
16596                    }
16597                }
16598
16599            } catch (PackageParserException e) {
16600                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16601                destroyApp = true;
16602            }
16603
16604            if (destroyApp) {
16605                synchronized (mInstallLock) {
16606                    if (packageName != null) {
16607                        removeDataDirsLI(volumeUuid, packageName);
16608                    }
16609                    if (file.isDirectory()) {
16610                        mInstaller.rmPackageDir(file.getAbsolutePath());
16611                    } else {
16612                        file.delete();
16613                    }
16614                }
16615            }
16616        }
16617    }
16618
16619    private void unfreezePackage(String packageName) {
16620        synchronized (mPackages) {
16621            final PackageSetting ps = mSettings.mPackages.get(packageName);
16622            if (ps != null) {
16623                ps.frozen = false;
16624            }
16625        }
16626    }
16627
16628    @Override
16629    public int movePackage(final String packageName, final String volumeUuid) {
16630        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16631
16632        final int moveId = mNextMoveId.getAndIncrement();
16633        mHandler.post(new Runnable() {
16634            @Override
16635            public void run() {
16636                try {
16637                    movePackageInternal(packageName, volumeUuid, moveId);
16638                } catch (PackageManagerException e) {
16639                    Slog.w(TAG, "Failed to move " + packageName, e);
16640                    mMoveCallbacks.notifyStatusChanged(moveId,
16641                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16642                }
16643            }
16644        });
16645        return moveId;
16646    }
16647
16648    private void movePackageInternal(final String packageName, final String volumeUuid,
16649            final int moveId) throws PackageManagerException {
16650        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16651        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16652        final PackageManager pm = mContext.getPackageManager();
16653
16654        final boolean currentAsec;
16655        final String currentVolumeUuid;
16656        final File codeFile;
16657        final String installerPackageName;
16658        final String packageAbiOverride;
16659        final int appId;
16660        final String seinfo;
16661        final String label;
16662
16663        // reader
16664        synchronized (mPackages) {
16665            final PackageParser.Package pkg = mPackages.get(packageName);
16666            final PackageSetting ps = mSettings.mPackages.get(packageName);
16667            if (pkg == null || ps == null) {
16668                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16669            }
16670
16671            if (pkg.applicationInfo.isSystemApp()) {
16672                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16673                        "Cannot move system application");
16674            }
16675
16676            if (pkg.applicationInfo.isExternalAsec()) {
16677                currentAsec = true;
16678                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16679            } else if (pkg.applicationInfo.isForwardLocked()) {
16680                currentAsec = true;
16681                currentVolumeUuid = "forward_locked";
16682            } else {
16683                currentAsec = false;
16684                currentVolumeUuid = ps.volumeUuid;
16685
16686                final File probe = new File(pkg.codePath);
16687                final File probeOat = new File(probe, "oat");
16688                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16689                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16690                            "Move only supported for modern cluster style installs");
16691                }
16692            }
16693
16694            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16695                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16696                        "Package already moved to " + volumeUuid);
16697            }
16698
16699            if (ps.frozen) {
16700                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16701                        "Failed to move already frozen package");
16702            }
16703            ps.frozen = true;
16704
16705            codeFile = new File(pkg.codePath);
16706            installerPackageName = ps.installerPackageName;
16707            packageAbiOverride = ps.cpuAbiOverrideString;
16708            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16709            seinfo = pkg.applicationInfo.seinfo;
16710            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16711        }
16712
16713        // Now that we're guarded by frozen state, kill app during move
16714        final long token = Binder.clearCallingIdentity();
16715        try {
16716            killApplication(packageName, appId, "move pkg");
16717        } finally {
16718            Binder.restoreCallingIdentity(token);
16719        }
16720
16721        final Bundle extras = new Bundle();
16722        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16723        extras.putString(Intent.EXTRA_TITLE, label);
16724        mMoveCallbacks.notifyCreated(moveId, extras);
16725
16726        int installFlags;
16727        final boolean moveCompleteApp;
16728        final File measurePath;
16729
16730        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16731            installFlags = INSTALL_INTERNAL;
16732            moveCompleteApp = !currentAsec;
16733            measurePath = Environment.getDataAppDirectory(volumeUuid);
16734        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16735            installFlags = INSTALL_EXTERNAL;
16736            moveCompleteApp = false;
16737            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16738        } else {
16739            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16740            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16741                    || !volume.isMountedWritable()) {
16742                unfreezePackage(packageName);
16743                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16744                        "Move location not mounted private volume");
16745            }
16746
16747            Preconditions.checkState(!currentAsec);
16748
16749            installFlags = INSTALL_INTERNAL;
16750            moveCompleteApp = true;
16751            measurePath = Environment.getDataAppDirectory(volumeUuid);
16752        }
16753
16754        final PackageStats stats = new PackageStats(null, -1);
16755        synchronized (mInstaller) {
16756            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16757                unfreezePackage(packageName);
16758                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16759                        "Failed to measure package size");
16760            }
16761        }
16762
16763        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16764                + stats.dataSize);
16765
16766        final long startFreeBytes = measurePath.getFreeSpace();
16767        final long sizeBytes;
16768        if (moveCompleteApp) {
16769            sizeBytes = stats.codeSize + stats.dataSize;
16770        } else {
16771            sizeBytes = stats.codeSize;
16772        }
16773
16774        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16775            unfreezePackage(packageName);
16776            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16777                    "Not enough free space to move");
16778        }
16779
16780        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16781
16782        final CountDownLatch installedLatch = new CountDownLatch(1);
16783        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16784            @Override
16785            public void onUserActionRequired(Intent intent) throws RemoteException {
16786                throw new IllegalStateException();
16787            }
16788
16789            @Override
16790            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16791                    Bundle extras) throws RemoteException {
16792                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16793                        + PackageManager.installStatusToString(returnCode, msg));
16794
16795                installedLatch.countDown();
16796
16797                // Regardless of success or failure of the move operation,
16798                // always unfreeze the package
16799                unfreezePackage(packageName);
16800
16801                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16802                switch (status) {
16803                    case PackageInstaller.STATUS_SUCCESS:
16804                        mMoveCallbacks.notifyStatusChanged(moveId,
16805                                PackageManager.MOVE_SUCCEEDED);
16806                        break;
16807                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16808                        mMoveCallbacks.notifyStatusChanged(moveId,
16809                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16810                        break;
16811                    default:
16812                        mMoveCallbacks.notifyStatusChanged(moveId,
16813                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16814                        break;
16815                }
16816            }
16817        };
16818
16819        final MoveInfo move;
16820        if (moveCompleteApp) {
16821            // Kick off a thread to report progress estimates
16822            new Thread() {
16823                @Override
16824                public void run() {
16825                    while (true) {
16826                        try {
16827                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16828                                break;
16829                            }
16830                        } catch (InterruptedException ignored) {
16831                        }
16832
16833                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16834                        final int progress = 10 + (int) MathUtils.constrain(
16835                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16836                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16837                    }
16838                }
16839            }.start();
16840
16841            final String dataAppName = codeFile.getName();
16842            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16843                    dataAppName, appId, seinfo);
16844        } else {
16845            move = null;
16846        }
16847
16848        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16849
16850        final Message msg = mHandler.obtainMessage(INIT_COPY);
16851        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16852        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16853                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16854        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16855        msg.obj = params;
16856
16857        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16858                System.identityHashCode(msg.obj));
16859        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16860                System.identityHashCode(msg.obj));
16861
16862        mHandler.sendMessage(msg);
16863    }
16864
16865    @Override
16866    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16867        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16868
16869        final int realMoveId = mNextMoveId.getAndIncrement();
16870        final Bundle extras = new Bundle();
16871        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16872        mMoveCallbacks.notifyCreated(realMoveId, extras);
16873
16874        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16875            @Override
16876            public void onCreated(int moveId, Bundle extras) {
16877                // Ignored
16878            }
16879
16880            @Override
16881            public void onStatusChanged(int moveId, int status, long estMillis) {
16882                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16883            }
16884        };
16885
16886        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16887        storage.setPrimaryStorageUuid(volumeUuid, callback);
16888        return realMoveId;
16889    }
16890
16891    @Override
16892    public int getMoveStatus(int moveId) {
16893        mContext.enforceCallingOrSelfPermission(
16894                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16895        return mMoveCallbacks.mLastStatus.get(moveId);
16896    }
16897
16898    @Override
16899    public void registerMoveCallback(IPackageMoveObserver callback) {
16900        mContext.enforceCallingOrSelfPermission(
16901                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16902        mMoveCallbacks.register(callback);
16903    }
16904
16905    @Override
16906    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16907        mContext.enforceCallingOrSelfPermission(
16908                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16909        mMoveCallbacks.unregister(callback);
16910    }
16911
16912    @Override
16913    public boolean setInstallLocation(int loc) {
16914        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16915                null);
16916        if (getInstallLocation() == loc) {
16917            return true;
16918        }
16919        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16920                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16921            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16922                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16923            return true;
16924        }
16925        return false;
16926   }
16927
16928    @Override
16929    public int getInstallLocation() {
16930        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16931                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16932                PackageHelper.APP_INSTALL_AUTO);
16933    }
16934
16935    /** Called by UserManagerService */
16936    void cleanUpUser(UserManagerService userManager, int userHandle) {
16937        synchronized (mPackages) {
16938            mDirtyUsers.remove(userHandle);
16939            mUserNeedsBadging.delete(userHandle);
16940            mSettings.removeUserLPw(userHandle);
16941            mPendingBroadcasts.remove(userHandle);
16942            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16943        }
16944        synchronized (mInstallLock) {
16945            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16946            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16947                final String volumeUuid = vol.getFsUuid();
16948                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16949                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16950            }
16951            synchronized (mPackages) {
16952                removeUnusedPackagesLILPw(userManager, userHandle);
16953            }
16954        }
16955    }
16956
16957    /**
16958     * We're removing userHandle and would like to remove any downloaded packages
16959     * that are no longer in use by any other user.
16960     * @param userHandle the user being removed
16961     */
16962    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16963        final boolean DEBUG_CLEAN_APKS = false;
16964        int [] users = userManager.getUserIds();
16965        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16966        while (psit.hasNext()) {
16967            PackageSetting ps = psit.next();
16968            if (ps.pkg == null) {
16969                continue;
16970            }
16971            final String packageName = ps.pkg.packageName;
16972            // Skip over if system app
16973            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16974                continue;
16975            }
16976            if (DEBUG_CLEAN_APKS) {
16977                Slog.i(TAG, "Checking package " + packageName);
16978            }
16979            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16980            if (keep) {
16981                if (DEBUG_CLEAN_APKS) {
16982                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16983                }
16984            } else {
16985                for (int i = 0; i < users.length; i++) {
16986                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16987                        keep = true;
16988                        if (DEBUG_CLEAN_APKS) {
16989                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
16990                                    + users[i]);
16991                        }
16992                        break;
16993                    }
16994                }
16995            }
16996            if (!keep) {
16997                if (DEBUG_CLEAN_APKS) {
16998                    Slog.i(TAG, "  Removing package " + packageName);
16999                }
17000                mHandler.post(new Runnable() {
17001                    public void run() {
17002                        deletePackageX(packageName, userHandle, 0);
17003                    } //end run
17004                });
17005            }
17006        }
17007    }
17008
17009    /** Called by UserManagerService */
17010    void createNewUser(int userHandle) {
17011        synchronized (mInstallLock) {
17012            mInstaller.createUserConfig(userHandle);
17013            mSettings.createNewUserLI(this, mInstaller, userHandle);
17014        }
17015        synchronized (mPackages) {
17016            applyFactoryDefaultBrowserLPw(userHandle);
17017            primeDomainVerificationsLPw(userHandle);
17018        }
17019    }
17020
17021    void newUserCreated(final int userHandle) {
17022        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17023        // If permission review for legacy apps is required, we represent
17024        // dagerous permissions for such apps as always granted runtime
17025        // permissions to keep per user flag state whether review is needed.
17026        // Hence, if a new user is added we have to propagate dangerous
17027        // permission grants for these legacy apps.
17028        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17029            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17030                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17031        }
17032    }
17033
17034    @Override
17035    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17036        mContext.enforceCallingOrSelfPermission(
17037                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17038                "Only package verification agents can read the verifier device identity");
17039
17040        synchronized (mPackages) {
17041            return mSettings.getVerifierDeviceIdentityLPw();
17042        }
17043    }
17044
17045    @Override
17046    public void setPermissionEnforced(String permission, boolean enforced) {
17047        // TODO: Now that we no longer change GID for storage, this should to away.
17048        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17049                "setPermissionEnforced");
17050        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17051            synchronized (mPackages) {
17052                if (mSettings.mReadExternalStorageEnforced == null
17053                        || mSettings.mReadExternalStorageEnforced != enforced) {
17054                    mSettings.mReadExternalStorageEnforced = enforced;
17055                    mSettings.writeLPr();
17056                }
17057            }
17058            // kill any non-foreground processes so we restart them and
17059            // grant/revoke the GID.
17060            final IActivityManager am = ActivityManagerNative.getDefault();
17061            if (am != null) {
17062                final long token = Binder.clearCallingIdentity();
17063                try {
17064                    am.killProcessesBelowForeground("setPermissionEnforcement");
17065                } catch (RemoteException e) {
17066                } finally {
17067                    Binder.restoreCallingIdentity(token);
17068                }
17069            }
17070        } else {
17071            throw new IllegalArgumentException("No selective enforcement for " + permission);
17072        }
17073    }
17074
17075    @Override
17076    @Deprecated
17077    public boolean isPermissionEnforced(String permission) {
17078        return true;
17079    }
17080
17081    @Override
17082    public boolean isStorageLow() {
17083        final long token = Binder.clearCallingIdentity();
17084        try {
17085            final DeviceStorageMonitorInternal
17086                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17087            if (dsm != null) {
17088                return dsm.isMemoryLow();
17089            } else {
17090                return false;
17091            }
17092        } finally {
17093            Binder.restoreCallingIdentity(token);
17094        }
17095    }
17096
17097    @Override
17098    public IPackageInstaller getPackageInstaller() {
17099        return mInstallerService;
17100    }
17101
17102    private boolean userNeedsBadging(int userId) {
17103        int index = mUserNeedsBadging.indexOfKey(userId);
17104        if (index < 0) {
17105            final UserInfo userInfo;
17106            final long token = Binder.clearCallingIdentity();
17107            try {
17108                userInfo = sUserManager.getUserInfo(userId);
17109            } finally {
17110                Binder.restoreCallingIdentity(token);
17111            }
17112            final boolean b;
17113            if (userInfo != null && userInfo.isManagedProfile()) {
17114                b = true;
17115            } else {
17116                b = false;
17117            }
17118            mUserNeedsBadging.put(userId, b);
17119            return b;
17120        }
17121        return mUserNeedsBadging.valueAt(index);
17122    }
17123
17124    @Override
17125    public KeySet getKeySetByAlias(String packageName, String alias) {
17126        if (packageName == null || alias == null) {
17127            return null;
17128        }
17129        synchronized(mPackages) {
17130            final PackageParser.Package pkg = mPackages.get(packageName);
17131            if (pkg == null) {
17132                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17133                throw new IllegalArgumentException("Unknown package: " + packageName);
17134            }
17135            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17136            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17137        }
17138    }
17139
17140    @Override
17141    public KeySet getSigningKeySet(String packageName) {
17142        if (packageName == null) {
17143            return null;
17144        }
17145        synchronized(mPackages) {
17146            final PackageParser.Package pkg = mPackages.get(packageName);
17147            if (pkg == null) {
17148                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17149                throw new IllegalArgumentException("Unknown package: " + packageName);
17150            }
17151            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17152                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17153                throw new SecurityException("May not access signing KeySet of other apps.");
17154            }
17155            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17156            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17157        }
17158    }
17159
17160    @Override
17161    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17162        if (packageName == null || ks == null) {
17163            return false;
17164        }
17165        synchronized(mPackages) {
17166            final PackageParser.Package pkg = mPackages.get(packageName);
17167            if (pkg == null) {
17168                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17169                throw new IllegalArgumentException("Unknown package: " + packageName);
17170            }
17171            IBinder ksh = ks.getToken();
17172            if (ksh instanceof KeySetHandle) {
17173                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17174                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17175            }
17176            return false;
17177        }
17178    }
17179
17180    @Override
17181    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17182        if (packageName == null || ks == null) {
17183            return false;
17184        }
17185        synchronized(mPackages) {
17186            final PackageParser.Package pkg = mPackages.get(packageName);
17187            if (pkg == null) {
17188                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17189                throw new IllegalArgumentException("Unknown package: " + packageName);
17190            }
17191            IBinder ksh = ks.getToken();
17192            if (ksh instanceof KeySetHandle) {
17193                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17194                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17195            }
17196            return false;
17197        }
17198    }
17199
17200    private void deletePackageIfUnusedLPr(final String packageName) {
17201        PackageSetting ps = mSettings.mPackages.get(packageName);
17202        if (ps == null) {
17203            return;
17204        }
17205        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17206            // TODO Implement atomic delete if package is unused
17207            // It is currently possible that the package will be deleted even if it is installed
17208            // after this method returns.
17209            mHandler.post(new Runnable() {
17210                public void run() {
17211                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17212                }
17213            });
17214        }
17215    }
17216
17217    /**
17218     * Check and throw if the given before/after packages would be considered a
17219     * downgrade.
17220     */
17221    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17222            throws PackageManagerException {
17223        if (after.versionCode < before.mVersionCode) {
17224            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17225                    "Update version code " + after.versionCode + " is older than current "
17226                    + before.mVersionCode);
17227        } else if (after.versionCode == before.mVersionCode) {
17228            if (after.baseRevisionCode < before.baseRevisionCode) {
17229                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17230                        "Update base revision code " + after.baseRevisionCode
17231                        + " is older than current " + before.baseRevisionCode);
17232            }
17233
17234            if (!ArrayUtils.isEmpty(after.splitNames)) {
17235                for (int i = 0; i < after.splitNames.length; i++) {
17236                    final String splitName = after.splitNames[i];
17237                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17238                    if (j != -1) {
17239                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17240                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17241                                    "Update split " + splitName + " revision code "
17242                                    + after.splitRevisionCodes[i] + " is older than current "
17243                                    + before.splitRevisionCodes[j]);
17244                        }
17245                    }
17246                }
17247            }
17248        }
17249    }
17250
17251    private static class MoveCallbacks extends Handler {
17252        private static final int MSG_CREATED = 1;
17253        private static final int MSG_STATUS_CHANGED = 2;
17254
17255        private final RemoteCallbackList<IPackageMoveObserver>
17256                mCallbacks = new RemoteCallbackList<>();
17257
17258        private final SparseIntArray mLastStatus = new SparseIntArray();
17259
17260        public MoveCallbacks(Looper looper) {
17261            super(looper);
17262        }
17263
17264        public void register(IPackageMoveObserver callback) {
17265            mCallbacks.register(callback);
17266        }
17267
17268        public void unregister(IPackageMoveObserver callback) {
17269            mCallbacks.unregister(callback);
17270        }
17271
17272        @Override
17273        public void handleMessage(Message msg) {
17274            final SomeArgs args = (SomeArgs) msg.obj;
17275            final int n = mCallbacks.beginBroadcast();
17276            for (int i = 0; i < n; i++) {
17277                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17278                try {
17279                    invokeCallback(callback, msg.what, args);
17280                } catch (RemoteException ignored) {
17281                }
17282            }
17283            mCallbacks.finishBroadcast();
17284            args.recycle();
17285        }
17286
17287        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17288                throws RemoteException {
17289            switch (what) {
17290                case MSG_CREATED: {
17291                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17292                    break;
17293                }
17294                case MSG_STATUS_CHANGED: {
17295                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17296                    break;
17297                }
17298            }
17299        }
17300
17301        private void notifyCreated(int moveId, Bundle extras) {
17302            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17303
17304            final SomeArgs args = SomeArgs.obtain();
17305            args.argi1 = moveId;
17306            args.arg2 = extras;
17307            obtainMessage(MSG_CREATED, args).sendToTarget();
17308        }
17309
17310        private void notifyStatusChanged(int moveId, int status) {
17311            notifyStatusChanged(moveId, status, -1);
17312        }
17313
17314        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17315            Slog.v(TAG, "Move " + moveId + " status " + status);
17316
17317            final SomeArgs args = SomeArgs.obtain();
17318            args.argi1 = moveId;
17319            args.argi2 = status;
17320            args.arg3 = estMillis;
17321            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17322
17323            synchronized (mLastStatus) {
17324                mLastStatus.put(moveId, status);
17325            }
17326        }
17327    }
17328
17329    private final class OnPermissionChangeListeners extends Handler {
17330        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17331
17332        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17333                new RemoteCallbackList<>();
17334
17335        public OnPermissionChangeListeners(Looper looper) {
17336            super(looper);
17337        }
17338
17339        @Override
17340        public void handleMessage(Message msg) {
17341            switch (msg.what) {
17342                case MSG_ON_PERMISSIONS_CHANGED: {
17343                    final int uid = msg.arg1;
17344                    handleOnPermissionsChanged(uid);
17345                } break;
17346            }
17347        }
17348
17349        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17350            mPermissionListeners.register(listener);
17351
17352        }
17353
17354        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17355            mPermissionListeners.unregister(listener);
17356        }
17357
17358        public void onPermissionsChanged(int uid) {
17359            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17360                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17361            }
17362        }
17363
17364        private void handleOnPermissionsChanged(int uid) {
17365            final int count = mPermissionListeners.beginBroadcast();
17366            try {
17367                for (int i = 0; i < count; i++) {
17368                    IOnPermissionsChangeListener callback = mPermissionListeners
17369                            .getBroadcastItem(i);
17370                    try {
17371                        callback.onPermissionsChanged(uid);
17372                    } catch (RemoteException e) {
17373                        Log.e(TAG, "Permission listener is dead", e);
17374                    }
17375                }
17376            } finally {
17377                mPermissionListeners.finishBroadcast();
17378            }
17379        }
17380    }
17381
17382    private class PackageManagerInternalImpl extends PackageManagerInternal {
17383        @Override
17384        public void setLocationPackagesProvider(PackagesProvider provider) {
17385            synchronized (mPackages) {
17386                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17387            }
17388        }
17389
17390        @Override
17391        public void setImePackagesProvider(PackagesProvider provider) {
17392            synchronized (mPackages) {
17393                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17394            }
17395        }
17396
17397        @Override
17398        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17399            synchronized (mPackages) {
17400                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17401            }
17402        }
17403
17404        @Override
17405        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17406            synchronized (mPackages) {
17407                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17408            }
17409        }
17410
17411        @Override
17412        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17413            synchronized (mPackages) {
17414                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17415            }
17416        }
17417
17418        @Override
17419        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17420            synchronized (mPackages) {
17421                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17422            }
17423        }
17424
17425        @Override
17426        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17427            synchronized (mPackages) {
17428                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17429            }
17430        }
17431
17432        @Override
17433        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17434            synchronized (mPackages) {
17435                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17436                        packageName, userId);
17437            }
17438        }
17439
17440        @Override
17441        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17442            synchronized (mPackages) {
17443                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17444                        packageName, userId);
17445            }
17446        }
17447
17448        @Override
17449        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17450            synchronized (mPackages) {
17451                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17452                        packageName, userId);
17453            }
17454        }
17455
17456        @Override
17457        public void setKeepUninstalledPackages(final List<String> packageList) {
17458            Preconditions.checkNotNull(packageList);
17459            List<String> removedFromList = null;
17460            synchronized (mPackages) {
17461                if (mKeepUninstalledPackages != null) {
17462                    final int packagesCount = mKeepUninstalledPackages.size();
17463                    for (int i = 0; i < packagesCount; i++) {
17464                        String oldPackage = mKeepUninstalledPackages.get(i);
17465                        if (packageList != null && packageList.contains(oldPackage)) {
17466                            continue;
17467                        }
17468                        if (removedFromList == null) {
17469                            removedFromList = new ArrayList<>();
17470                        }
17471                        removedFromList.add(oldPackage);
17472                    }
17473                }
17474                mKeepUninstalledPackages = new ArrayList<>(packageList);
17475                if (removedFromList != null) {
17476                    final int removedCount = removedFromList.size();
17477                    for (int i = 0; i < removedCount; i++) {
17478                        deletePackageIfUnusedLPr(removedFromList.get(i));
17479                    }
17480                }
17481            }
17482        }
17483
17484        @Override
17485        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17486            synchronized (mPackages) {
17487                // If we do not support permission review, done.
17488                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17489                    return false;
17490                }
17491
17492                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17493                if (packageSetting == null) {
17494                    return false;
17495                }
17496
17497                // Permission review applies only to apps not supporting the new permission model.
17498                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17499                    return false;
17500                }
17501
17502                // Legacy apps have the permission and get user consent on launch.
17503                PermissionsState permissionsState = packageSetting.getPermissionsState();
17504                return permissionsState.isPermissionReviewRequired(userId);
17505            }
17506        }
17507    }
17508
17509    @Override
17510    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17511        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17512        synchronized (mPackages) {
17513            final long identity = Binder.clearCallingIdentity();
17514            try {
17515                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17516                        packageNames, userId);
17517            } finally {
17518                Binder.restoreCallingIdentity(identity);
17519            }
17520        }
17521    }
17522
17523    private static void enforceSystemOrPhoneCaller(String tag) {
17524        int callingUid = Binder.getCallingUid();
17525        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17526            throw new SecurityException(
17527                    "Cannot call " + tag + " from UID " + callingUid);
17528        }
17529    }
17530}
17531