PackageManagerService.java revision 7440f177c3e70da0b883f8abffd6c8fc1d507bb8
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
63import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
64import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
65import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
66import static android.content.pm.PackageManager.PERMISSION_DENIED;
67import static android.content.pm.PackageManager.PERMISSION_GRANTED;
68import static android.content.pm.PackageParser.isApkFile;
69import static android.os.Process.PACKAGE_INFO_GID;
70import static android.os.Process.SYSTEM_UID;
71import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
72import static android.system.OsConstants.O_CREAT;
73import static android.system.OsConstants.O_RDWR;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
76import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
77import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
78import static com.android.internal.util.ArrayUtils.appendInt;
79import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
80import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
83import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
84import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
88
89import android.Manifest;
90import android.app.ActivityManager;
91import android.app.ActivityManagerNative;
92import android.app.AppGlobals;
93import android.app.IActivityManager;
94import android.app.admin.IDevicePolicyManager;
95import android.app.backup.IBackupManager;
96import android.content.BroadcastReceiver;
97import android.content.ComponentName;
98import android.content.Context;
99import android.content.IIntentReceiver;
100import android.content.Intent;
101import android.content.IntentFilter;
102import android.content.IntentSender;
103import android.content.IntentSender.SendIntentException;
104import android.content.ServiceConnection;
105import android.content.pm.ActivityInfo;
106import android.content.pm.ApplicationInfo;
107import android.content.pm.AppsQueryHelper;
108import android.content.pm.EphemeralResolveInfo;
109import android.content.pm.EphemeralApplicationInfo;
110import android.content.pm.FeatureInfo;
111import android.content.pm.IOnPermissionsChangeListener;
112import android.content.pm.IPackageDataObserver;
113import android.content.pm.IPackageDeleteObserver;
114import android.content.pm.IPackageDeleteObserver2;
115import android.content.pm.IPackageInstallObserver2;
116import android.content.pm.IPackageInstaller;
117import android.content.pm.IPackageManager;
118import android.content.pm.IPackageMoveObserver;
119import android.content.pm.IPackageStatsObserver;
120import android.content.pm.InstrumentationInfo;
121import android.content.pm.IntentFilterVerificationInfo;
122import android.content.pm.KeySet;
123import android.content.pm.ManifestDigest;
124import android.content.pm.PackageCleanItem;
125import android.content.pm.PackageInfo;
126import android.content.pm.PackageInfoLite;
127import android.content.pm.PackageInstaller;
128import android.content.pm.PackageManager;
129import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
130import android.content.pm.PackageManagerInternal;
131import android.content.pm.PackageParser;
132import android.content.pm.PackageParser.ActivityIntentInfo;
133import android.content.pm.PackageParser.PackageLite;
134import android.content.pm.PackageParser.PackageParserException;
135import android.content.pm.PackageStats;
136import android.content.pm.PackageUserState;
137import android.content.pm.ParceledListSlice;
138import android.content.pm.PermissionGroupInfo;
139import android.content.pm.PermissionInfo;
140import android.content.pm.ProviderInfo;
141import android.content.pm.ResolveInfo;
142import android.content.pm.ServiceInfo;
143import android.content.pm.Signature;
144import android.content.pm.UserInfo;
145import android.content.pm.VerificationParams;
146import android.content.pm.VerifierDeviceIdentity;
147import android.content.pm.VerifierInfo;
148import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
149import android.content.res.Resources;
150import android.graphics.Bitmap;
151import android.hardware.display.DisplayManager;
152import android.net.Uri;
153import android.os.Debug;
154import android.os.Binder;
155import android.os.Build;
156import android.os.Bundle;
157import android.os.Environment;
158import android.os.Environment.UserEnvironment;
159import android.os.FileUtils;
160import android.os.Handler;
161import android.os.IBinder;
162import android.os.Looper;
163import android.os.Message;
164import android.os.Parcel;
165import android.os.ParcelFileDescriptor;
166import android.os.Process;
167import android.os.RemoteCallbackList;
168import android.os.RemoteException;
169import android.os.ResultReceiver;
170import android.os.SELinux;
171import android.os.ServiceManager;
172import android.os.SystemClock;
173import android.os.SystemProperties;
174import android.os.Trace;
175import android.os.UserHandle;
176import android.os.UserManager;
177import android.os.storage.IMountService;
178import android.os.storage.MountServiceInternal;
179import android.os.storage.StorageEventListener;
180import android.os.storage.StorageManager;
181import android.os.storage.VolumeInfo;
182import android.os.storage.VolumeRecord;
183import android.security.KeyStore;
184import android.security.SystemKeyStore;
185import android.system.ErrnoException;
186import android.system.Os;
187import android.system.StructStat;
188import android.text.TextUtils;
189import android.text.format.DateUtils;
190import android.util.ArrayMap;
191import android.util.ArraySet;
192import android.util.AtomicFile;
193import android.util.DisplayMetrics;
194import android.util.EventLog;
195import android.util.ExceptionUtils;
196import android.util.Log;
197import android.util.LogPrinter;
198import android.util.MathUtils;
199import android.util.PrintStreamPrinter;
200import android.util.Slog;
201import android.util.SparseArray;
202import android.util.SparseBooleanArray;
203import android.util.SparseIntArray;
204import android.util.Xml;
205import android.view.Display;
206
207import com.android.internal.annotations.GuardedBy;
208import dalvik.system.DexFile;
209import dalvik.system.VMRuntime;
210
211import libcore.io.IoUtils;
212import libcore.util.EmptyArray;
213
214import com.android.internal.R;
215import com.android.internal.annotations.GuardedBy;
216import com.android.internal.app.IMediaContainerService;
217import com.android.internal.app.ResolverActivity;
218import com.android.internal.content.NativeLibraryHelper;
219import com.android.internal.content.PackageHelper;
220import com.android.internal.os.IParcelFileDescriptorFactory;
221import com.android.internal.os.SomeArgs;
222import com.android.internal.os.Zygote;
223import com.android.internal.util.ArrayUtils;
224import com.android.internal.util.FastPrintWriter;
225import com.android.internal.util.FastXmlSerializer;
226import com.android.internal.util.IndentingPrintWriter;
227import com.android.internal.util.Preconditions;
228import com.android.server.EventLogTags;
229import com.android.server.FgThread;
230import com.android.server.IntentResolver;
231import com.android.server.LocalServices;
232import com.android.server.ServiceThread;
233import com.android.server.SystemConfig;
234import com.android.server.Watchdog;
235import com.android.server.pm.PermissionsState.PermissionState;
236import com.android.server.pm.Settings.DatabaseVersion;
237import com.android.server.pm.Settings.VersionInfo;
238import com.android.server.storage.DeviceStorageMonitorInternal;
239
240import org.xmlpull.v1.XmlPullParser;
241import org.xmlpull.v1.XmlPullParserException;
242import org.xmlpull.v1.XmlSerializer;
243
244import java.io.BufferedInputStream;
245import java.io.BufferedOutputStream;
246import java.io.BufferedReader;
247import java.io.ByteArrayInputStream;
248import java.io.ByteArrayOutputStream;
249import java.io.File;
250import java.io.FileDescriptor;
251import java.io.FileNotFoundException;
252import java.io.FileOutputStream;
253import java.io.FileReader;
254import java.io.FilenameFilter;
255import java.io.IOException;
256import java.io.InputStream;
257import java.io.PrintWriter;
258import java.nio.charset.StandardCharsets;
259import java.security.MessageDigest;
260import java.security.NoSuchAlgorithmException;
261import java.security.PublicKey;
262import java.security.cert.CertificateEncodingException;
263import java.security.cert.CertificateException;
264import java.text.SimpleDateFormat;
265import java.util.ArrayList;
266import java.util.Arrays;
267import java.util.Collection;
268import java.util.Collections;
269import java.util.Comparator;
270import java.util.Date;
271import java.util.Iterator;
272import java.util.List;
273import java.util.Map;
274import java.util.Objects;
275import java.util.Set;
276import java.util.concurrent.CountDownLatch;
277import java.util.concurrent.TimeUnit;
278import java.util.concurrent.atomic.AtomicBoolean;
279import java.util.concurrent.atomic.AtomicInteger;
280import java.util.concurrent.atomic.AtomicLong;
281
282/**
283 * Keep track of all those .apks everywhere.
284 *
285 * This is very central to the platform's security; please run the unit
286 * tests whenever making modifications here:
287 *
288runtest -c android.content.pm.PackageManagerTests frameworks-core
289 *
290 * {@hide}
291 */
292public class PackageManagerService extends IPackageManager.Stub {
293    static final String TAG = "PackageManager";
294    static final boolean DEBUG_SETTINGS = false;
295    static final boolean DEBUG_PREFERRED = false;
296    static final boolean DEBUG_UPGRADE = false;
297    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
298    private static final boolean DEBUG_BACKUP = false;
299    private static final boolean DEBUG_INSTALL = false;
300    private static final boolean DEBUG_REMOVE = false;
301    private static final boolean DEBUG_BROADCASTS = false;
302    private static final boolean DEBUG_SHOW_INFO = false;
303    private static final boolean DEBUG_PACKAGE_INFO = false;
304    private static final boolean DEBUG_INTENT_MATCHING = false;
305    private static final boolean DEBUG_PACKAGE_SCANNING = false;
306    private static final boolean DEBUG_VERIFY = false;
307    private static final boolean DEBUG_DEXOPT = false;
308    private static final boolean DEBUG_ABI_SELECTION = false;
309    private static final boolean DEBUG_EPHEMERAL = false;
310
311    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
312
313    private static final int RADIO_UID = Process.PHONE_UID;
314    private static final int LOG_UID = Process.LOG_UID;
315    private static final int NFC_UID = Process.NFC_UID;
316    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
317    private static final int SHELL_UID = Process.SHELL_UID;
318
319    // Cap the size of permission trees that 3rd party apps can define
320    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
321
322    // Suffix used during package installation when copying/moving
323    // package apks to install directory.
324    private static final String INSTALL_PACKAGE_SUFFIX = "-";
325
326    static final int SCAN_NO_DEX = 1<<1;
327    static final int SCAN_FORCE_DEX = 1<<2;
328    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
329    static final int SCAN_NEW_INSTALL = 1<<4;
330    static final int SCAN_NO_PATHS = 1<<5;
331    static final int SCAN_UPDATE_TIME = 1<<6;
332    static final int SCAN_DEFER_DEX = 1<<7;
333    static final int SCAN_BOOTING = 1<<8;
334    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
335    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
336    static final int SCAN_REPLACING = 1<<11;
337    static final int SCAN_REQUIRE_KNOWN = 1<<12;
338    static final int SCAN_MOVE = 1<<13;
339    static final int SCAN_INITIAL = 1<<14;
340
341    static final int REMOVE_CHATTY = 1<<16;
342
343    private static final int[] EMPTY_INT_ARRAY = new int[0];
344
345    /**
346     * Timeout (in milliseconds) after which the watchdog should declare that
347     * our handler thread is wedged.  The usual default for such things is one
348     * minute but we sometimes do very lengthy I/O operations on this thread,
349     * such as installing multi-gigabyte applications, so ours needs to be longer.
350     */
351    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
352
353    /**
354     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
355     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
356     * settings entry if available, otherwise we use the hardcoded default.  If it's been
357     * more than this long since the last fstrim, we force one during the boot sequence.
358     *
359     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
360     * one gets run at the next available charging+idle time.  This final mandatory
361     * no-fstrim check kicks in only of the other scheduling criteria is never met.
362     */
363    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
364
365    /**
366     * Whether verification is enabled by default.
367     */
368    private static final boolean DEFAULT_VERIFY_ENABLE = true;
369
370    /**
371     * The default maximum time to wait for the verification agent to return in
372     * milliseconds.
373     */
374    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
375
376    /**
377     * The default response for package verification timeout.
378     *
379     * This can be either PackageManager.VERIFICATION_ALLOW or
380     * PackageManager.VERIFICATION_REJECT.
381     */
382    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
383
384    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
385
386    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
387            DEFAULT_CONTAINER_PACKAGE,
388            "com.android.defcontainer.DefaultContainerService");
389
390    private static final String KILL_APP_REASON_GIDS_CHANGED =
391            "permission grant or revoke changed gids";
392
393    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
394            "permissions revoked";
395
396    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
397
398    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
399
400    /** Permission grant: not grant the permission. */
401    private static final int GRANT_DENIED = 1;
402
403    /** Permission grant: grant the permission as an install permission. */
404    private static final int GRANT_INSTALL = 2;
405
406    /** Permission grant: grant the permission as a runtime one. */
407    private static final int GRANT_RUNTIME = 3;
408
409    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
410    private static final int GRANT_UPGRADE = 4;
411
412    /** Canonical intent used to identify what counts as a "web browser" app */
413    private static final Intent sBrowserIntent;
414    static {
415        sBrowserIntent = new Intent();
416        sBrowserIntent.setAction(Intent.ACTION_VIEW);
417        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
418        sBrowserIntent.setData(Uri.parse("http:"));
419    }
420
421    final ServiceThread mHandlerThread;
422
423    final PackageHandler mHandler;
424
425    /**
426     * Messages for {@link #mHandler} that need to wait for system ready before
427     * being dispatched.
428     */
429    private ArrayList<Message> mPostSystemReadyMessages;
430
431    final int mSdkVersion = Build.VERSION.SDK_INT;
432
433    final Context mContext;
434    final boolean mFactoryTest;
435    final boolean mOnlyCore;
436    final DisplayMetrics mMetrics;
437    final int mDefParseFlags;
438    final String[] mSeparateProcesses;
439    final boolean mIsUpgrade;
440
441    /** The location for ASEC container files on internal storage. */
442    final String mAsecInternalPath;
443
444    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
445    // LOCK HELD.  Can be called with mInstallLock held.
446    @GuardedBy("mInstallLock")
447    final Installer mInstaller;
448
449    /** Directory where installed third-party apps stored */
450    final File mAppInstallDir;
451    final File mEphemeralInstallDir;
452
453    /**
454     * Directory to which applications installed internally have their
455     * 32 bit native libraries copied.
456     */
457    private File mAppLib32InstallDir;
458
459    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
460    // apps.
461    final File mDrmAppPrivateInstallDir;
462
463    // ----------------------------------------------------------------
464
465    // Lock for state used when installing and doing other long running
466    // operations.  Methods that must be called with this lock held have
467    // the suffix "LI".
468    final Object mInstallLock = new Object();
469
470    // ----------------------------------------------------------------
471
472    // Keys are String (package name), values are Package.  This also serves
473    // as the lock for the global state.  Methods that must be called with
474    // this lock held have the prefix "LP".
475    @GuardedBy("mPackages")
476    final ArrayMap<String, PackageParser.Package> mPackages =
477            new ArrayMap<String, PackageParser.Package>();
478
479    // Tracks available target package names -> overlay package paths.
480    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
481        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
482
483    /**
484     * Tracks new system packages [received in an OTA] that we expect to
485     * find updated user-installed versions. Keys are package name, values
486     * are package location.
487     */
488    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
489
490    /**
491     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
492     */
493    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
494    /**
495     * Whether or not system app permissions should be promoted from install to runtime.
496     */
497    boolean mPromoteSystemApps;
498
499    final Settings mSettings;
500    boolean mRestoredSettings;
501
502    // System configuration read by SystemConfig.
503    final int[] mGlobalGids;
504    final SparseArray<ArraySet<String>> mSystemPermissions;
505    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
506
507    // If mac_permissions.xml was found for seinfo labeling.
508    boolean mFoundPolicyFile;
509
510    // If a recursive restorecon of /data/data/<pkg> is needed.
511    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
512
513    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
514
515    public static final class SharedLibraryEntry {
516        public final String path;
517        public final String apk;
518
519        SharedLibraryEntry(String _path, String _apk) {
520            path = _path;
521            apk = _apk;
522        }
523    }
524
525    // Currently known shared libraries.
526    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
527            new ArrayMap<String, SharedLibraryEntry>();
528
529    // All available activities, for your resolving pleasure.
530    final ActivityIntentResolver mActivities =
531            new ActivityIntentResolver();
532
533    // All available receivers, for your resolving pleasure.
534    final ActivityIntentResolver mReceivers =
535            new ActivityIntentResolver();
536
537    // All available services, for your resolving pleasure.
538    final ServiceIntentResolver mServices = new ServiceIntentResolver();
539
540    // All available providers, for your resolving pleasure.
541    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
542
543    // Mapping from provider base names (first directory in content URI codePath)
544    // to the provider information.
545    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
546            new ArrayMap<String, PackageParser.Provider>();
547
548    // Mapping from instrumentation class names to info about them.
549    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
550            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
551
552    // Mapping from permission names to info about them.
553    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
554            new ArrayMap<String, PackageParser.PermissionGroup>();
555
556    // Packages whose data we have transfered into another package, thus
557    // should no longer exist.
558    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
559
560    // Broadcast actions that are only available to the system.
561    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
562
563    /** List of packages waiting for verification. */
564    final SparseArray<PackageVerificationState> mPendingVerification
565            = new SparseArray<PackageVerificationState>();
566
567    /** Set of packages associated with each app op permission. */
568    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
569
570    final PackageInstallerService mInstallerService;
571
572    private final PackageDexOptimizer mPackageDexOptimizer;
573
574    private AtomicInteger mNextMoveId = new AtomicInteger();
575    private final MoveCallbacks mMoveCallbacks;
576
577    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
578
579    // Cache of users who need badging.
580    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
581
582    /** Token for keys in mPendingVerification. */
583    private int mPendingVerificationToken = 0;
584
585    volatile boolean mSystemReady;
586    volatile boolean mSafeMode;
587    volatile boolean mHasSystemUidErrors;
588
589    ApplicationInfo mAndroidApplication;
590    final ActivityInfo mResolveActivity = new ActivityInfo();
591    final ResolveInfo mResolveInfo = new ResolveInfo();
592    ComponentName mResolveComponentName;
593    PackageParser.Package mPlatformPackage;
594    ComponentName mCustomResolverComponentName;
595
596    boolean mResolverReplaced = false;
597
598    private final ComponentName mIntentFilterVerifierComponent;
599    private int mIntentFilterVerificationToken = 0;
600
601    /** Component that knows whether or not an ephemeral application exists */
602    final ComponentName mEphemeralResolverComponent;
603    /** The service connection to the ephemeral resolver */
604    final EphemeralResolverConnection mEphemeralResolverConnection;
605
606    /** Component used to install ephemeral applications */
607    final ComponentName mEphemeralInstallerComponent;
608    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
609    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
610
611    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
612            = new SparseArray<IntentFilterVerificationState>();
613
614    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
615            new DefaultPermissionGrantPolicy(this);
616
617    // List of packages names to keep cached, even if they are uninstalled for all users
618    private List<String> mKeepUninstalledPackages;
619
620    private static class IFVerificationParams {
621        PackageParser.Package pkg;
622        boolean replacing;
623        int userId;
624        int verifierUid;
625
626        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
627                int _userId, int _verifierUid) {
628            pkg = _pkg;
629            replacing = _replacing;
630            userId = _userId;
631            replacing = _replacing;
632            verifierUid = _verifierUid;
633        }
634    }
635
636    private interface IntentFilterVerifier<T extends IntentFilter> {
637        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
638                                               T filter, String packageName);
639        void startVerifications(int userId);
640        void receiveVerificationResponse(int verificationId);
641    }
642
643    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
644        private Context mContext;
645        private ComponentName mIntentFilterVerifierComponent;
646        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
647
648        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
649            mContext = context;
650            mIntentFilterVerifierComponent = verifierComponent;
651        }
652
653        private String getDefaultScheme() {
654            return IntentFilter.SCHEME_HTTPS;
655        }
656
657        @Override
658        public void startVerifications(int userId) {
659            // Launch verifications requests
660            int count = mCurrentIntentFilterVerifications.size();
661            for (int n=0; n<count; n++) {
662                int verificationId = mCurrentIntentFilterVerifications.get(n);
663                final IntentFilterVerificationState ivs =
664                        mIntentFilterVerificationStates.get(verificationId);
665
666                String packageName = ivs.getPackageName();
667
668                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
669                final int filterCount = filters.size();
670                ArraySet<String> domainsSet = new ArraySet<>();
671                for (int m=0; m<filterCount; m++) {
672                    PackageParser.ActivityIntentInfo filter = filters.get(m);
673                    domainsSet.addAll(filter.getHostsList());
674                }
675                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
676                synchronized (mPackages) {
677                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
678                            packageName, domainsList) != null) {
679                        scheduleWriteSettingsLocked();
680                    }
681                }
682                sendVerificationRequest(userId, verificationId, ivs);
683            }
684            mCurrentIntentFilterVerifications.clear();
685        }
686
687        private void sendVerificationRequest(int userId, int verificationId,
688                IntentFilterVerificationState ivs) {
689
690            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
691            verificationIntent.putExtra(
692                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
693                    verificationId);
694            verificationIntent.putExtra(
695                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
696                    getDefaultScheme());
697            verificationIntent.putExtra(
698                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
699                    ivs.getHostsString());
700            verificationIntent.putExtra(
701                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
702                    ivs.getPackageName());
703            verificationIntent.setComponent(mIntentFilterVerifierComponent);
704            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
705
706            UserHandle user = new UserHandle(userId);
707            mContext.sendBroadcastAsUser(verificationIntent, user);
708            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
709                    "Sending IntentFilter verification broadcast");
710        }
711
712        public void receiveVerificationResponse(int verificationId) {
713            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
714
715            final boolean verified = ivs.isVerified();
716
717            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
718            final int count = filters.size();
719            if (DEBUG_DOMAIN_VERIFICATION) {
720                Slog.i(TAG, "Received verification response " + verificationId
721                        + " for " + count + " filters, verified=" + verified);
722            }
723            for (int n=0; n<count; n++) {
724                PackageParser.ActivityIntentInfo filter = filters.get(n);
725                filter.setVerified(verified);
726
727                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
728                        + " verified with result:" + verified + " and hosts:"
729                        + ivs.getHostsString());
730            }
731
732            mIntentFilterVerificationStates.remove(verificationId);
733
734            final String packageName = ivs.getPackageName();
735            IntentFilterVerificationInfo ivi = null;
736
737            synchronized (mPackages) {
738                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
739            }
740            if (ivi == null) {
741                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
742                        + verificationId + " packageName:" + packageName);
743                return;
744            }
745            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
746                    "Updating IntentFilterVerificationInfo for package " + packageName
747                            +" verificationId:" + verificationId);
748
749            synchronized (mPackages) {
750                if (verified) {
751                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
752                } else {
753                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
754                }
755                scheduleWriteSettingsLocked();
756
757                final int userId = ivs.getUserId();
758                if (userId != UserHandle.USER_ALL) {
759                    final int userStatus =
760                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
761
762                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
763                    boolean needUpdate = false;
764
765                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
766                    // already been set by the User thru the Disambiguation dialog
767                    switch (userStatus) {
768                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
769                            if (verified) {
770                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
771                            } else {
772                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
773                            }
774                            needUpdate = true;
775                            break;
776
777                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
778                            if (verified) {
779                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
780                                needUpdate = true;
781                            }
782                            break;
783
784                        default:
785                            // Nothing to do
786                    }
787
788                    if (needUpdate) {
789                        mSettings.updateIntentFilterVerificationStatusLPw(
790                                packageName, updatedStatus, userId);
791                        scheduleWritePackageRestrictionsLocked(userId);
792                    }
793                }
794            }
795        }
796
797        @Override
798        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
799                    ActivityIntentInfo filter, String packageName) {
800            if (!hasValidDomains(filter)) {
801                return false;
802            }
803            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
804            if (ivs == null) {
805                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
806                        packageName);
807            }
808            if (DEBUG_DOMAIN_VERIFICATION) {
809                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
810            }
811            ivs.addFilter(filter);
812            return true;
813        }
814
815        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
816                int userId, int verificationId, String packageName) {
817            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
818                    verifierUid, userId, packageName);
819            ivs.setPendingState();
820            synchronized (mPackages) {
821                mIntentFilterVerificationStates.append(verificationId, ivs);
822                mCurrentIntentFilterVerifications.add(verificationId);
823            }
824            return ivs;
825        }
826    }
827
828    private static boolean hasValidDomains(ActivityIntentInfo filter) {
829        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
830                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
831                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
832    }
833
834    private IntentFilterVerifier mIntentFilterVerifier;
835
836    // Set of pending broadcasts for aggregating enable/disable of components.
837    static class PendingPackageBroadcasts {
838        // for each user id, a map of <package name -> components within that package>
839        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
840
841        public PendingPackageBroadcasts() {
842            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
843        }
844
845        public ArrayList<String> get(int userId, String packageName) {
846            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
847            return packages.get(packageName);
848        }
849
850        public void put(int userId, String packageName, ArrayList<String> components) {
851            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
852            packages.put(packageName, components);
853        }
854
855        public void remove(int userId, String packageName) {
856            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
857            if (packages != null) {
858                packages.remove(packageName);
859            }
860        }
861
862        public void remove(int userId) {
863            mUidMap.remove(userId);
864        }
865
866        public int userIdCount() {
867            return mUidMap.size();
868        }
869
870        public int userIdAt(int n) {
871            return mUidMap.keyAt(n);
872        }
873
874        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
875            return mUidMap.get(userId);
876        }
877
878        public int size() {
879            // total number of pending broadcast entries across all userIds
880            int num = 0;
881            for (int i = 0; i< mUidMap.size(); i++) {
882                num += mUidMap.valueAt(i).size();
883            }
884            return num;
885        }
886
887        public void clear() {
888            mUidMap.clear();
889        }
890
891        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
892            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
893            if (map == null) {
894                map = new ArrayMap<String, ArrayList<String>>();
895                mUidMap.put(userId, map);
896            }
897            return map;
898        }
899    }
900    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
901
902    // Service Connection to remote media container service to copy
903    // package uri's from external media onto secure containers
904    // or internal storage.
905    private IMediaContainerService mContainerService = null;
906
907    static final int SEND_PENDING_BROADCAST = 1;
908    static final int MCS_BOUND = 3;
909    static final int END_COPY = 4;
910    static final int INIT_COPY = 5;
911    static final int MCS_UNBIND = 6;
912    static final int START_CLEANING_PACKAGE = 7;
913    static final int FIND_INSTALL_LOC = 8;
914    static final int POST_INSTALL = 9;
915    static final int MCS_RECONNECT = 10;
916    static final int MCS_GIVE_UP = 11;
917    static final int UPDATED_MEDIA_STATUS = 12;
918    static final int WRITE_SETTINGS = 13;
919    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
920    static final int PACKAGE_VERIFIED = 15;
921    static final int CHECK_PENDING_VERIFICATION = 16;
922    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
923    static final int INTENT_FILTER_VERIFIED = 18;
924
925    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
926
927    // Delay time in millisecs
928    static final int BROADCAST_DELAY = 10 * 1000;
929
930    static UserManagerService sUserManager;
931
932    // Stores a list of users whose package restrictions file needs to be updated
933    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
934
935    final private DefaultContainerConnection mDefContainerConn =
936            new DefaultContainerConnection();
937    class DefaultContainerConnection implements ServiceConnection {
938        public void onServiceConnected(ComponentName name, IBinder service) {
939            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
940            IMediaContainerService imcs =
941                IMediaContainerService.Stub.asInterface(service);
942            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
943        }
944
945        public void onServiceDisconnected(ComponentName name) {
946            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
947        }
948    }
949
950    // Recordkeeping of restore-after-install operations that are currently in flight
951    // between the Package Manager and the Backup Manager
952    static class PostInstallData {
953        public InstallArgs args;
954        public PackageInstalledInfo res;
955
956        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
957            args = _a;
958            res = _r;
959        }
960    }
961
962    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
963    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
964
965    // XML tags for backup/restore of various bits of state
966    private static final String TAG_PREFERRED_BACKUP = "pa";
967    private static final String TAG_DEFAULT_APPS = "da";
968    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
969
970    final String mRequiredVerifierPackage;
971    final String mRequiredInstallerPackage;
972
973    private final PackageUsage mPackageUsage = new PackageUsage();
974
975    private class PackageUsage {
976        private static final int WRITE_INTERVAL
977            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
978
979        private final Object mFileLock = new Object();
980        private final AtomicLong mLastWritten = new AtomicLong(0);
981        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
982
983        private boolean mIsHistoricalPackageUsageAvailable = true;
984
985        boolean isHistoricalPackageUsageAvailable() {
986            return mIsHistoricalPackageUsageAvailable;
987        }
988
989        void write(boolean force) {
990            if (force) {
991                writeInternal();
992                return;
993            }
994            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
995                && !DEBUG_DEXOPT) {
996                return;
997            }
998            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
999                new Thread("PackageUsage_DiskWriter") {
1000                    @Override
1001                    public void run() {
1002                        try {
1003                            writeInternal();
1004                        } finally {
1005                            mBackgroundWriteRunning.set(false);
1006                        }
1007                    }
1008                }.start();
1009            }
1010        }
1011
1012        private void writeInternal() {
1013            synchronized (mPackages) {
1014                synchronized (mFileLock) {
1015                    AtomicFile file = getFile();
1016                    FileOutputStream f = null;
1017                    try {
1018                        f = file.startWrite();
1019                        BufferedOutputStream out = new BufferedOutputStream(f);
1020                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1021                        StringBuilder sb = new StringBuilder();
1022                        for (PackageParser.Package pkg : mPackages.values()) {
1023                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1024                                continue;
1025                            }
1026                            sb.setLength(0);
1027                            sb.append(pkg.packageName);
1028                            sb.append(' ');
1029                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1030                            sb.append('\n');
1031                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1032                        }
1033                        out.flush();
1034                        file.finishWrite(f);
1035                    } catch (IOException e) {
1036                        if (f != null) {
1037                            file.failWrite(f);
1038                        }
1039                        Log.e(TAG, "Failed to write package usage times", e);
1040                    }
1041                }
1042            }
1043            mLastWritten.set(SystemClock.elapsedRealtime());
1044        }
1045
1046        void readLP() {
1047            synchronized (mFileLock) {
1048                AtomicFile file = getFile();
1049                BufferedInputStream in = null;
1050                try {
1051                    in = new BufferedInputStream(file.openRead());
1052                    StringBuffer sb = new StringBuffer();
1053                    while (true) {
1054                        String packageName = readToken(in, sb, ' ');
1055                        if (packageName == null) {
1056                            break;
1057                        }
1058                        String timeInMillisString = readToken(in, sb, '\n');
1059                        if (timeInMillisString == null) {
1060                            throw new IOException("Failed to find last usage time for package "
1061                                                  + packageName);
1062                        }
1063                        PackageParser.Package pkg = mPackages.get(packageName);
1064                        if (pkg == null) {
1065                            continue;
1066                        }
1067                        long timeInMillis;
1068                        try {
1069                            timeInMillis = Long.parseLong(timeInMillisString);
1070                        } catch (NumberFormatException e) {
1071                            throw new IOException("Failed to parse " + timeInMillisString
1072                                                  + " as a long.", e);
1073                        }
1074                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1075                    }
1076                } catch (FileNotFoundException expected) {
1077                    mIsHistoricalPackageUsageAvailable = false;
1078                } catch (IOException e) {
1079                    Log.w(TAG, "Failed to read package usage times", e);
1080                } finally {
1081                    IoUtils.closeQuietly(in);
1082                }
1083            }
1084            mLastWritten.set(SystemClock.elapsedRealtime());
1085        }
1086
1087        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1088                throws IOException {
1089            sb.setLength(0);
1090            while (true) {
1091                int ch = in.read();
1092                if (ch == -1) {
1093                    if (sb.length() == 0) {
1094                        return null;
1095                    }
1096                    throw new IOException("Unexpected EOF");
1097                }
1098                if (ch == endOfToken) {
1099                    return sb.toString();
1100                }
1101                sb.append((char)ch);
1102            }
1103        }
1104
1105        private AtomicFile getFile() {
1106            File dataDir = Environment.getDataDirectory();
1107            File systemDir = new File(dataDir, "system");
1108            File fname = new File(systemDir, "package-usage.list");
1109            return new AtomicFile(fname);
1110        }
1111    }
1112
1113    class PackageHandler extends Handler {
1114        private boolean mBound = false;
1115        final ArrayList<HandlerParams> mPendingInstalls =
1116            new ArrayList<HandlerParams>();
1117
1118        private boolean connectToService() {
1119            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1120                    " DefaultContainerService");
1121            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1124                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1125                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126                mBound = true;
1127                return true;
1128            }
1129            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1130            return false;
1131        }
1132
1133        private void disconnectService() {
1134            mContainerService = null;
1135            mBound = false;
1136            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1137            mContext.unbindService(mDefContainerConn);
1138            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1139        }
1140
1141        PackageHandler(Looper looper) {
1142            super(looper);
1143        }
1144
1145        public void handleMessage(Message msg) {
1146            try {
1147                doHandleMessage(msg);
1148            } finally {
1149                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1150            }
1151        }
1152
1153        void doHandleMessage(Message msg) {
1154            switch (msg.what) {
1155                case INIT_COPY: {
1156                    HandlerParams params = (HandlerParams) msg.obj;
1157                    int idx = mPendingInstalls.size();
1158                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1159                    // If a bind was already initiated we dont really
1160                    // need to do anything. The pending install
1161                    // will be processed later on.
1162                    if (!mBound) {
1163                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1164                                System.identityHashCode(mHandler));
1165                        // If this is the only one pending we might
1166                        // have to bind to the service again.
1167                        if (!connectToService()) {
1168                            Slog.e(TAG, "Failed to bind to media container service");
1169                            params.serviceError();
1170                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1171                                    System.identityHashCode(mHandler));
1172                            if (params.traceMethod != null) {
1173                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1174                                        params.traceCookie);
1175                            }
1176                            return;
1177                        } else {
1178                            // Once we bind to the service, the first
1179                            // pending request will be processed.
1180                            mPendingInstalls.add(idx, params);
1181                        }
1182                    } else {
1183                        mPendingInstalls.add(idx, params);
1184                        // Already bound to the service. Just make
1185                        // sure we trigger off processing the first request.
1186                        if (idx == 0) {
1187                            mHandler.sendEmptyMessage(MCS_BOUND);
1188                        }
1189                    }
1190                    break;
1191                }
1192                case MCS_BOUND: {
1193                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1194                    if (msg.obj != null) {
1195                        mContainerService = (IMediaContainerService) msg.obj;
1196                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1197                                System.identityHashCode(mHandler));
1198                    }
1199                    if (mContainerService == null) {
1200                        if (!mBound) {
1201                            // Something seriously wrong since we are not bound and we are not
1202                            // waiting for connection. Bail out.
1203                            Slog.e(TAG, "Cannot bind to media container service");
1204                            for (HandlerParams params : mPendingInstalls) {
1205                                // Indicate service bind error
1206                                params.serviceError();
1207                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1208                                        System.identityHashCode(params));
1209                                if (params.traceMethod != null) {
1210                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1211                                            params.traceMethod, params.traceCookie);
1212                                }
1213                                return;
1214                            }
1215                            mPendingInstalls.clear();
1216                        } else {
1217                            Slog.w(TAG, "Waiting to connect to media container service");
1218                        }
1219                    } else if (mPendingInstalls.size() > 0) {
1220                        HandlerParams params = mPendingInstalls.get(0);
1221                        if (params != null) {
1222                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1223                                    System.identityHashCode(params));
1224                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1225                            if (params.startCopy()) {
1226                                // We are done...  look for more work or to
1227                                // go idle.
1228                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1229                                        "Checking for more work or unbind...");
1230                                // Delete pending install
1231                                if (mPendingInstalls.size() > 0) {
1232                                    mPendingInstalls.remove(0);
1233                                }
1234                                if (mPendingInstalls.size() == 0) {
1235                                    if (mBound) {
1236                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1237                                                "Posting delayed MCS_UNBIND");
1238                                        removeMessages(MCS_UNBIND);
1239                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1240                                        // Unbind after a little delay, to avoid
1241                                        // continual thrashing.
1242                                        sendMessageDelayed(ubmsg, 10000);
1243                                    }
1244                                } else {
1245                                    // There are more pending requests in queue.
1246                                    // Just post MCS_BOUND message to trigger processing
1247                                    // of next pending install.
1248                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1249                                            "Posting MCS_BOUND for next work");
1250                                    mHandler.sendEmptyMessage(MCS_BOUND);
1251                                }
1252                            }
1253                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1254                        }
1255                    } else {
1256                        // Should never happen ideally.
1257                        Slog.w(TAG, "Empty queue");
1258                    }
1259                    break;
1260                }
1261                case MCS_RECONNECT: {
1262                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1263                    if (mPendingInstalls.size() > 0) {
1264                        if (mBound) {
1265                            disconnectService();
1266                        }
1267                        if (!connectToService()) {
1268                            Slog.e(TAG, "Failed to bind to media container service");
1269                            for (HandlerParams params : mPendingInstalls) {
1270                                // Indicate service bind error
1271                                params.serviceError();
1272                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1273                                        System.identityHashCode(params));
1274                            }
1275                            mPendingInstalls.clear();
1276                        }
1277                    }
1278                    break;
1279                }
1280                case MCS_UNBIND: {
1281                    // If there is no actual work left, then time to unbind.
1282                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1283
1284                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1285                        if (mBound) {
1286                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1287
1288                            disconnectService();
1289                        }
1290                    } else if (mPendingInstalls.size() > 0) {
1291                        // There are more pending requests in queue.
1292                        // Just post MCS_BOUND message to trigger processing
1293                        // of next pending install.
1294                        mHandler.sendEmptyMessage(MCS_BOUND);
1295                    }
1296
1297                    break;
1298                }
1299                case MCS_GIVE_UP: {
1300                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1301                    HandlerParams params = mPendingInstalls.remove(0);
1302                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1303                            System.identityHashCode(params));
1304                    break;
1305                }
1306                case SEND_PENDING_BROADCAST: {
1307                    String packages[];
1308                    ArrayList<String> components[];
1309                    int size = 0;
1310                    int uids[];
1311                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1312                    synchronized (mPackages) {
1313                        if (mPendingBroadcasts == null) {
1314                            return;
1315                        }
1316                        size = mPendingBroadcasts.size();
1317                        if (size <= 0) {
1318                            // Nothing to be done. Just return
1319                            return;
1320                        }
1321                        packages = new String[size];
1322                        components = new ArrayList[size];
1323                        uids = new int[size];
1324                        int i = 0;  // filling out the above arrays
1325
1326                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1327                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1328                            Iterator<Map.Entry<String, ArrayList<String>>> it
1329                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1330                                            .entrySet().iterator();
1331                            while (it.hasNext() && i < size) {
1332                                Map.Entry<String, ArrayList<String>> ent = it.next();
1333                                packages[i] = ent.getKey();
1334                                components[i] = ent.getValue();
1335                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1336                                uids[i] = (ps != null)
1337                                        ? UserHandle.getUid(packageUserId, ps.appId)
1338                                        : -1;
1339                                i++;
1340                            }
1341                        }
1342                        size = i;
1343                        mPendingBroadcasts.clear();
1344                    }
1345                    // Send broadcasts
1346                    for (int i = 0; i < size; i++) {
1347                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1348                    }
1349                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1350                    break;
1351                }
1352                case START_CLEANING_PACKAGE: {
1353                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1354                    final String packageName = (String)msg.obj;
1355                    final int userId = msg.arg1;
1356                    final boolean andCode = msg.arg2 != 0;
1357                    synchronized (mPackages) {
1358                        if (userId == UserHandle.USER_ALL) {
1359                            int[] users = sUserManager.getUserIds();
1360                            for (int user : users) {
1361                                mSettings.addPackageToCleanLPw(
1362                                        new PackageCleanItem(user, packageName, andCode));
1363                            }
1364                        } else {
1365                            mSettings.addPackageToCleanLPw(
1366                                    new PackageCleanItem(userId, packageName, andCode));
1367                        }
1368                    }
1369                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1370                    startCleaningPackages();
1371                } break;
1372                case POST_INSTALL: {
1373                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1374
1375                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1376                    mRunningInstalls.delete(msg.arg1);
1377                    boolean deleteOld = false;
1378
1379                    if (data != null) {
1380                        InstallArgs args = data.args;
1381                        PackageInstalledInfo res = data.res;
1382
1383                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1384                            final String packageName = res.pkg.applicationInfo.packageName;
1385                            res.removedInfo.sendBroadcast(false, true, false);
1386                            Bundle extras = new Bundle(1);
1387                            extras.putInt(Intent.EXTRA_UID, res.uid);
1388
1389                            // Now that we successfully installed the package, grant runtime
1390                            // permissions if requested before broadcasting the install.
1391                            if ((args.installFlags
1392                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1393                                    && res.pkg.applicationInfo.targetSdkVersion
1394                                            >= Build.VERSION_CODES.M) {
1395                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1396                                        args.installGrantPermissions);
1397                            }
1398
1399                            synchronized (mPackages) {
1400                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1401                            }
1402
1403                            // Determine the set of users who are adding this
1404                            // package for the first time vs. those who are seeing
1405                            // an update.
1406                            int[] firstUsers;
1407                            int[] updateUsers = new int[0];
1408                            if (res.origUsers == null || res.origUsers.length == 0) {
1409                                firstUsers = res.newUsers;
1410                            } else {
1411                                firstUsers = new int[0];
1412                                for (int i=0; i<res.newUsers.length; i++) {
1413                                    int user = res.newUsers[i];
1414                                    boolean isNew = true;
1415                                    for (int j=0; j<res.origUsers.length; j++) {
1416                                        if (res.origUsers[j] == user) {
1417                                            isNew = false;
1418                                            break;
1419                                        }
1420                                    }
1421                                    if (isNew) {
1422                                        int[] newFirst = new int[firstUsers.length+1];
1423                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1424                                                firstUsers.length);
1425                                        newFirst[firstUsers.length] = user;
1426                                        firstUsers = newFirst;
1427                                    } else {
1428                                        int[] newUpdate = new int[updateUsers.length+1];
1429                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1430                                                updateUsers.length);
1431                                        newUpdate[updateUsers.length] = user;
1432                                        updateUsers = newUpdate;
1433                                    }
1434                                }
1435                            }
1436                            // don't broadcast for ephemeral installs/updates
1437                            final boolean isEphemeral = isEphemeral(res.pkg);
1438                            if (!isEphemeral) {
1439                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1440                                        extras, 0 /*flags*/, null /*targetPackage*/,
1441                                        null /*finishedReceiver*/, firstUsers);
1442                            }
1443                            final boolean update = res.removedInfo.removedPackage != null;
1444                            if (update) {
1445                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1446                            }
1447                            if (!isEphemeral) {
1448                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1449                                        extras, 0 /*flags*/, null /*targetPackage*/,
1450                                        null /*finishedReceiver*/, updateUsers);
1451                            }
1452                            if (update) {
1453                                if (!isEphemeral) {
1454                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1455                                            packageName, extras, 0 /*flags*/,
1456                                            null /*targetPackage*/, null /*finishedReceiver*/,
1457                                            updateUsers);
1458                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1459                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1460                                            packageName /*targetPackage*/,
1461                                            null /*finishedReceiver*/, updateUsers);
1462                                }
1463
1464                                // treat asec-hosted packages like removable media on upgrade
1465                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1466                                    if (DEBUG_INSTALL) {
1467                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1468                                                + " is ASEC-hosted -> AVAILABLE");
1469                                    }
1470                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1471                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1472                                    pkgList.add(packageName);
1473                                    sendResourcesChangedBroadcast(true, true,
1474                                            pkgList,uidArray, null);
1475                                }
1476                            }
1477                            if (res.removedInfo.args != null) {
1478                                // Remove the replaced package's older resources safely now
1479                                deleteOld = true;
1480                            }
1481
1482                            // If this app is a browser and it's newly-installed for some
1483                            // users, clear any default-browser state in those users
1484                            if (firstUsers.length > 0) {
1485                                // the app's nature doesn't depend on the user, so we can just
1486                                // check its browser nature in any user and generalize.
1487                                if (packageIsBrowser(packageName, firstUsers[0])) {
1488                                    synchronized (mPackages) {
1489                                        for (int userId : firstUsers) {
1490                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1491                                        }
1492                                    }
1493                                }
1494                            }
1495                            // Log current value of "unknown sources" setting
1496                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1497                                getUnknownSourcesSettings());
1498                        }
1499                        // Force a gc to clear up things
1500                        Runtime.getRuntime().gc();
1501                        // We delete after a gc for applications  on sdcard.
1502                        if (deleteOld) {
1503                            synchronized (mInstallLock) {
1504                                res.removedInfo.args.doPostDeleteLI(true);
1505                            }
1506                        }
1507                        if (args.observer != null) {
1508                            try {
1509                                Bundle extras = extrasForInstallResult(res);
1510                                args.observer.onPackageInstalled(res.name, res.returnCode,
1511                                        res.returnMsg, extras);
1512                            } catch (RemoteException e) {
1513                                Slog.i(TAG, "Observer no longer exists.");
1514                            }
1515                        }
1516                        if (args.traceMethod != null) {
1517                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1518                                    args.traceCookie);
1519                        }
1520                        return;
1521                    } else {
1522                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1523                    }
1524
1525                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1526                } break;
1527                case UPDATED_MEDIA_STATUS: {
1528                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1529                    boolean reportStatus = msg.arg1 == 1;
1530                    boolean doGc = msg.arg2 == 1;
1531                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1532                    if (doGc) {
1533                        // Force a gc to clear up stale containers.
1534                        Runtime.getRuntime().gc();
1535                    }
1536                    if (msg.obj != null) {
1537                        @SuppressWarnings("unchecked")
1538                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1539                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1540                        // Unload containers
1541                        unloadAllContainers(args);
1542                    }
1543                    if (reportStatus) {
1544                        try {
1545                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1546                            PackageHelper.getMountService().finishMediaUpdate();
1547                        } catch (RemoteException e) {
1548                            Log.e(TAG, "MountService not running?");
1549                        }
1550                    }
1551                } break;
1552                case WRITE_SETTINGS: {
1553                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1554                    synchronized (mPackages) {
1555                        removeMessages(WRITE_SETTINGS);
1556                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1557                        mSettings.writeLPr();
1558                        mDirtyUsers.clear();
1559                    }
1560                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1561                } break;
1562                case WRITE_PACKAGE_RESTRICTIONS: {
1563                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1564                    synchronized (mPackages) {
1565                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1566                        for (int userId : mDirtyUsers) {
1567                            mSettings.writePackageRestrictionsLPr(userId);
1568                        }
1569                        mDirtyUsers.clear();
1570                    }
1571                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1572                } break;
1573                case CHECK_PENDING_VERIFICATION: {
1574                    final int verificationId = msg.arg1;
1575                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1576
1577                    if ((state != null) && !state.timeoutExtended()) {
1578                        final InstallArgs args = state.getInstallArgs();
1579                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1580
1581                        Slog.i(TAG, "Verification timed out for " + originUri);
1582                        mPendingVerification.remove(verificationId);
1583
1584                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1585
1586                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1587                            Slog.i(TAG, "Continuing with installation of " + originUri);
1588                            state.setVerifierResponse(Binder.getCallingUid(),
1589                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1590                            broadcastPackageVerified(verificationId, originUri,
1591                                    PackageManager.VERIFICATION_ALLOW,
1592                                    state.getInstallArgs().getUser());
1593                            try {
1594                                ret = args.copyApk(mContainerService, true);
1595                            } catch (RemoteException e) {
1596                                Slog.e(TAG, "Could not contact the ContainerService");
1597                            }
1598                        } else {
1599                            broadcastPackageVerified(verificationId, originUri,
1600                                    PackageManager.VERIFICATION_REJECT,
1601                                    state.getInstallArgs().getUser());
1602                        }
1603
1604                        Trace.asyncTraceEnd(
1605                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1606
1607                        processPendingInstall(args, ret);
1608                        mHandler.sendEmptyMessage(MCS_UNBIND);
1609                    }
1610                    break;
1611                }
1612                case PACKAGE_VERIFIED: {
1613                    final int verificationId = msg.arg1;
1614
1615                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1616                    if (state == null) {
1617                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1618                        break;
1619                    }
1620
1621                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1622
1623                    state.setVerifierResponse(response.callerUid, response.code);
1624
1625                    if (state.isVerificationComplete()) {
1626                        mPendingVerification.remove(verificationId);
1627
1628                        final InstallArgs args = state.getInstallArgs();
1629                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1630
1631                        int ret;
1632                        if (state.isInstallAllowed()) {
1633                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1634                            broadcastPackageVerified(verificationId, originUri,
1635                                    response.code, state.getInstallArgs().getUser());
1636                            try {
1637                                ret = args.copyApk(mContainerService, true);
1638                            } catch (RemoteException e) {
1639                                Slog.e(TAG, "Could not contact the ContainerService");
1640                            }
1641                        } else {
1642                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1643                        }
1644
1645                        Trace.asyncTraceEnd(
1646                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1647
1648                        processPendingInstall(args, ret);
1649                        mHandler.sendEmptyMessage(MCS_UNBIND);
1650                    }
1651
1652                    break;
1653                }
1654                case START_INTENT_FILTER_VERIFICATIONS: {
1655                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1656                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1657                            params.replacing, params.pkg);
1658                    break;
1659                }
1660                case INTENT_FILTER_VERIFIED: {
1661                    final int verificationId = msg.arg1;
1662
1663                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1664                            verificationId);
1665                    if (state == null) {
1666                        Slog.w(TAG, "Invalid IntentFilter verification token "
1667                                + verificationId + " received");
1668                        break;
1669                    }
1670
1671                    final int userId = state.getUserId();
1672
1673                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1674                            "Processing IntentFilter verification with token:"
1675                            + verificationId + " and userId:" + userId);
1676
1677                    final IntentFilterVerificationResponse response =
1678                            (IntentFilterVerificationResponse) msg.obj;
1679
1680                    state.setVerifierResponse(response.callerUid, response.code);
1681
1682                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1683                            "IntentFilter verification with token:" + verificationId
1684                            + " and userId:" + userId
1685                            + " is settings verifier response with response code:"
1686                            + response.code);
1687
1688                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1689                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1690                                + response.getFailedDomainsString());
1691                    }
1692
1693                    if (state.isVerificationComplete()) {
1694                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1695                    } else {
1696                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1697                                "IntentFilter verification with token:" + verificationId
1698                                + " was not said to be complete");
1699                    }
1700
1701                    break;
1702                }
1703            }
1704        }
1705    }
1706
1707    private StorageEventListener mStorageListener = new StorageEventListener() {
1708        @Override
1709        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1710            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1711                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1712                    final String volumeUuid = vol.getFsUuid();
1713
1714                    // Clean up any users or apps that were removed or recreated
1715                    // while this volume was missing
1716                    reconcileUsers(volumeUuid);
1717                    reconcileApps(volumeUuid);
1718
1719                    // Clean up any install sessions that expired or were
1720                    // cancelled while this volume was missing
1721                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1722
1723                    loadPrivatePackages(vol);
1724
1725                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1726                    unloadPrivatePackages(vol);
1727                }
1728            }
1729
1730            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1731                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1732                    updateExternalMediaStatus(true, false);
1733                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1734                    updateExternalMediaStatus(false, false);
1735                }
1736            }
1737        }
1738
1739        @Override
1740        public void onVolumeForgotten(String fsUuid) {
1741            if (TextUtils.isEmpty(fsUuid)) {
1742                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1743                return;
1744            }
1745
1746            // Remove any apps installed on the forgotten volume
1747            synchronized (mPackages) {
1748                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1749                for (PackageSetting ps : packages) {
1750                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1751                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1752                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1753                }
1754
1755                mSettings.onVolumeForgotten(fsUuid);
1756                mSettings.writeLPr();
1757            }
1758        }
1759    };
1760
1761    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1762            String[] grantedPermissions) {
1763        if (userId >= UserHandle.USER_SYSTEM) {
1764            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1765        } else if (userId == UserHandle.USER_ALL) {
1766            final int[] userIds;
1767            synchronized (mPackages) {
1768                userIds = UserManagerService.getInstance().getUserIds();
1769            }
1770            for (int someUserId : userIds) {
1771                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1772            }
1773        }
1774
1775        // We could have touched GID membership, so flush out packages.list
1776        synchronized (mPackages) {
1777            mSettings.writePackageListLPr();
1778        }
1779    }
1780
1781    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1782            String[] grantedPermissions) {
1783        SettingBase sb = (SettingBase) pkg.mExtras;
1784        if (sb == null) {
1785            return;
1786        }
1787
1788        PermissionsState permissionsState = sb.getPermissionsState();
1789
1790        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1791                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1792
1793        synchronized (mPackages) {
1794            for (String permission : pkg.requestedPermissions) {
1795                BasePermission bp = mSettings.mPermissions.get(permission);
1796                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1797                        && (grantedPermissions == null
1798                               || ArrayUtils.contains(grantedPermissions, permission))) {
1799                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1800                    // Installer cannot change immutable permissions.
1801                    if ((flags & immutableFlags) == 0) {
1802                        grantRuntimePermission(pkg.packageName, permission, userId);
1803                    }
1804                }
1805            }
1806        }
1807    }
1808
1809    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1810        Bundle extras = null;
1811        switch (res.returnCode) {
1812            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1813                extras = new Bundle();
1814                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1815                        res.origPermission);
1816                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1817                        res.origPackage);
1818                break;
1819            }
1820            case PackageManager.INSTALL_SUCCEEDED: {
1821                extras = new Bundle();
1822                extras.putBoolean(Intent.EXTRA_REPLACING,
1823                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1824                break;
1825            }
1826        }
1827        return extras;
1828    }
1829
1830    void scheduleWriteSettingsLocked() {
1831        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1832            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1833        }
1834    }
1835
1836    void scheduleWritePackageRestrictionsLocked(int userId) {
1837        if (!sUserManager.exists(userId)) return;
1838        mDirtyUsers.add(userId);
1839        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1840            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1841        }
1842    }
1843
1844    public static PackageManagerService main(Context context, Installer installer,
1845            boolean factoryTest, boolean onlyCore) {
1846        PackageManagerService m = new PackageManagerService(context, installer,
1847                factoryTest, onlyCore);
1848        m.enableSystemUserApps();
1849        ServiceManager.addService("package", m);
1850        return m;
1851    }
1852
1853    private void enableSystemUserApps() {
1854        if (!UserManager.isSplitSystemUser()) {
1855            return;
1856        }
1857        // For system user, enable apps based on the following conditions:
1858        // - app is whitelisted or belong to one of these groups:
1859        //   -- system app which has no launcher icons
1860        //   -- system app which has INTERACT_ACROSS_USERS permission
1861        //   -- system IME app
1862        // - app is not in the blacklist
1863        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1864        Set<String> enableApps = new ArraySet<>();
1865        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1866                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1867                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1868        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1869        enableApps.addAll(wlApps);
1870        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1871        enableApps.removeAll(blApps);
1872
1873        List<String> systemApps = queryHelper.queryApps(0, /* systemAppsOnly */ true,
1874                UserHandle.SYSTEM);
1875        final int systemAppsSize = systemApps.size();
1876        synchronized (mPackages) {
1877            for (int i = 0; i < systemAppsSize; i++) {
1878                String pName = systemApps.get(i);
1879                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1880                // Should not happen, but we shouldn't be failing if it does
1881                if (pkgSetting == null) {
1882                    continue;
1883                }
1884                boolean installed = enableApps.contains(pName);
1885                pkgSetting.setInstalled(installed, UserHandle.USER_SYSTEM);
1886            }
1887        }
1888    }
1889
1890    static String[] splitString(String str, char sep) {
1891        int count = 1;
1892        int i = 0;
1893        while ((i=str.indexOf(sep, i)) >= 0) {
1894            count++;
1895            i++;
1896        }
1897
1898        String[] res = new String[count];
1899        i=0;
1900        count = 0;
1901        int lastI=0;
1902        while ((i=str.indexOf(sep, i)) >= 0) {
1903            res[count] = str.substring(lastI, i);
1904            count++;
1905            i++;
1906            lastI = i;
1907        }
1908        res[count] = str.substring(lastI, str.length());
1909        return res;
1910    }
1911
1912    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1913        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1914                Context.DISPLAY_SERVICE);
1915        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1916    }
1917
1918    public PackageManagerService(Context context, Installer installer,
1919            boolean factoryTest, boolean onlyCore) {
1920        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1921                SystemClock.uptimeMillis());
1922
1923        if (mSdkVersion <= 0) {
1924            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1925        }
1926
1927        mContext = context;
1928        mFactoryTest = factoryTest;
1929        mOnlyCore = onlyCore;
1930        mMetrics = new DisplayMetrics();
1931        mSettings = new Settings(mPackages);
1932        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1933                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1934        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1935                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1936        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1937                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1938        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1939                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1940        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1941                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1942        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1943                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1944
1945        String separateProcesses = SystemProperties.get("debug.separate_processes");
1946        if (separateProcesses != null && separateProcesses.length() > 0) {
1947            if ("*".equals(separateProcesses)) {
1948                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1949                mSeparateProcesses = null;
1950                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1951            } else {
1952                mDefParseFlags = 0;
1953                mSeparateProcesses = separateProcesses.split(",");
1954                Slog.w(TAG, "Running with debug.separate_processes: "
1955                        + separateProcesses);
1956            }
1957        } else {
1958            mDefParseFlags = 0;
1959            mSeparateProcesses = null;
1960        }
1961
1962        mInstaller = installer;
1963        mPackageDexOptimizer = new PackageDexOptimizer(this);
1964        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1965
1966        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1967                FgThread.get().getLooper());
1968
1969        getDefaultDisplayMetrics(context, mMetrics);
1970
1971        SystemConfig systemConfig = SystemConfig.getInstance();
1972        mGlobalGids = systemConfig.getGlobalGids();
1973        mSystemPermissions = systemConfig.getSystemPermissions();
1974        mAvailableFeatures = systemConfig.getAvailableFeatures();
1975
1976        synchronized (mInstallLock) {
1977        // writer
1978        synchronized (mPackages) {
1979            mHandlerThread = new ServiceThread(TAG,
1980                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1981            mHandlerThread.start();
1982            mHandler = new PackageHandler(mHandlerThread.getLooper());
1983            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1984
1985            File dataDir = Environment.getDataDirectory();
1986            mAppInstallDir = new File(dataDir, "app");
1987            mAppLib32InstallDir = new File(dataDir, "app-lib");
1988            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1989            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1990            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1991
1992            sUserManager = new UserManagerService(context, this, mPackages);
1993
1994            // Propagate permission configuration in to package manager.
1995            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1996                    = systemConfig.getPermissions();
1997            for (int i=0; i<permConfig.size(); i++) {
1998                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1999                BasePermission bp = mSettings.mPermissions.get(perm.name);
2000                if (bp == null) {
2001                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2002                    mSettings.mPermissions.put(perm.name, bp);
2003                }
2004                if (perm.gids != null) {
2005                    bp.setGids(perm.gids, perm.perUser);
2006                }
2007            }
2008
2009            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2010            for (int i=0; i<libConfig.size(); i++) {
2011                mSharedLibraries.put(libConfig.keyAt(i),
2012                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2013            }
2014
2015            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2016
2017            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2018
2019            String customResolverActivity = Resources.getSystem().getString(
2020                    R.string.config_customResolverActivity);
2021            if (TextUtils.isEmpty(customResolverActivity)) {
2022                customResolverActivity = null;
2023            } else {
2024                mCustomResolverComponentName = ComponentName.unflattenFromString(
2025                        customResolverActivity);
2026            }
2027
2028            long startTime = SystemClock.uptimeMillis();
2029
2030            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2031                    startTime);
2032
2033            // Set flag to monitor and not change apk file paths when
2034            // scanning install directories.
2035            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2036
2037            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2038            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2039
2040            if (bootClassPath == null) {
2041                Slog.w(TAG, "No BOOTCLASSPATH found!");
2042            }
2043
2044            if (systemServerClassPath == null) {
2045                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2046            }
2047
2048            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2049            final String[] dexCodeInstructionSets =
2050                    getDexCodeInstructionSets(
2051                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2052
2053            /**
2054             * Ensure all external libraries have had dexopt run on them.
2055             */
2056            if (mSharedLibraries.size() > 0) {
2057                // NOTE: For now, we're compiling these system "shared libraries"
2058                // (and framework jars) into all available architectures. It's possible
2059                // to compile them only when we come across an app that uses them (there's
2060                // already logic for that in scanPackageLI) but that adds some complexity.
2061                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2062                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2063                        final String lib = libEntry.path;
2064                        if (lib == null) {
2065                            continue;
2066                        }
2067
2068                        try {
2069                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2070                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2071                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2072                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2073                            }
2074                        } catch (FileNotFoundException e) {
2075                            Slog.w(TAG, "Library not found: " + lib);
2076                        } catch (IOException e) {
2077                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2078                                    + e.getMessage());
2079                        }
2080                    }
2081                }
2082            }
2083
2084            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2085
2086            final VersionInfo ver = mSettings.getInternalVersion();
2087            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2088            // when upgrading from pre-M, promote system app permissions from install to runtime
2089            mPromoteSystemApps =
2090                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2091
2092            // save off the names of pre-existing system packages prior to scanning; we don't
2093            // want to automatically grant runtime permissions for new system apps
2094            if (mPromoteSystemApps) {
2095                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2096                while (pkgSettingIter.hasNext()) {
2097                    PackageSetting ps = pkgSettingIter.next();
2098                    if (isSystemApp(ps)) {
2099                        mExistingSystemPackages.add(ps.name);
2100                    }
2101                }
2102            }
2103
2104            // Collect vendor overlay packages.
2105            // (Do this before scanning any apps.)
2106            // For security and version matching reason, only consider
2107            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2108            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2109            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2110                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2111
2112            // Find base frameworks (resource packages without code).
2113            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2114                    | PackageParser.PARSE_IS_SYSTEM_DIR
2115                    | PackageParser.PARSE_IS_PRIVILEGED,
2116                    scanFlags | SCAN_NO_DEX, 0);
2117
2118            // Collected privileged system packages.
2119            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2120            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2121                    | PackageParser.PARSE_IS_SYSTEM_DIR
2122                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2123
2124            // Collect ordinary system packages.
2125            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2126            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2127                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2128
2129            // Collect all vendor packages.
2130            File vendorAppDir = new File("/vendor/app");
2131            try {
2132                vendorAppDir = vendorAppDir.getCanonicalFile();
2133            } catch (IOException e) {
2134                // failed to look up canonical path, continue with original one
2135            }
2136            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2137                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2138
2139            // Collect all OEM packages.
2140            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2141            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2142                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2143
2144            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2145            mInstaller.moveFiles();
2146
2147            // Prune any system packages that no longer exist.
2148            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2149            if (!mOnlyCore) {
2150                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2151                while (psit.hasNext()) {
2152                    PackageSetting ps = psit.next();
2153
2154                    /*
2155                     * If this is not a system app, it can't be a
2156                     * disable system app.
2157                     */
2158                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2159                        continue;
2160                    }
2161
2162                    /*
2163                     * If the package is scanned, it's not erased.
2164                     */
2165                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2166                    if (scannedPkg != null) {
2167                        /*
2168                         * If the system app is both scanned and in the
2169                         * disabled packages list, then it must have been
2170                         * added via OTA. Remove it from the currently
2171                         * scanned package so the previously user-installed
2172                         * application can be scanned.
2173                         */
2174                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2175                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2176                                    + ps.name + "; removing system app.  Last known codePath="
2177                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2178                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2179                                    + scannedPkg.mVersionCode);
2180                            removePackageLI(ps, true);
2181                            mExpectingBetter.put(ps.name, ps.codePath);
2182                        }
2183
2184                        continue;
2185                    }
2186
2187                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2188                        psit.remove();
2189                        logCriticalInfo(Log.WARN, "System package " + ps.name
2190                                + " no longer exists; wiping its data");
2191                        removeDataDirsLI(null, ps.name);
2192                    } else {
2193                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2194                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2195                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2196                        }
2197                    }
2198                }
2199            }
2200
2201            //look for any incomplete package installations
2202            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2203            //clean up list
2204            for(int i = 0; i < deletePkgsList.size(); i++) {
2205                //clean up here
2206                cleanupInstallFailedPackage(deletePkgsList.get(i));
2207            }
2208            //delete tmp files
2209            deleteTempPackageFiles();
2210
2211            // Remove any shared userIDs that have no associated packages
2212            mSettings.pruneSharedUsersLPw();
2213
2214            if (!mOnlyCore) {
2215                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2216                        SystemClock.uptimeMillis());
2217                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2218
2219                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2220                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2221
2222                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2223                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2224
2225                /**
2226                 * Remove disable package settings for any updated system
2227                 * apps that were removed via an OTA. If they're not a
2228                 * previously-updated app, remove them completely.
2229                 * Otherwise, just revoke their system-level permissions.
2230                 */
2231                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2232                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2233                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2234
2235                    String msg;
2236                    if (deletedPkg == null) {
2237                        msg = "Updated system package " + deletedAppName
2238                                + " no longer exists; wiping its data";
2239                        removeDataDirsLI(null, deletedAppName);
2240                    } else {
2241                        msg = "Updated system app + " + deletedAppName
2242                                + " no longer present; removing system privileges for "
2243                                + deletedAppName;
2244
2245                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2246
2247                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2248                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2249                    }
2250                    logCriticalInfo(Log.WARN, msg);
2251                }
2252
2253                /**
2254                 * Make sure all system apps that we expected to appear on
2255                 * the userdata partition actually showed up. If they never
2256                 * appeared, crawl back and revive the system version.
2257                 */
2258                for (int i = 0; i < mExpectingBetter.size(); i++) {
2259                    final String packageName = mExpectingBetter.keyAt(i);
2260                    if (!mPackages.containsKey(packageName)) {
2261                        final File scanFile = mExpectingBetter.valueAt(i);
2262
2263                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2264                                + " but never showed up; reverting to system");
2265
2266                        final int reparseFlags;
2267                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2268                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2269                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2270                                    | PackageParser.PARSE_IS_PRIVILEGED;
2271                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2272                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2273                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2274                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2275                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2276                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2277                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2278                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2279                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2280                        } else {
2281                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2282                            continue;
2283                        }
2284
2285                        mSettings.enableSystemPackageLPw(packageName);
2286
2287                        try {
2288                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2289                        } catch (PackageManagerException e) {
2290                            Slog.e(TAG, "Failed to parse original system package: "
2291                                    + e.getMessage());
2292                        }
2293                    }
2294                }
2295            }
2296            mExpectingBetter.clear();
2297
2298            // Now that we know all of the shared libraries, update all clients to have
2299            // the correct library paths.
2300            updateAllSharedLibrariesLPw();
2301
2302            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2303                // NOTE: We ignore potential failures here during a system scan (like
2304                // the rest of the commands above) because there's precious little we
2305                // can do about it. A settings error is reported, though.
2306                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2307                        false /* boot complete */);
2308            }
2309
2310            // Now that we know all the packages we are keeping,
2311            // read and update their last usage times.
2312            mPackageUsage.readLP();
2313
2314            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2315                    SystemClock.uptimeMillis());
2316            Slog.i(TAG, "Time to scan packages: "
2317                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2318                    + " seconds");
2319
2320            // If the platform SDK has changed since the last time we booted,
2321            // we need to re-grant app permission to catch any new ones that
2322            // appear.  This is really a hack, and means that apps can in some
2323            // cases get permissions that the user didn't initially explicitly
2324            // allow...  it would be nice to have some better way to handle
2325            // this situation.
2326            int updateFlags = UPDATE_PERMISSIONS_ALL;
2327            if (ver.sdkVersion != mSdkVersion) {
2328                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2329                        + mSdkVersion + "; regranting permissions for internal storage");
2330                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2331            }
2332            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2333            ver.sdkVersion = mSdkVersion;
2334
2335            // If this is the first boot or an update from pre-M, and it is a normal
2336            // boot, then we need to initialize the default preferred apps across
2337            // all defined users.
2338            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2339                for (UserInfo user : sUserManager.getUsers(true)) {
2340                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2341                    applyFactoryDefaultBrowserLPw(user.id);
2342                    primeDomainVerificationsLPw(user.id);
2343                }
2344            }
2345
2346            // If this is first boot after an OTA, and a normal boot, then
2347            // we need to clear code cache directories.
2348            if (mIsUpgrade && !onlyCore) {
2349                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2350                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2351                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2352                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2353                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2354                    }
2355                }
2356                ver.fingerprint = Build.FINGERPRINT;
2357            }
2358
2359            checkDefaultBrowser();
2360
2361            // clear only after permissions and other defaults have been updated
2362            mExistingSystemPackages.clear();
2363            mPromoteSystemApps = false;
2364
2365            // All the changes are done during package scanning.
2366            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2367
2368            // can downgrade to reader
2369            mSettings.writeLPr();
2370
2371            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2372                    SystemClock.uptimeMillis());
2373
2374            mRequiredVerifierPackage = getRequiredVerifierLPr();
2375            mRequiredInstallerPackage = getRequiredInstallerLPr();
2376
2377            mInstallerService = new PackageInstallerService(context, this);
2378
2379            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2380            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2381                    mIntentFilterVerifierComponent);
2382
2383            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2384            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2385            // both the installer and resolver must be present to enable ephemeral
2386            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2387                if (DEBUG_EPHEMERAL) {
2388                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2389                            + " installer:" + ephemeralInstallerComponent);
2390                }
2391                mEphemeralResolverComponent = ephemeralResolverComponent;
2392                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2393                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2394                mEphemeralResolverConnection =
2395                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2396            } else {
2397                if (DEBUG_EPHEMERAL) {
2398                    final String missingComponent =
2399                            (ephemeralResolverComponent == null)
2400                            ? (ephemeralInstallerComponent == null)
2401                                    ? "resolver and installer"
2402                                    : "resolver"
2403                            : "installer";
2404                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2405                }
2406                mEphemeralResolverComponent = null;
2407                mEphemeralInstallerComponent = null;
2408                mEphemeralResolverConnection = null;
2409            }
2410
2411            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2412        } // synchronized (mPackages)
2413        } // synchronized (mInstallLock)
2414
2415        // Now after opening every single application zip, make sure they
2416        // are all flushed.  Not really needed, but keeps things nice and
2417        // tidy.
2418        Runtime.getRuntime().gc();
2419
2420        // The initial scanning above does many calls into installd while
2421        // holding the mPackages lock, but we're mostly interested in yelling
2422        // once we have a booted system.
2423        mInstaller.setWarnIfHeld(mPackages);
2424
2425        // Expose private service for system components to use.
2426        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2427    }
2428
2429    @Override
2430    public boolean isFirstBoot() {
2431        return !mRestoredSettings;
2432    }
2433
2434    @Override
2435    public boolean isOnlyCoreApps() {
2436        return mOnlyCore;
2437    }
2438
2439    @Override
2440    public boolean isUpgrade() {
2441        return mIsUpgrade;
2442    }
2443
2444    private String getRequiredVerifierLPr() {
2445        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2446        // We only care about verifier that's installed under system user.
2447        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2448                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2449
2450        String requiredVerifier = null;
2451
2452        final int N = receivers.size();
2453        for (int i = 0; i < N; i++) {
2454            final ResolveInfo info = receivers.get(i);
2455
2456            if (info.activityInfo == null) {
2457                continue;
2458            }
2459
2460            final String packageName = info.activityInfo.packageName;
2461
2462            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2463                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2464                continue;
2465            }
2466
2467            if (requiredVerifier != null) {
2468                throw new RuntimeException("There can be only one required verifier");
2469            }
2470
2471            requiredVerifier = packageName;
2472        }
2473
2474        return requiredVerifier;
2475    }
2476
2477    private String getRequiredInstallerLPr() {
2478        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2479        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2480        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2481
2482        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2483                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2484
2485        String requiredInstaller = null;
2486
2487        final int N = installers.size();
2488        for (int i = 0; i < N; i++) {
2489            final ResolveInfo info = installers.get(i);
2490            final String packageName = info.activityInfo.packageName;
2491
2492            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2493                continue;
2494            }
2495
2496            if (requiredInstaller != null) {
2497                throw new RuntimeException("There must be one required installer");
2498            }
2499
2500            requiredInstaller = packageName;
2501        }
2502
2503        if (requiredInstaller == null) {
2504            throw new RuntimeException("There must be one required installer");
2505        }
2506
2507        return requiredInstaller;
2508    }
2509
2510    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2511        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2512        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2513                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2514
2515        ComponentName verifierComponentName = null;
2516
2517        int priority = -1000;
2518        final int N = receivers.size();
2519        for (int i = 0; i < N; i++) {
2520            final ResolveInfo info = receivers.get(i);
2521
2522            if (info.activityInfo == null) {
2523                continue;
2524            }
2525
2526            final String packageName = info.activityInfo.packageName;
2527
2528            final PackageSetting ps = mSettings.mPackages.get(packageName);
2529            if (ps == null) {
2530                continue;
2531            }
2532
2533            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2534                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2535                continue;
2536            }
2537
2538            // Select the IntentFilterVerifier with the highest priority
2539            if (priority < info.priority) {
2540                priority = info.priority;
2541                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2542                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2543                        + verifierComponentName + " with priority: " + info.priority);
2544            }
2545        }
2546
2547        return verifierComponentName;
2548    }
2549
2550    private ComponentName getEphemeralResolverLPr() {
2551        final String[] packageArray =
2552                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2553        if (packageArray.length == 0) {
2554            if (DEBUG_EPHEMERAL) {
2555                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2556            }
2557            return null;
2558        }
2559
2560        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2561        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2562                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2563
2564        final int N = resolvers.size();
2565        if (N == 0) {
2566            if (DEBUG_EPHEMERAL) {
2567                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2568            }
2569            return null;
2570        }
2571
2572        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2573        for (int i = 0; i < N; i++) {
2574            final ResolveInfo info = resolvers.get(i);
2575
2576            if (info.serviceInfo == null) {
2577                continue;
2578            }
2579
2580            final String packageName = info.serviceInfo.packageName;
2581            if (!possiblePackages.contains(packageName)) {
2582                if (DEBUG_EPHEMERAL) {
2583                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2584                            + " pkg: " + packageName + ", info:" + info);
2585                }
2586                continue;
2587            }
2588
2589            if (DEBUG_EPHEMERAL) {
2590                Slog.v(TAG, "Ephemeral resolver found;"
2591                        + " pkg: " + packageName + ", info:" + info);
2592            }
2593            return new ComponentName(packageName, info.serviceInfo.name);
2594        }
2595        if (DEBUG_EPHEMERAL) {
2596            Slog.v(TAG, "Ephemeral resolver NOT found");
2597        }
2598        return null;
2599    }
2600
2601    private ComponentName getEphemeralInstallerLPr() {
2602        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2603        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2604        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2605        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2606                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2607
2608        ComponentName ephemeralInstaller = null;
2609
2610        final int N = installers.size();
2611        for (int i = 0; i < N; i++) {
2612            final ResolveInfo info = installers.get(i);
2613            final String packageName = info.activityInfo.packageName;
2614
2615            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2616                if (DEBUG_EPHEMERAL) {
2617                    Slog.d(TAG, "Ephemeral installer is not system app;"
2618                            + " pkg: " + packageName + ", info:" + info);
2619                }
2620                continue;
2621            }
2622
2623            if (ephemeralInstaller != null) {
2624                throw new RuntimeException("There must only be one ephemeral installer");
2625            }
2626
2627            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2628        }
2629
2630        return ephemeralInstaller;
2631    }
2632
2633    private void primeDomainVerificationsLPw(int userId) {
2634        if (DEBUG_DOMAIN_VERIFICATION) {
2635            Slog.d(TAG, "Priming domain verifications in user " + userId);
2636        }
2637
2638        SystemConfig systemConfig = SystemConfig.getInstance();
2639        ArraySet<String> packages = systemConfig.getLinkedApps();
2640        ArraySet<String> domains = new ArraySet<String>();
2641
2642        for (String packageName : packages) {
2643            PackageParser.Package pkg = mPackages.get(packageName);
2644            if (pkg != null) {
2645                if (!pkg.isSystemApp()) {
2646                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2647                    continue;
2648                }
2649
2650                domains.clear();
2651                for (PackageParser.Activity a : pkg.activities) {
2652                    for (ActivityIntentInfo filter : a.intents) {
2653                        if (hasValidDomains(filter)) {
2654                            domains.addAll(filter.getHostsList());
2655                        }
2656                    }
2657                }
2658
2659                if (domains.size() > 0) {
2660                    if (DEBUG_DOMAIN_VERIFICATION) {
2661                        Slog.v(TAG, "      + " + packageName);
2662                    }
2663                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2664                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2665                    // and then 'always' in the per-user state actually used for intent resolution.
2666                    final IntentFilterVerificationInfo ivi;
2667                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2668                            new ArrayList<String>(domains));
2669                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2670                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2671                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2672                } else {
2673                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2674                            + "' does not handle web links");
2675                }
2676            } else {
2677                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2678            }
2679        }
2680
2681        scheduleWritePackageRestrictionsLocked(userId);
2682        scheduleWriteSettingsLocked();
2683    }
2684
2685    private void applyFactoryDefaultBrowserLPw(int userId) {
2686        // The default browser app's package name is stored in a string resource,
2687        // with a product-specific overlay used for vendor customization.
2688        String browserPkg = mContext.getResources().getString(
2689                com.android.internal.R.string.default_browser);
2690        if (!TextUtils.isEmpty(browserPkg)) {
2691            // non-empty string => required to be a known package
2692            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2693            if (ps == null) {
2694                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2695                browserPkg = null;
2696            } else {
2697                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2698            }
2699        }
2700
2701        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2702        // default.  If there's more than one, just leave everything alone.
2703        if (browserPkg == null) {
2704            calculateDefaultBrowserLPw(userId);
2705        }
2706    }
2707
2708    private void calculateDefaultBrowserLPw(int userId) {
2709        List<String> allBrowsers = resolveAllBrowserApps(userId);
2710        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2711        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2712    }
2713
2714    private List<String> resolveAllBrowserApps(int userId) {
2715        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2716        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2717                PackageManager.MATCH_ALL, userId);
2718
2719        final int count = list.size();
2720        List<String> result = new ArrayList<String>(count);
2721        for (int i=0; i<count; i++) {
2722            ResolveInfo info = list.get(i);
2723            if (info.activityInfo == null
2724                    || !info.handleAllWebDataURI
2725                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2726                    || result.contains(info.activityInfo.packageName)) {
2727                continue;
2728            }
2729            result.add(info.activityInfo.packageName);
2730        }
2731
2732        return result;
2733    }
2734
2735    private boolean packageIsBrowser(String packageName, int userId) {
2736        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2737                PackageManager.MATCH_ALL, userId);
2738        final int N = list.size();
2739        for (int i = 0; i < N; i++) {
2740            ResolveInfo info = list.get(i);
2741            if (packageName.equals(info.activityInfo.packageName)) {
2742                return true;
2743            }
2744        }
2745        return false;
2746    }
2747
2748    private void checkDefaultBrowser() {
2749        final int myUserId = UserHandle.myUserId();
2750        final String packageName = getDefaultBrowserPackageName(myUserId);
2751        if (packageName != null) {
2752            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2753            if (info == null) {
2754                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2755                synchronized (mPackages) {
2756                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2757                }
2758            }
2759        }
2760    }
2761
2762    @Override
2763    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2764            throws RemoteException {
2765        try {
2766            return super.onTransact(code, data, reply, flags);
2767        } catch (RuntimeException e) {
2768            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2769                Slog.wtf(TAG, "Package Manager Crash", e);
2770            }
2771            throw e;
2772        }
2773    }
2774
2775    void cleanupInstallFailedPackage(PackageSetting ps) {
2776        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2777
2778        removeDataDirsLI(ps.volumeUuid, ps.name);
2779        if (ps.codePath != null) {
2780            if (ps.codePath.isDirectory()) {
2781                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2782            } else {
2783                ps.codePath.delete();
2784            }
2785        }
2786        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2787            if (ps.resourcePath.isDirectory()) {
2788                FileUtils.deleteContents(ps.resourcePath);
2789            }
2790            ps.resourcePath.delete();
2791        }
2792        mSettings.removePackageLPw(ps.name);
2793    }
2794
2795    static int[] appendInts(int[] cur, int[] add) {
2796        if (add == null) return cur;
2797        if (cur == null) return add;
2798        final int N = add.length;
2799        for (int i=0; i<N; i++) {
2800            cur = appendInt(cur, add[i]);
2801        }
2802        return cur;
2803    }
2804
2805    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2806        if (!sUserManager.exists(userId)) return null;
2807        final PackageSetting ps = (PackageSetting) p.mExtras;
2808        if (ps == null) {
2809            return null;
2810        }
2811
2812        final PermissionsState permissionsState = ps.getPermissionsState();
2813
2814        final int[] gids = permissionsState.computeGids(userId);
2815        final Set<String> permissions = permissionsState.getPermissions(userId);
2816        final PackageUserState state = ps.readUserState(userId);
2817
2818        return PackageParser.generatePackageInfo(p, gids, flags,
2819                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2820    }
2821
2822    @Override
2823    public void checkPackageStartable(String packageName, int userId) {
2824        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2825
2826        synchronized (mPackages) {
2827            final PackageSetting ps = mSettings.mPackages.get(packageName);
2828            if (ps == null) {
2829                throw new SecurityException("Package " + packageName + " was not found!");
2830            }
2831
2832            if (ps.frozen) {
2833                throw new SecurityException("Package " + packageName + " is currently frozen!");
2834            }
2835
2836            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2837                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2838                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2839            }
2840        }
2841    }
2842
2843    @Override
2844    public boolean isPackageAvailable(String packageName, int userId) {
2845        if (!sUserManager.exists(userId)) return false;
2846        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2847        synchronized (mPackages) {
2848            PackageParser.Package p = mPackages.get(packageName);
2849            if (p != null) {
2850                final PackageSetting ps = (PackageSetting) p.mExtras;
2851                if (ps != null) {
2852                    final PackageUserState state = ps.readUserState(userId);
2853                    if (state != null) {
2854                        return PackageParser.isAvailable(state);
2855                    }
2856                }
2857            }
2858        }
2859        return false;
2860    }
2861
2862    @Override
2863    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2864        if (!sUserManager.exists(userId)) return null;
2865        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2866        // reader
2867        synchronized (mPackages) {
2868            PackageParser.Package p = mPackages.get(packageName);
2869            if (DEBUG_PACKAGE_INFO)
2870                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2871            if (p != null) {
2872                return generatePackageInfo(p, flags, userId);
2873            }
2874            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2875                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2876            }
2877        }
2878        return null;
2879    }
2880
2881    @Override
2882    public String[] currentToCanonicalPackageNames(String[] names) {
2883        String[] out = new String[names.length];
2884        // reader
2885        synchronized (mPackages) {
2886            for (int i=names.length-1; i>=0; i--) {
2887                PackageSetting ps = mSettings.mPackages.get(names[i]);
2888                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2889            }
2890        }
2891        return out;
2892    }
2893
2894    @Override
2895    public String[] canonicalToCurrentPackageNames(String[] names) {
2896        String[] out = new String[names.length];
2897        // reader
2898        synchronized (mPackages) {
2899            for (int i=names.length-1; i>=0; i--) {
2900                String cur = mSettings.mRenamedPackages.get(names[i]);
2901                out[i] = cur != null ? cur : names[i];
2902            }
2903        }
2904        return out;
2905    }
2906
2907    @Override
2908    public int getPackageUid(String packageName, int userId) {
2909        return getPackageUidEtc(packageName, 0, userId);
2910    }
2911
2912    @Override
2913    public int getPackageUidEtc(String packageName, int flags, int userId) {
2914        if (!sUserManager.exists(userId)) return -1;
2915        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2916
2917        // reader
2918        synchronized (mPackages) {
2919            final PackageParser.Package p = mPackages.get(packageName);
2920            if (p != null) {
2921                return UserHandle.getUid(userId, p.applicationInfo.uid);
2922            }
2923            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2924                final PackageSetting ps = mSettings.mPackages.get(packageName);
2925                if (ps != null) {
2926                    return UserHandle.getUid(userId, ps.appId);
2927                }
2928            }
2929        }
2930
2931        return -1;
2932    }
2933
2934    @Override
2935    public int[] getPackageGids(String packageName, int userId) {
2936        return getPackageGidsEtc(packageName, 0, userId);
2937    }
2938
2939    @Override
2940    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2941        if (!sUserManager.exists(userId)) {
2942            return null;
2943        }
2944
2945        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2946                "getPackageGids");
2947
2948        // reader
2949        synchronized (mPackages) {
2950            final PackageParser.Package p = mPackages.get(packageName);
2951            if (p != null) {
2952                PackageSetting ps = (PackageSetting) p.mExtras;
2953                return ps.getPermissionsState().computeGids(userId);
2954            }
2955            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2956                final PackageSetting ps = mSettings.mPackages.get(packageName);
2957                if (ps != null) {
2958                    return ps.getPermissionsState().computeGids(userId);
2959                }
2960            }
2961        }
2962
2963        return null;
2964    }
2965
2966    static PermissionInfo generatePermissionInfo(
2967            BasePermission bp, int flags) {
2968        if (bp.perm != null) {
2969            return PackageParser.generatePermissionInfo(bp.perm, flags);
2970        }
2971        PermissionInfo pi = new PermissionInfo();
2972        pi.name = bp.name;
2973        pi.packageName = bp.sourcePackage;
2974        pi.nonLocalizedLabel = bp.name;
2975        pi.protectionLevel = bp.protectionLevel;
2976        return pi;
2977    }
2978
2979    @Override
2980    public PermissionInfo getPermissionInfo(String name, int flags) {
2981        // reader
2982        synchronized (mPackages) {
2983            final BasePermission p = mSettings.mPermissions.get(name);
2984            if (p != null) {
2985                return generatePermissionInfo(p, flags);
2986            }
2987            return null;
2988        }
2989    }
2990
2991    @Override
2992    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2993        // reader
2994        synchronized (mPackages) {
2995            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2996            for (BasePermission p : mSettings.mPermissions.values()) {
2997                if (group == null) {
2998                    if (p.perm == null || p.perm.info.group == null) {
2999                        out.add(generatePermissionInfo(p, flags));
3000                    }
3001                } else {
3002                    if (p.perm != null && group.equals(p.perm.info.group)) {
3003                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3004                    }
3005                }
3006            }
3007
3008            if (out.size() > 0) {
3009                return out;
3010            }
3011            return mPermissionGroups.containsKey(group) ? out : null;
3012        }
3013    }
3014
3015    @Override
3016    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3017        // reader
3018        synchronized (mPackages) {
3019            return PackageParser.generatePermissionGroupInfo(
3020                    mPermissionGroups.get(name), flags);
3021        }
3022    }
3023
3024    @Override
3025    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3026        // reader
3027        synchronized (mPackages) {
3028            final int N = mPermissionGroups.size();
3029            ArrayList<PermissionGroupInfo> out
3030                    = new ArrayList<PermissionGroupInfo>(N);
3031            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3032                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3033            }
3034            return out;
3035        }
3036    }
3037
3038    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3039            int userId) {
3040        if (!sUserManager.exists(userId)) return null;
3041        PackageSetting ps = mSettings.mPackages.get(packageName);
3042        if (ps != null) {
3043            if (ps.pkg == null) {
3044                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3045                        flags, userId);
3046                if (pInfo != null) {
3047                    return pInfo.applicationInfo;
3048                }
3049                return null;
3050            }
3051            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3052                    ps.readUserState(userId), userId);
3053        }
3054        return null;
3055    }
3056
3057    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3058            int userId) {
3059        if (!sUserManager.exists(userId)) return null;
3060        PackageSetting ps = mSettings.mPackages.get(packageName);
3061        if (ps != null) {
3062            PackageParser.Package pkg = ps.pkg;
3063            if (pkg == null) {
3064                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3065                    return null;
3066                }
3067                // Only data remains, so we aren't worried about code paths
3068                pkg = new PackageParser.Package(packageName);
3069                pkg.applicationInfo.packageName = packageName;
3070                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3071                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3072                pkg.applicationInfo.uid = ps.appId;
3073                pkg.applicationInfo.initForUser(userId);
3074                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3075                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3076            }
3077            return generatePackageInfo(pkg, flags, userId);
3078        }
3079        return null;
3080    }
3081
3082    @Override
3083    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3084        if (!sUserManager.exists(userId)) return null;
3085        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3086        // writer
3087        synchronized (mPackages) {
3088            PackageParser.Package p = mPackages.get(packageName);
3089            if (DEBUG_PACKAGE_INFO) Log.v(
3090                    TAG, "getApplicationInfo " + packageName
3091                    + ": " + p);
3092            if (p != null) {
3093                PackageSetting ps = mSettings.mPackages.get(packageName);
3094                if (ps == null) return null;
3095                // Note: isEnabledLP() does not apply here - always return info
3096                return PackageParser.generateApplicationInfo(
3097                        p, flags, ps.readUserState(userId), userId);
3098            }
3099            if ("android".equals(packageName)||"system".equals(packageName)) {
3100                return mAndroidApplication;
3101            }
3102            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3103                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3104            }
3105        }
3106        return null;
3107    }
3108
3109    @Override
3110    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3111            final IPackageDataObserver observer) {
3112        mContext.enforceCallingOrSelfPermission(
3113                android.Manifest.permission.CLEAR_APP_CACHE, null);
3114        // Queue up an async operation since clearing cache may take a little while.
3115        mHandler.post(new Runnable() {
3116            public void run() {
3117                mHandler.removeCallbacks(this);
3118                int retCode = -1;
3119                synchronized (mInstallLock) {
3120                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3121                    if (retCode < 0) {
3122                        Slog.w(TAG, "Couldn't clear application caches");
3123                    }
3124                }
3125                if (observer != null) {
3126                    try {
3127                        observer.onRemoveCompleted(null, (retCode >= 0));
3128                    } catch (RemoteException e) {
3129                        Slog.w(TAG, "RemoveException when invoking call back");
3130                    }
3131                }
3132            }
3133        });
3134    }
3135
3136    @Override
3137    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3138            final IntentSender pi) {
3139        mContext.enforceCallingOrSelfPermission(
3140                android.Manifest.permission.CLEAR_APP_CACHE, null);
3141        // Queue up an async operation since clearing cache may take a little while.
3142        mHandler.post(new Runnable() {
3143            public void run() {
3144                mHandler.removeCallbacks(this);
3145                int retCode = -1;
3146                synchronized (mInstallLock) {
3147                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3148                    if (retCode < 0) {
3149                        Slog.w(TAG, "Couldn't clear application caches");
3150                    }
3151                }
3152                if(pi != null) {
3153                    try {
3154                        // Callback via pending intent
3155                        int code = (retCode >= 0) ? 1 : 0;
3156                        pi.sendIntent(null, code, null,
3157                                null, null);
3158                    } catch (SendIntentException e1) {
3159                        Slog.i(TAG, "Failed to send pending intent");
3160                    }
3161                }
3162            }
3163        });
3164    }
3165
3166    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3167        synchronized (mInstallLock) {
3168            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3169                throw new IOException("Failed to free enough space");
3170            }
3171        }
3172    }
3173
3174    /**
3175     * Return if the user key is currently unlocked.
3176     */
3177    private boolean isUserKeyUnlocked(int userId) {
3178        if (StorageManager.isFileBasedEncryptionEnabled()) {
3179            final IMountService mount = IMountService.Stub
3180                    .asInterface(ServiceManager.getService("mount"));
3181            if (mount == null) {
3182                Slog.w(TAG, "Early during boot, assuming locked");
3183                return false;
3184            }
3185            final long token = Binder.clearCallingIdentity();
3186            try {
3187                return mount.isUserKeyUnlocked(userId);
3188            } catch (RemoteException e) {
3189                throw e.rethrowAsRuntimeException();
3190            } finally {
3191                Binder.restoreCallingIdentity(token);
3192            }
3193        } else {
3194            return true;
3195        }
3196    }
3197
3198    /**
3199     * Augment the given flags depending on current user running state. This is
3200     * purposefully done before acquiring {@link #mPackages} lock.
3201     */
3202    private int augmentFlagsForUser(int flags, int userId) {
3203        if (!isUserKeyUnlocked(userId)) {
3204            flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3205        }
3206        return flags;
3207    }
3208
3209    @Override
3210    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3211        if (!sUserManager.exists(userId)) return null;
3212        flags = augmentFlagsForUser(flags, userId);
3213        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3214        synchronized (mPackages) {
3215            PackageParser.Activity a = mActivities.mActivities.get(component);
3216
3217            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3218            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3219                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3220                if (ps == null) return null;
3221                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3222                        userId);
3223            }
3224            if (mResolveComponentName.equals(component)) {
3225                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3226                        new PackageUserState(), userId);
3227            }
3228        }
3229        return null;
3230    }
3231
3232    @Override
3233    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3234            String resolvedType) {
3235        synchronized (mPackages) {
3236            if (component.equals(mResolveComponentName)) {
3237                // The resolver supports EVERYTHING!
3238                return true;
3239            }
3240            PackageParser.Activity a = mActivities.mActivities.get(component);
3241            if (a == null) {
3242                return false;
3243            }
3244            for (int i=0; i<a.intents.size(); i++) {
3245                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3246                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3247                    return true;
3248                }
3249            }
3250            return false;
3251        }
3252    }
3253
3254    @Override
3255    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3256        if (!sUserManager.exists(userId)) return null;
3257        flags = augmentFlagsForUser(flags, userId);
3258        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3259        synchronized (mPackages) {
3260            PackageParser.Activity a = mReceivers.mActivities.get(component);
3261            if (DEBUG_PACKAGE_INFO) Log.v(
3262                TAG, "getReceiverInfo " + component + ": " + a);
3263            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3264                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3265                if (ps == null) return null;
3266                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3267                        userId);
3268            }
3269        }
3270        return null;
3271    }
3272
3273    @Override
3274    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3275        if (!sUserManager.exists(userId)) return null;
3276        flags = augmentFlagsForUser(flags, userId);
3277        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3278        synchronized (mPackages) {
3279            PackageParser.Service s = mServices.mServices.get(component);
3280            if (DEBUG_PACKAGE_INFO) Log.v(
3281                TAG, "getServiceInfo " + component + ": " + s);
3282            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3283                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3284                if (ps == null) return null;
3285                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3286                        userId);
3287            }
3288        }
3289        return null;
3290    }
3291
3292    @Override
3293    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3294        if (!sUserManager.exists(userId)) return null;
3295        flags = augmentFlagsForUser(flags, userId);
3296        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3297        synchronized (mPackages) {
3298            PackageParser.Provider p = mProviders.mProviders.get(component);
3299            if (DEBUG_PACKAGE_INFO) Log.v(
3300                TAG, "getProviderInfo " + component + ": " + p);
3301            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3302                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3303                if (ps == null) return null;
3304                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3305                        userId);
3306            }
3307        }
3308        return null;
3309    }
3310
3311    @Override
3312    public String[] getSystemSharedLibraryNames() {
3313        Set<String> libSet;
3314        synchronized (mPackages) {
3315            libSet = mSharedLibraries.keySet();
3316            int size = libSet.size();
3317            if (size > 0) {
3318                String[] libs = new String[size];
3319                libSet.toArray(libs);
3320                return libs;
3321            }
3322        }
3323        return null;
3324    }
3325
3326    /**
3327     * @hide
3328     */
3329    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3330        synchronized (mPackages) {
3331            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3332            if (lib != null && lib.apk != null) {
3333                return mPackages.get(lib.apk);
3334            }
3335        }
3336        return null;
3337    }
3338
3339    @Override
3340    public FeatureInfo[] getSystemAvailableFeatures() {
3341        Collection<FeatureInfo> featSet;
3342        synchronized (mPackages) {
3343            featSet = mAvailableFeatures.values();
3344            int size = featSet.size();
3345            if (size > 0) {
3346                FeatureInfo[] features = new FeatureInfo[size+1];
3347                featSet.toArray(features);
3348                FeatureInfo fi = new FeatureInfo();
3349                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3350                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3351                features[size] = fi;
3352                return features;
3353            }
3354        }
3355        return null;
3356    }
3357
3358    @Override
3359    public boolean hasSystemFeature(String name) {
3360        synchronized (mPackages) {
3361            return mAvailableFeatures.containsKey(name);
3362        }
3363    }
3364
3365    @Override
3366    public int checkPermission(String permName, String pkgName, int userId) {
3367        if (!sUserManager.exists(userId)) {
3368            return PackageManager.PERMISSION_DENIED;
3369        }
3370
3371        synchronized (mPackages) {
3372            final PackageParser.Package p = mPackages.get(pkgName);
3373            if (p != null && p.mExtras != null) {
3374                final PackageSetting ps = (PackageSetting) p.mExtras;
3375                final PermissionsState permissionsState = ps.getPermissionsState();
3376                if (permissionsState.hasPermission(permName, userId)) {
3377                    return PackageManager.PERMISSION_GRANTED;
3378                }
3379                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3380                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3381                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3382                    return PackageManager.PERMISSION_GRANTED;
3383                }
3384            }
3385        }
3386
3387        return PackageManager.PERMISSION_DENIED;
3388    }
3389
3390    @Override
3391    public int checkUidPermission(String permName, int uid) {
3392        final int userId = UserHandle.getUserId(uid);
3393
3394        if (!sUserManager.exists(userId)) {
3395            return PackageManager.PERMISSION_DENIED;
3396        }
3397
3398        synchronized (mPackages) {
3399            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3400            if (obj != null) {
3401                final SettingBase ps = (SettingBase) obj;
3402                final PermissionsState permissionsState = ps.getPermissionsState();
3403                if (permissionsState.hasPermission(permName, userId)) {
3404                    return PackageManager.PERMISSION_GRANTED;
3405                }
3406                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3407                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3408                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3409                    return PackageManager.PERMISSION_GRANTED;
3410                }
3411            } else {
3412                ArraySet<String> perms = mSystemPermissions.get(uid);
3413                if (perms != null) {
3414                    if (perms.contains(permName)) {
3415                        return PackageManager.PERMISSION_GRANTED;
3416                    }
3417                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3418                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3419                        return PackageManager.PERMISSION_GRANTED;
3420                    }
3421                }
3422            }
3423        }
3424
3425        return PackageManager.PERMISSION_DENIED;
3426    }
3427
3428    @Override
3429    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3430        if (UserHandle.getCallingUserId() != userId) {
3431            mContext.enforceCallingPermission(
3432                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3433                    "isPermissionRevokedByPolicy for user " + userId);
3434        }
3435
3436        if (checkPermission(permission, packageName, userId)
3437                == PackageManager.PERMISSION_GRANTED) {
3438            return false;
3439        }
3440
3441        final long identity = Binder.clearCallingIdentity();
3442        try {
3443            final int flags = getPermissionFlags(permission, packageName, userId);
3444            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3445        } finally {
3446            Binder.restoreCallingIdentity(identity);
3447        }
3448    }
3449
3450    @Override
3451    public String getPermissionControllerPackageName() {
3452        synchronized (mPackages) {
3453            return mRequiredInstallerPackage;
3454        }
3455    }
3456
3457    /**
3458     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3459     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3460     * @param checkShell TODO(yamasani):
3461     * @param message the message to log on security exception
3462     */
3463    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3464            boolean checkShell, String message) {
3465        if (userId < 0) {
3466            throw new IllegalArgumentException("Invalid userId " + userId);
3467        }
3468        if (checkShell) {
3469            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3470        }
3471        if (userId == UserHandle.getUserId(callingUid)) return;
3472        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3473            if (requireFullPermission) {
3474                mContext.enforceCallingOrSelfPermission(
3475                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3476            } else {
3477                try {
3478                    mContext.enforceCallingOrSelfPermission(
3479                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3480                } catch (SecurityException se) {
3481                    mContext.enforceCallingOrSelfPermission(
3482                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3483                }
3484            }
3485        }
3486    }
3487
3488    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3489        if (callingUid == Process.SHELL_UID) {
3490            if (userHandle >= 0
3491                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3492                throw new SecurityException("Shell does not have permission to access user "
3493                        + userHandle);
3494            } else if (userHandle < 0) {
3495                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3496                        + Debug.getCallers(3));
3497            }
3498        }
3499    }
3500
3501    private BasePermission findPermissionTreeLP(String permName) {
3502        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3503            if (permName.startsWith(bp.name) &&
3504                    permName.length() > bp.name.length() &&
3505                    permName.charAt(bp.name.length()) == '.') {
3506                return bp;
3507            }
3508        }
3509        return null;
3510    }
3511
3512    private BasePermission checkPermissionTreeLP(String permName) {
3513        if (permName != null) {
3514            BasePermission bp = findPermissionTreeLP(permName);
3515            if (bp != null) {
3516                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3517                    return bp;
3518                }
3519                throw new SecurityException("Calling uid "
3520                        + Binder.getCallingUid()
3521                        + " is not allowed to add to permission tree "
3522                        + bp.name + " owned by uid " + bp.uid);
3523            }
3524        }
3525        throw new SecurityException("No permission tree found for " + permName);
3526    }
3527
3528    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3529        if (s1 == null) {
3530            return s2 == null;
3531        }
3532        if (s2 == null) {
3533            return false;
3534        }
3535        if (s1.getClass() != s2.getClass()) {
3536            return false;
3537        }
3538        return s1.equals(s2);
3539    }
3540
3541    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3542        if (pi1.icon != pi2.icon) return false;
3543        if (pi1.logo != pi2.logo) return false;
3544        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3545        if (!compareStrings(pi1.name, pi2.name)) return false;
3546        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3547        // We'll take care of setting this one.
3548        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3549        // These are not currently stored in settings.
3550        //if (!compareStrings(pi1.group, pi2.group)) return false;
3551        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3552        //if (pi1.labelRes != pi2.labelRes) return false;
3553        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3554        return true;
3555    }
3556
3557    int permissionInfoFootprint(PermissionInfo info) {
3558        int size = info.name.length();
3559        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3560        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3561        return size;
3562    }
3563
3564    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3565        int size = 0;
3566        for (BasePermission perm : mSettings.mPermissions.values()) {
3567            if (perm.uid == tree.uid) {
3568                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3569            }
3570        }
3571        return size;
3572    }
3573
3574    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3575        // We calculate the max size of permissions defined by this uid and throw
3576        // if that plus the size of 'info' would exceed our stated maximum.
3577        if (tree.uid != Process.SYSTEM_UID) {
3578            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3579            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3580                throw new SecurityException("Permission tree size cap exceeded");
3581            }
3582        }
3583    }
3584
3585    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3586        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3587            throw new SecurityException("Label must be specified in permission");
3588        }
3589        BasePermission tree = checkPermissionTreeLP(info.name);
3590        BasePermission bp = mSettings.mPermissions.get(info.name);
3591        boolean added = bp == null;
3592        boolean changed = true;
3593        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3594        if (added) {
3595            enforcePermissionCapLocked(info, tree);
3596            bp = new BasePermission(info.name, tree.sourcePackage,
3597                    BasePermission.TYPE_DYNAMIC);
3598        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3599            throw new SecurityException(
3600                    "Not allowed to modify non-dynamic permission "
3601                    + info.name);
3602        } else {
3603            if (bp.protectionLevel == fixedLevel
3604                    && bp.perm.owner.equals(tree.perm.owner)
3605                    && bp.uid == tree.uid
3606                    && comparePermissionInfos(bp.perm.info, info)) {
3607                changed = false;
3608            }
3609        }
3610        bp.protectionLevel = fixedLevel;
3611        info = new PermissionInfo(info);
3612        info.protectionLevel = fixedLevel;
3613        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3614        bp.perm.info.packageName = tree.perm.info.packageName;
3615        bp.uid = tree.uid;
3616        if (added) {
3617            mSettings.mPermissions.put(info.name, bp);
3618        }
3619        if (changed) {
3620            if (!async) {
3621                mSettings.writeLPr();
3622            } else {
3623                scheduleWriteSettingsLocked();
3624            }
3625        }
3626        return added;
3627    }
3628
3629    @Override
3630    public boolean addPermission(PermissionInfo info) {
3631        synchronized (mPackages) {
3632            return addPermissionLocked(info, false);
3633        }
3634    }
3635
3636    @Override
3637    public boolean addPermissionAsync(PermissionInfo info) {
3638        synchronized (mPackages) {
3639            return addPermissionLocked(info, true);
3640        }
3641    }
3642
3643    @Override
3644    public void removePermission(String name) {
3645        synchronized (mPackages) {
3646            checkPermissionTreeLP(name);
3647            BasePermission bp = mSettings.mPermissions.get(name);
3648            if (bp != null) {
3649                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3650                    throw new SecurityException(
3651                            "Not allowed to modify non-dynamic permission "
3652                            + name);
3653                }
3654                mSettings.mPermissions.remove(name);
3655                mSettings.writeLPr();
3656            }
3657        }
3658    }
3659
3660    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3661            BasePermission bp) {
3662        int index = pkg.requestedPermissions.indexOf(bp.name);
3663        if (index == -1) {
3664            throw new SecurityException("Package " + pkg.packageName
3665                    + " has not requested permission " + bp.name);
3666        }
3667        if (!bp.isRuntime() && !bp.isDevelopment()) {
3668            throw new SecurityException("Permission " + bp.name
3669                    + " is not a changeable permission type");
3670        }
3671    }
3672
3673    @Override
3674    public void grantRuntimePermission(String packageName, String name, final int userId) {
3675        if (!sUserManager.exists(userId)) {
3676            Log.e(TAG, "No such user:" + userId);
3677            return;
3678        }
3679
3680        mContext.enforceCallingOrSelfPermission(
3681                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3682                "grantRuntimePermission");
3683
3684        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3685                "grantRuntimePermission");
3686
3687        final int uid;
3688        final SettingBase sb;
3689
3690        synchronized (mPackages) {
3691            final PackageParser.Package pkg = mPackages.get(packageName);
3692            if (pkg == null) {
3693                throw new IllegalArgumentException("Unknown package: " + packageName);
3694            }
3695
3696            final BasePermission bp = mSettings.mPermissions.get(name);
3697            if (bp == null) {
3698                throw new IllegalArgumentException("Unknown permission: " + name);
3699            }
3700
3701            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3702
3703            // If a permission review is required for legacy apps we represent
3704            // their permissions as always granted runtime ones since we need
3705            // to keep the review required permission flag per user while an
3706            // install permission's state is shared across all users.
3707            if (Build.PERMISSIONS_REVIEW_REQUIRED
3708                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3709                    && bp.isRuntime()) {
3710                return;
3711            }
3712
3713            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3714            sb = (SettingBase) pkg.mExtras;
3715            if (sb == null) {
3716                throw new IllegalArgumentException("Unknown package: " + packageName);
3717            }
3718
3719            final PermissionsState permissionsState = sb.getPermissionsState();
3720
3721            final int flags = permissionsState.getPermissionFlags(name, userId);
3722            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3723                throw new SecurityException("Cannot grant system fixed permission: "
3724                        + name + " for package: " + packageName);
3725            }
3726
3727            if (bp.isDevelopment()) {
3728                // Development permissions must be handled specially, since they are not
3729                // normal runtime permissions.  For now they apply to all users.
3730                if (permissionsState.grantInstallPermission(bp) !=
3731                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3732                    scheduleWriteSettingsLocked();
3733                }
3734                return;
3735            }
3736
3737            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3738                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3739                return;
3740            }
3741
3742            final int result = permissionsState.grantRuntimePermission(bp, userId);
3743            switch (result) {
3744                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3745                    return;
3746                }
3747
3748                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3749                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3750                    mHandler.post(new Runnable() {
3751                        @Override
3752                        public void run() {
3753                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3754                        }
3755                    });
3756                }
3757                break;
3758            }
3759
3760            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3761
3762            // Not critical if that is lost - app has to request again.
3763            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3764        }
3765
3766        // Only need to do this if user is initialized. Otherwise it's a new user
3767        // and there are no processes running as the user yet and there's no need
3768        // to make an expensive call to remount processes for the changed permissions.
3769        if (READ_EXTERNAL_STORAGE.equals(name)
3770                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3771            final long token = Binder.clearCallingIdentity();
3772            try {
3773                if (sUserManager.isInitialized(userId)) {
3774                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3775                            MountServiceInternal.class);
3776                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3777                }
3778            } finally {
3779                Binder.restoreCallingIdentity(token);
3780            }
3781        }
3782    }
3783
3784    @Override
3785    public void revokeRuntimePermission(String packageName, String name, int userId) {
3786        if (!sUserManager.exists(userId)) {
3787            Log.e(TAG, "No such user:" + userId);
3788            return;
3789        }
3790
3791        mContext.enforceCallingOrSelfPermission(
3792                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3793                "revokeRuntimePermission");
3794
3795        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3796                "revokeRuntimePermission");
3797
3798        final int appId;
3799
3800        synchronized (mPackages) {
3801            final PackageParser.Package pkg = mPackages.get(packageName);
3802            if (pkg == null) {
3803                throw new IllegalArgumentException("Unknown package: " + packageName);
3804            }
3805
3806            final BasePermission bp = mSettings.mPermissions.get(name);
3807            if (bp == null) {
3808                throw new IllegalArgumentException("Unknown permission: " + name);
3809            }
3810
3811            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3812
3813            // If a permission review is required for legacy apps we represent
3814            // their permissions as always granted runtime ones since we need
3815            // to keep the review required permission flag per user while an
3816            // install permission's state is shared across all users.
3817            if (Build.PERMISSIONS_REVIEW_REQUIRED
3818                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3819                    && bp.isRuntime()) {
3820                return;
3821            }
3822
3823            SettingBase sb = (SettingBase) pkg.mExtras;
3824            if (sb == null) {
3825                throw new IllegalArgumentException("Unknown package: " + packageName);
3826            }
3827
3828            final PermissionsState permissionsState = sb.getPermissionsState();
3829
3830            final int flags = permissionsState.getPermissionFlags(name, userId);
3831            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3832                throw new SecurityException("Cannot revoke system fixed permission: "
3833                        + name + " for package: " + packageName);
3834            }
3835
3836            if (bp.isDevelopment()) {
3837                // Development permissions must be handled specially, since they are not
3838                // normal runtime permissions.  For now they apply to all users.
3839                if (permissionsState.revokeInstallPermission(bp) !=
3840                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3841                    scheduleWriteSettingsLocked();
3842                }
3843                return;
3844            }
3845
3846            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3847                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3848                return;
3849            }
3850
3851            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3852
3853            // Critical, after this call app should never have the permission.
3854            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3855
3856            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3857        }
3858
3859        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3860    }
3861
3862    @Override
3863    public void resetRuntimePermissions() {
3864        mContext.enforceCallingOrSelfPermission(
3865                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3866                "revokeRuntimePermission");
3867
3868        int callingUid = Binder.getCallingUid();
3869        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3870            mContext.enforceCallingOrSelfPermission(
3871                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3872                    "resetRuntimePermissions");
3873        }
3874
3875        synchronized (mPackages) {
3876            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3877            for (int userId : UserManagerService.getInstance().getUserIds()) {
3878                final int packageCount = mPackages.size();
3879                for (int i = 0; i < packageCount; i++) {
3880                    PackageParser.Package pkg = mPackages.valueAt(i);
3881                    if (!(pkg.mExtras instanceof PackageSetting)) {
3882                        continue;
3883                    }
3884                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3885                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3886                }
3887            }
3888        }
3889    }
3890
3891    @Override
3892    public int getPermissionFlags(String name, String packageName, int userId) {
3893        if (!sUserManager.exists(userId)) {
3894            return 0;
3895        }
3896
3897        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3898
3899        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3900                "getPermissionFlags");
3901
3902        synchronized (mPackages) {
3903            final PackageParser.Package pkg = mPackages.get(packageName);
3904            if (pkg == null) {
3905                throw new IllegalArgumentException("Unknown package: " + packageName);
3906            }
3907
3908            final BasePermission bp = mSettings.mPermissions.get(name);
3909            if (bp == null) {
3910                throw new IllegalArgumentException("Unknown permission: " + name);
3911            }
3912
3913            SettingBase sb = (SettingBase) pkg.mExtras;
3914            if (sb == null) {
3915                throw new IllegalArgumentException("Unknown package: " + packageName);
3916            }
3917
3918            PermissionsState permissionsState = sb.getPermissionsState();
3919            return permissionsState.getPermissionFlags(name, userId);
3920        }
3921    }
3922
3923    @Override
3924    public void updatePermissionFlags(String name, String packageName, int flagMask,
3925            int flagValues, int userId) {
3926        if (!sUserManager.exists(userId)) {
3927            return;
3928        }
3929
3930        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3931
3932        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3933                "updatePermissionFlags");
3934
3935        // Only the system can change these flags and nothing else.
3936        if (getCallingUid() != Process.SYSTEM_UID) {
3937            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3938            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3939            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3940            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3941            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3942        }
3943
3944        synchronized (mPackages) {
3945            final PackageParser.Package pkg = mPackages.get(packageName);
3946            if (pkg == null) {
3947                throw new IllegalArgumentException("Unknown package: " + packageName);
3948            }
3949
3950            final BasePermission bp = mSettings.mPermissions.get(name);
3951            if (bp == null) {
3952                throw new IllegalArgumentException("Unknown permission: " + name);
3953            }
3954
3955            SettingBase sb = (SettingBase) pkg.mExtras;
3956            if (sb == null) {
3957                throw new IllegalArgumentException("Unknown package: " + packageName);
3958            }
3959
3960            PermissionsState permissionsState = sb.getPermissionsState();
3961
3962            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3963
3964            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3965                // Install and runtime permissions are stored in different places,
3966                // so figure out what permission changed and persist the change.
3967                if (permissionsState.getInstallPermissionState(name) != null) {
3968                    scheduleWriteSettingsLocked();
3969                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3970                        || hadState) {
3971                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3972                }
3973            }
3974        }
3975    }
3976
3977    /**
3978     * Update the permission flags for all packages and runtime permissions of a user in order
3979     * to allow device or profile owner to remove POLICY_FIXED.
3980     */
3981    @Override
3982    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3983        if (!sUserManager.exists(userId)) {
3984            return;
3985        }
3986
3987        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3988
3989        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3990                "updatePermissionFlagsForAllApps");
3991
3992        // Only the system can change system fixed flags.
3993        if (getCallingUid() != Process.SYSTEM_UID) {
3994            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3995            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3996        }
3997
3998        synchronized (mPackages) {
3999            boolean changed = false;
4000            final int packageCount = mPackages.size();
4001            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4002                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4003                SettingBase sb = (SettingBase) pkg.mExtras;
4004                if (sb == null) {
4005                    continue;
4006                }
4007                PermissionsState permissionsState = sb.getPermissionsState();
4008                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4009                        userId, flagMask, flagValues);
4010            }
4011            if (changed) {
4012                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4013            }
4014        }
4015    }
4016
4017    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4018        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4019                != PackageManager.PERMISSION_GRANTED
4020            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4021                != PackageManager.PERMISSION_GRANTED) {
4022            throw new SecurityException(message + " requires "
4023                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4024                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4025        }
4026    }
4027
4028    @Override
4029    public boolean shouldShowRequestPermissionRationale(String permissionName,
4030            String packageName, int userId) {
4031        if (UserHandle.getCallingUserId() != userId) {
4032            mContext.enforceCallingPermission(
4033                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4034                    "canShowRequestPermissionRationale for user " + userId);
4035        }
4036
4037        final int uid = getPackageUid(packageName, userId);
4038        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4039            return false;
4040        }
4041
4042        if (checkPermission(permissionName, packageName, userId)
4043                == PackageManager.PERMISSION_GRANTED) {
4044            return false;
4045        }
4046
4047        final int flags;
4048
4049        final long identity = Binder.clearCallingIdentity();
4050        try {
4051            flags = getPermissionFlags(permissionName,
4052                    packageName, userId);
4053        } finally {
4054            Binder.restoreCallingIdentity(identity);
4055        }
4056
4057        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4058                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4059                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4060
4061        if ((flags & fixedFlags) != 0) {
4062            return false;
4063        }
4064
4065        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4066    }
4067
4068    @Override
4069    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4070        mContext.enforceCallingOrSelfPermission(
4071                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4072                "addOnPermissionsChangeListener");
4073
4074        synchronized (mPackages) {
4075            mOnPermissionChangeListeners.addListenerLocked(listener);
4076        }
4077    }
4078
4079    @Override
4080    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4081        synchronized (mPackages) {
4082            mOnPermissionChangeListeners.removeListenerLocked(listener);
4083        }
4084    }
4085
4086    @Override
4087    public boolean isProtectedBroadcast(String actionName) {
4088        synchronized (mPackages) {
4089            if (mProtectedBroadcasts.contains(actionName)) {
4090                return true;
4091            } else if (actionName != null) {
4092                // TODO: remove these terrible hacks
4093                if (actionName.startsWith("android.net.netmon.lingerExpired")
4094                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4095                    return true;
4096                }
4097            }
4098        }
4099        return false;
4100    }
4101
4102    @Override
4103    public int checkSignatures(String pkg1, String pkg2) {
4104        synchronized (mPackages) {
4105            final PackageParser.Package p1 = mPackages.get(pkg1);
4106            final PackageParser.Package p2 = mPackages.get(pkg2);
4107            if (p1 == null || p1.mExtras == null
4108                    || p2 == null || p2.mExtras == null) {
4109                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4110            }
4111            return compareSignatures(p1.mSignatures, p2.mSignatures);
4112        }
4113    }
4114
4115    @Override
4116    public int checkUidSignatures(int uid1, int uid2) {
4117        // Map to base uids.
4118        uid1 = UserHandle.getAppId(uid1);
4119        uid2 = UserHandle.getAppId(uid2);
4120        // reader
4121        synchronized (mPackages) {
4122            Signature[] s1;
4123            Signature[] s2;
4124            Object obj = mSettings.getUserIdLPr(uid1);
4125            if (obj != null) {
4126                if (obj instanceof SharedUserSetting) {
4127                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4128                } else if (obj instanceof PackageSetting) {
4129                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4130                } else {
4131                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4132                }
4133            } else {
4134                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4135            }
4136            obj = mSettings.getUserIdLPr(uid2);
4137            if (obj != null) {
4138                if (obj instanceof SharedUserSetting) {
4139                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4140                } else if (obj instanceof PackageSetting) {
4141                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4142                } else {
4143                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4144                }
4145            } else {
4146                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4147            }
4148            return compareSignatures(s1, s2);
4149        }
4150    }
4151
4152    private void killUid(int appId, int userId, String reason) {
4153        final long identity = Binder.clearCallingIdentity();
4154        try {
4155            IActivityManager am = ActivityManagerNative.getDefault();
4156            if (am != null) {
4157                try {
4158                    am.killUid(appId, userId, reason);
4159                } catch (RemoteException e) {
4160                    /* ignore - same process */
4161                }
4162            }
4163        } finally {
4164            Binder.restoreCallingIdentity(identity);
4165        }
4166    }
4167
4168    /**
4169     * Compares two sets of signatures. Returns:
4170     * <br />
4171     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4172     * <br />
4173     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4174     * <br />
4175     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4176     * <br />
4177     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4178     * <br />
4179     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4180     */
4181    static int compareSignatures(Signature[] s1, Signature[] s2) {
4182        if (s1 == null) {
4183            return s2 == null
4184                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4185                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4186        }
4187
4188        if (s2 == null) {
4189            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4190        }
4191
4192        if (s1.length != s2.length) {
4193            return PackageManager.SIGNATURE_NO_MATCH;
4194        }
4195
4196        // Since both signature sets are of size 1, we can compare without HashSets.
4197        if (s1.length == 1) {
4198            return s1[0].equals(s2[0]) ?
4199                    PackageManager.SIGNATURE_MATCH :
4200                    PackageManager.SIGNATURE_NO_MATCH;
4201        }
4202
4203        ArraySet<Signature> set1 = new ArraySet<Signature>();
4204        for (Signature sig : s1) {
4205            set1.add(sig);
4206        }
4207        ArraySet<Signature> set2 = new ArraySet<Signature>();
4208        for (Signature sig : s2) {
4209            set2.add(sig);
4210        }
4211        // Make sure s2 contains all signatures in s1.
4212        if (set1.equals(set2)) {
4213            return PackageManager.SIGNATURE_MATCH;
4214        }
4215        return PackageManager.SIGNATURE_NO_MATCH;
4216    }
4217
4218    /**
4219     * If the database version for this type of package (internal storage or
4220     * external storage) is less than the version where package signatures
4221     * were updated, return true.
4222     */
4223    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4224        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4225        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4226    }
4227
4228    /**
4229     * Used for backward compatibility to make sure any packages with
4230     * certificate chains get upgraded to the new style. {@code existingSigs}
4231     * will be in the old format (since they were stored on disk from before the
4232     * system upgrade) and {@code scannedSigs} will be in the newer format.
4233     */
4234    private int compareSignaturesCompat(PackageSignatures existingSigs,
4235            PackageParser.Package scannedPkg) {
4236        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4237            return PackageManager.SIGNATURE_NO_MATCH;
4238        }
4239
4240        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4241        for (Signature sig : existingSigs.mSignatures) {
4242            existingSet.add(sig);
4243        }
4244        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4245        for (Signature sig : scannedPkg.mSignatures) {
4246            try {
4247                Signature[] chainSignatures = sig.getChainSignatures();
4248                for (Signature chainSig : chainSignatures) {
4249                    scannedCompatSet.add(chainSig);
4250                }
4251            } catch (CertificateEncodingException e) {
4252                scannedCompatSet.add(sig);
4253            }
4254        }
4255        /*
4256         * Make sure the expanded scanned set contains all signatures in the
4257         * existing one.
4258         */
4259        if (scannedCompatSet.equals(existingSet)) {
4260            // Migrate the old signatures to the new scheme.
4261            existingSigs.assignSignatures(scannedPkg.mSignatures);
4262            // The new KeySets will be re-added later in the scanning process.
4263            synchronized (mPackages) {
4264                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4265            }
4266            return PackageManager.SIGNATURE_MATCH;
4267        }
4268        return PackageManager.SIGNATURE_NO_MATCH;
4269    }
4270
4271    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4272        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4273        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4274    }
4275
4276    private int compareSignaturesRecover(PackageSignatures existingSigs,
4277            PackageParser.Package scannedPkg) {
4278        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4279            return PackageManager.SIGNATURE_NO_MATCH;
4280        }
4281
4282        String msg = null;
4283        try {
4284            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4285                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4286                        + scannedPkg.packageName);
4287                return PackageManager.SIGNATURE_MATCH;
4288            }
4289        } catch (CertificateException e) {
4290            msg = e.getMessage();
4291        }
4292
4293        logCriticalInfo(Log.INFO,
4294                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4295        return PackageManager.SIGNATURE_NO_MATCH;
4296    }
4297
4298    @Override
4299    public String[] getPackagesForUid(int uid) {
4300        uid = UserHandle.getAppId(uid);
4301        // reader
4302        synchronized (mPackages) {
4303            Object obj = mSettings.getUserIdLPr(uid);
4304            if (obj instanceof SharedUserSetting) {
4305                final SharedUserSetting sus = (SharedUserSetting) obj;
4306                final int N = sus.packages.size();
4307                final String[] res = new String[N];
4308                final Iterator<PackageSetting> it = sus.packages.iterator();
4309                int i = 0;
4310                while (it.hasNext()) {
4311                    res[i++] = it.next().name;
4312                }
4313                return res;
4314            } else if (obj instanceof PackageSetting) {
4315                final PackageSetting ps = (PackageSetting) obj;
4316                return new String[] { ps.name };
4317            }
4318        }
4319        return null;
4320    }
4321
4322    @Override
4323    public String getNameForUid(int uid) {
4324        // reader
4325        synchronized (mPackages) {
4326            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4327            if (obj instanceof SharedUserSetting) {
4328                final SharedUserSetting sus = (SharedUserSetting) obj;
4329                return sus.name + ":" + sus.userId;
4330            } else if (obj instanceof PackageSetting) {
4331                final PackageSetting ps = (PackageSetting) obj;
4332                return ps.name;
4333            }
4334        }
4335        return null;
4336    }
4337
4338    @Override
4339    public int getUidForSharedUser(String sharedUserName) {
4340        if(sharedUserName == null) {
4341            return -1;
4342        }
4343        // reader
4344        synchronized (mPackages) {
4345            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4346            if (suid == null) {
4347                return -1;
4348            }
4349            return suid.userId;
4350        }
4351    }
4352
4353    @Override
4354    public int getFlagsForUid(int uid) {
4355        synchronized (mPackages) {
4356            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4357            if (obj instanceof SharedUserSetting) {
4358                final SharedUserSetting sus = (SharedUserSetting) obj;
4359                return sus.pkgFlags;
4360            } else if (obj instanceof PackageSetting) {
4361                final PackageSetting ps = (PackageSetting) obj;
4362                return ps.pkgFlags;
4363            }
4364        }
4365        return 0;
4366    }
4367
4368    @Override
4369    public int getPrivateFlagsForUid(int uid) {
4370        synchronized (mPackages) {
4371            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4372            if (obj instanceof SharedUserSetting) {
4373                final SharedUserSetting sus = (SharedUserSetting) obj;
4374                return sus.pkgPrivateFlags;
4375            } else if (obj instanceof PackageSetting) {
4376                final PackageSetting ps = (PackageSetting) obj;
4377                return ps.pkgPrivateFlags;
4378            }
4379        }
4380        return 0;
4381    }
4382
4383    @Override
4384    public boolean isUidPrivileged(int uid) {
4385        uid = UserHandle.getAppId(uid);
4386        // reader
4387        synchronized (mPackages) {
4388            Object obj = mSettings.getUserIdLPr(uid);
4389            if (obj instanceof SharedUserSetting) {
4390                final SharedUserSetting sus = (SharedUserSetting) obj;
4391                final Iterator<PackageSetting> it = sus.packages.iterator();
4392                while (it.hasNext()) {
4393                    if (it.next().isPrivileged()) {
4394                        return true;
4395                    }
4396                }
4397            } else if (obj instanceof PackageSetting) {
4398                final PackageSetting ps = (PackageSetting) obj;
4399                return ps.isPrivileged();
4400            }
4401        }
4402        return false;
4403    }
4404
4405    @Override
4406    public String[] getAppOpPermissionPackages(String permissionName) {
4407        synchronized (mPackages) {
4408            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4409            if (pkgs == null) {
4410                return null;
4411            }
4412            return pkgs.toArray(new String[pkgs.size()]);
4413        }
4414    }
4415
4416    @Override
4417    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4418            int flags, int userId) {
4419        if (!sUserManager.exists(userId)) return null;
4420        flags = augmentFlagsForUser(flags, userId);
4421        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4422        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4423        final ResolveInfo bestChoice =
4424                chooseBestActivity(intent, resolvedType, flags, query, userId);
4425
4426        if (isEphemeralAllowed(intent, query, userId)) {
4427            final EphemeralResolveInfo ai =
4428                    getEphemeralResolveInfo(intent, resolvedType, userId);
4429            if (ai != null) {
4430                if (DEBUG_EPHEMERAL) {
4431                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4432                }
4433                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4434                bestChoice.ephemeralResolveInfo = ai;
4435            }
4436        }
4437        return bestChoice;
4438    }
4439
4440    @Override
4441    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4442            IntentFilter filter, int match, ComponentName activity) {
4443        final int userId = UserHandle.getCallingUserId();
4444        if (DEBUG_PREFERRED) {
4445            Log.v(TAG, "setLastChosenActivity intent=" + intent
4446                + " resolvedType=" + resolvedType
4447                + " flags=" + flags
4448                + " filter=" + filter
4449                + " match=" + match
4450                + " activity=" + activity);
4451            filter.dump(new PrintStreamPrinter(System.out), "    ");
4452        }
4453        intent.setComponent(null);
4454        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4455        // Find any earlier preferred or last chosen entries and nuke them
4456        findPreferredActivity(intent, resolvedType,
4457                flags, query, 0, false, true, false, userId);
4458        // Add the new activity as the last chosen for this filter
4459        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4460                "Setting last chosen");
4461    }
4462
4463    @Override
4464    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4465        final int userId = UserHandle.getCallingUserId();
4466        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4467        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4468        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4469                false, false, false, userId);
4470    }
4471
4472
4473    private boolean isEphemeralAllowed(
4474            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4475        // Short circuit and return early if possible.
4476        final int callingUser = UserHandle.getCallingUserId();
4477        if (callingUser != UserHandle.USER_SYSTEM) {
4478            return false;
4479        }
4480        if (mEphemeralResolverConnection == null) {
4481            return false;
4482        }
4483        if (intent.getComponent() != null) {
4484            return false;
4485        }
4486        if (intent.getPackage() != null) {
4487            return false;
4488        }
4489        final boolean isWebUri = hasWebURI(intent);
4490        if (!isWebUri) {
4491            return false;
4492        }
4493        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4494        synchronized (mPackages) {
4495            final int count = resolvedActivites.size();
4496            for (int n = 0; n < count; n++) {
4497                ResolveInfo info = resolvedActivites.get(n);
4498                String packageName = info.activityInfo.packageName;
4499                PackageSetting ps = mSettings.mPackages.get(packageName);
4500                if (ps != null) {
4501                    // Try to get the status from User settings first
4502                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4503                    int status = (int) (packedStatus >> 32);
4504                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4505                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4506                        if (DEBUG_EPHEMERAL) {
4507                            Slog.v(TAG, "DENY ephemeral apps;"
4508                                + " pkg: " + packageName + ", status: " + status);
4509                        }
4510                        return false;
4511                    }
4512                }
4513            }
4514        }
4515        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4516        return true;
4517    }
4518
4519    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4520            int userId) {
4521        MessageDigest digest = null;
4522        try {
4523            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4524        } catch (NoSuchAlgorithmException e) {
4525            // If we can't create a digest, ignore ephemeral apps.
4526            return null;
4527        }
4528
4529        final byte[] hostBytes = intent.getData().getHost().getBytes();
4530        final byte[] digestBytes = digest.digest(hostBytes);
4531        int shaPrefix =
4532                digestBytes[0] << 24
4533                | digestBytes[1] << 16
4534                | digestBytes[2] << 8
4535                | digestBytes[3] << 0;
4536        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4537                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4538        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4539            // No hash prefix match; there are no ephemeral apps for this domain.
4540            return null;
4541        }
4542        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4543            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4544            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4545                continue;
4546            }
4547            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4548            // No filters; this should never happen.
4549            if (filters.isEmpty()) {
4550                continue;
4551            }
4552            // We have a domain match; resolve the filters to see if anything matches.
4553            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4554            for (int j = filters.size() - 1; j >= 0; --j) {
4555                final EphemeralResolveIntentInfo intentInfo =
4556                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4557                ephemeralResolver.addFilter(intentInfo);
4558            }
4559            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4560                    intent, resolvedType, false /*defaultOnly*/, userId);
4561            if (!matchedResolveInfoList.isEmpty()) {
4562                return matchedResolveInfoList.get(0);
4563            }
4564        }
4565        // Hash or filter mis-match; no ephemeral apps for this domain.
4566        return null;
4567    }
4568
4569    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4570            int flags, List<ResolveInfo> query, int userId) {
4571        if (query != null) {
4572            final int N = query.size();
4573            if (N == 1) {
4574                return query.get(0);
4575            } else if (N > 1) {
4576                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4577                // If there is more than one activity with the same priority,
4578                // then let the user decide between them.
4579                ResolveInfo r0 = query.get(0);
4580                ResolveInfo r1 = query.get(1);
4581                if (DEBUG_INTENT_MATCHING || debug) {
4582                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4583                            + r1.activityInfo.name + "=" + r1.priority);
4584                }
4585                // If the first activity has a higher priority, or a different
4586                // default, then it is always desirable to pick it.
4587                if (r0.priority != r1.priority
4588                        || r0.preferredOrder != r1.preferredOrder
4589                        || r0.isDefault != r1.isDefault) {
4590                    return query.get(0);
4591                }
4592                // If we have saved a preference for a preferred activity for
4593                // this Intent, use that.
4594                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4595                        flags, query, r0.priority, true, false, debug, userId);
4596                if (ri != null) {
4597                    return ri;
4598                }
4599                ri = new ResolveInfo(mResolveInfo);
4600                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4601                ri.activityInfo.applicationInfo = new ApplicationInfo(
4602                        ri.activityInfo.applicationInfo);
4603                if (userId != 0) {
4604                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4605                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4606                }
4607                // Make sure that the resolver is displayable in car mode
4608                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4609                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4610                return ri;
4611            }
4612        }
4613        return null;
4614    }
4615
4616    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4617            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4618        final int N = query.size();
4619        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4620                .get(userId);
4621        // Get the list of persistent preferred activities that handle the intent
4622        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4623        List<PersistentPreferredActivity> pprefs = ppir != null
4624                ? ppir.queryIntent(intent, resolvedType,
4625                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4626                : null;
4627        if (pprefs != null && pprefs.size() > 0) {
4628            final int M = pprefs.size();
4629            for (int i=0; i<M; i++) {
4630                final PersistentPreferredActivity ppa = pprefs.get(i);
4631                if (DEBUG_PREFERRED || debug) {
4632                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4633                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4634                            + "\n  component=" + ppa.mComponent);
4635                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4636                }
4637                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4638                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4639                if (DEBUG_PREFERRED || debug) {
4640                    Slog.v(TAG, "Found persistent preferred activity:");
4641                    if (ai != null) {
4642                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4643                    } else {
4644                        Slog.v(TAG, "  null");
4645                    }
4646                }
4647                if (ai == null) {
4648                    // This previously registered persistent preferred activity
4649                    // component is no longer known. Ignore it and do NOT remove it.
4650                    continue;
4651                }
4652                for (int j=0; j<N; j++) {
4653                    final ResolveInfo ri = query.get(j);
4654                    if (!ri.activityInfo.applicationInfo.packageName
4655                            .equals(ai.applicationInfo.packageName)) {
4656                        continue;
4657                    }
4658                    if (!ri.activityInfo.name.equals(ai.name)) {
4659                        continue;
4660                    }
4661                    //  Found a persistent preference that can handle the intent.
4662                    if (DEBUG_PREFERRED || debug) {
4663                        Slog.v(TAG, "Returning persistent preferred activity: " +
4664                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4665                    }
4666                    return ri;
4667                }
4668            }
4669        }
4670        return null;
4671    }
4672
4673    // TODO: handle preferred activities missing while user has amnesia
4674    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4675            List<ResolveInfo> query, int priority, boolean always,
4676            boolean removeMatches, boolean debug, int userId) {
4677        if (!sUserManager.exists(userId)) return null;
4678        flags = augmentFlagsForUser(flags, userId);
4679        // writer
4680        synchronized (mPackages) {
4681            if (intent.getSelector() != null) {
4682                intent = intent.getSelector();
4683            }
4684            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4685
4686            // Try to find a matching persistent preferred activity.
4687            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4688                    debug, userId);
4689
4690            // If a persistent preferred activity matched, use it.
4691            if (pri != null) {
4692                return pri;
4693            }
4694
4695            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4696            // Get the list of preferred activities that handle the intent
4697            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4698            List<PreferredActivity> prefs = pir != null
4699                    ? pir.queryIntent(intent, resolvedType,
4700                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4701                    : null;
4702            if (prefs != null && prefs.size() > 0) {
4703                boolean changed = false;
4704                try {
4705                    // First figure out how good the original match set is.
4706                    // We will only allow preferred activities that came
4707                    // from the same match quality.
4708                    int match = 0;
4709
4710                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4711
4712                    final int N = query.size();
4713                    for (int j=0; j<N; j++) {
4714                        final ResolveInfo ri = query.get(j);
4715                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4716                                + ": 0x" + Integer.toHexString(match));
4717                        if (ri.match > match) {
4718                            match = ri.match;
4719                        }
4720                    }
4721
4722                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4723                            + Integer.toHexString(match));
4724
4725                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4726                    final int M = prefs.size();
4727                    for (int i=0; i<M; i++) {
4728                        final PreferredActivity pa = prefs.get(i);
4729                        if (DEBUG_PREFERRED || debug) {
4730                            Slog.v(TAG, "Checking PreferredActivity ds="
4731                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4732                                    + "\n  component=" + pa.mPref.mComponent);
4733                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4734                        }
4735                        if (pa.mPref.mMatch != match) {
4736                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4737                                    + Integer.toHexString(pa.mPref.mMatch));
4738                            continue;
4739                        }
4740                        // If it's not an "always" type preferred activity and that's what we're
4741                        // looking for, skip it.
4742                        if (always && !pa.mPref.mAlways) {
4743                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4744                            continue;
4745                        }
4746                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4747                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4748                        if (DEBUG_PREFERRED || debug) {
4749                            Slog.v(TAG, "Found preferred activity:");
4750                            if (ai != null) {
4751                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4752                            } else {
4753                                Slog.v(TAG, "  null");
4754                            }
4755                        }
4756                        if (ai == null) {
4757                            // This previously registered preferred activity
4758                            // component is no longer known.  Most likely an update
4759                            // to the app was installed and in the new version this
4760                            // component no longer exists.  Clean it up by removing
4761                            // it from the preferred activities list, and skip it.
4762                            Slog.w(TAG, "Removing dangling preferred activity: "
4763                                    + pa.mPref.mComponent);
4764                            pir.removeFilter(pa);
4765                            changed = true;
4766                            continue;
4767                        }
4768                        for (int j=0; j<N; j++) {
4769                            final ResolveInfo ri = query.get(j);
4770                            if (!ri.activityInfo.applicationInfo.packageName
4771                                    .equals(ai.applicationInfo.packageName)) {
4772                                continue;
4773                            }
4774                            if (!ri.activityInfo.name.equals(ai.name)) {
4775                                continue;
4776                            }
4777
4778                            if (removeMatches) {
4779                                pir.removeFilter(pa);
4780                                changed = true;
4781                                if (DEBUG_PREFERRED) {
4782                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4783                                }
4784                                break;
4785                            }
4786
4787                            // Okay we found a previously set preferred or last chosen app.
4788                            // If the result set is different from when this
4789                            // was created, we need to clear it and re-ask the
4790                            // user their preference, if we're looking for an "always" type entry.
4791                            if (always && !pa.mPref.sameSet(query)) {
4792                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4793                                        + intent + " type " + resolvedType);
4794                                if (DEBUG_PREFERRED) {
4795                                    Slog.v(TAG, "Removing preferred activity since set changed "
4796                                            + pa.mPref.mComponent);
4797                                }
4798                                pir.removeFilter(pa);
4799                                // Re-add the filter as a "last chosen" entry (!always)
4800                                PreferredActivity lastChosen = new PreferredActivity(
4801                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4802                                pir.addFilter(lastChosen);
4803                                changed = true;
4804                                return null;
4805                            }
4806
4807                            // Yay! Either the set matched or we're looking for the last chosen
4808                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4809                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4810                            return ri;
4811                        }
4812                    }
4813                } finally {
4814                    if (changed) {
4815                        if (DEBUG_PREFERRED) {
4816                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4817                        }
4818                        scheduleWritePackageRestrictionsLocked(userId);
4819                    }
4820                }
4821            }
4822        }
4823        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4824        return null;
4825    }
4826
4827    /*
4828     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4829     */
4830    @Override
4831    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4832            int targetUserId) {
4833        mContext.enforceCallingOrSelfPermission(
4834                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4835        List<CrossProfileIntentFilter> matches =
4836                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4837        if (matches != null) {
4838            int size = matches.size();
4839            for (int i = 0; i < size; i++) {
4840                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4841            }
4842        }
4843        if (hasWebURI(intent)) {
4844            // cross-profile app linking works only towards the parent.
4845            final UserInfo parent = getProfileParent(sourceUserId);
4846            synchronized(mPackages) {
4847                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4848                        intent, resolvedType, 0, sourceUserId, parent.id);
4849                return xpDomainInfo != null;
4850            }
4851        }
4852        return false;
4853    }
4854
4855    private UserInfo getProfileParent(int userId) {
4856        final long identity = Binder.clearCallingIdentity();
4857        try {
4858            return sUserManager.getProfileParent(userId);
4859        } finally {
4860            Binder.restoreCallingIdentity(identity);
4861        }
4862    }
4863
4864    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4865            String resolvedType, int userId) {
4866        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4867        if (resolver != null) {
4868            return resolver.queryIntent(intent, resolvedType, false, userId);
4869        }
4870        return null;
4871    }
4872
4873    @Override
4874    public List<ResolveInfo> queryIntentActivities(Intent intent,
4875            String resolvedType, int flags, int userId) {
4876        if (!sUserManager.exists(userId)) return Collections.emptyList();
4877        flags = augmentFlagsForUser(flags, userId);
4878        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4879        ComponentName comp = intent.getComponent();
4880        if (comp == null) {
4881            if (intent.getSelector() != null) {
4882                intent = intent.getSelector();
4883                comp = intent.getComponent();
4884            }
4885        }
4886
4887        if (comp != null) {
4888            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4889            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4890            if (ai != null) {
4891                final ResolveInfo ri = new ResolveInfo();
4892                ri.activityInfo = ai;
4893                list.add(ri);
4894            }
4895            return list;
4896        }
4897
4898        // reader
4899        synchronized (mPackages) {
4900            final String pkgName = intent.getPackage();
4901            if (pkgName == null) {
4902                List<CrossProfileIntentFilter> matchingFilters =
4903                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4904                // Check for results that need to skip the current profile.
4905                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4906                        resolvedType, flags, userId);
4907                if (xpResolveInfo != null) {
4908                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4909                    result.add(xpResolveInfo);
4910                    return filterIfNotSystemUser(result, userId);
4911                }
4912
4913                // Check for results in the current profile.
4914                List<ResolveInfo> result = mActivities.queryIntent(
4915                        intent, resolvedType, flags, userId);
4916                result = filterIfNotSystemUser(result, userId);
4917
4918                // Check for cross profile results.
4919                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4920                xpResolveInfo = queryCrossProfileIntents(
4921                        matchingFilters, intent, resolvedType, flags, userId,
4922                        hasNonNegativePriorityResult);
4923                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4924                    boolean isVisibleToUser = filterIfNotSystemUser(
4925                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4926                    if (isVisibleToUser) {
4927                        result.add(xpResolveInfo);
4928                        Collections.sort(result, mResolvePrioritySorter);
4929                    }
4930                }
4931                if (hasWebURI(intent)) {
4932                    CrossProfileDomainInfo xpDomainInfo = null;
4933                    final UserInfo parent = getProfileParent(userId);
4934                    if (parent != null) {
4935                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4936                                flags, userId, parent.id);
4937                    }
4938                    if (xpDomainInfo != null) {
4939                        if (xpResolveInfo != null) {
4940                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4941                            // in the result.
4942                            result.remove(xpResolveInfo);
4943                        }
4944                        if (result.size() == 0) {
4945                            result.add(xpDomainInfo.resolveInfo);
4946                            return result;
4947                        }
4948                    } else if (result.size() <= 1) {
4949                        return result;
4950                    }
4951                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4952                            xpDomainInfo, userId);
4953                    Collections.sort(result, mResolvePrioritySorter);
4954                }
4955                return result;
4956            }
4957            final PackageParser.Package pkg = mPackages.get(pkgName);
4958            if (pkg != null) {
4959                return filterIfNotSystemUser(
4960                        mActivities.queryIntentForPackage(
4961                                intent, resolvedType, flags, pkg.activities, userId),
4962                        userId);
4963            }
4964            return new ArrayList<ResolveInfo>();
4965        }
4966    }
4967
4968    private static class CrossProfileDomainInfo {
4969        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4970        ResolveInfo resolveInfo;
4971        /* Best domain verification status of the activities found in the other profile */
4972        int bestDomainVerificationStatus;
4973    }
4974
4975    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4976            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4977        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4978                sourceUserId)) {
4979            return null;
4980        }
4981        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4982                resolvedType, flags, parentUserId);
4983
4984        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4985            return null;
4986        }
4987        CrossProfileDomainInfo result = null;
4988        int size = resultTargetUser.size();
4989        for (int i = 0; i < size; i++) {
4990            ResolveInfo riTargetUser = resultTargetUser.get(i);
4991            // Intent filter verification is only for filters that specify a host. So don't return
4992            // those that handle all web uris.
4993            if (riTargetUser.handleAllWebDataURI) {
4994                continue;
4995            }
4996            String packageName = riTargetUser.activityInfo.packageName;
4997            PackageSetting ps = mSettings.mPackages.get(packageName);
4998            if (ps == null) {
4999                continue;
5000            }
5001            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5002            int status = (int)(verificationState >> 32);
5003            if (result == null) {
5004                result = new CrossProfileDomainInfo();
5005                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5006                        sourceUserId, parentUserId);
5007                result.bestDomainVerificationStatus = status;
5008            } else {
5009                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5010                        result.bestDomainVerificationStatus);
5011            }
5012        }
5013        // Don't consider matches with status NEVER across profiles.
5014        if (result != null && result.bestDomainVerificationStatus
5015                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5016            return null;
5017        }
5018        return result;
5019    }
5020
5021    /**
5022     * Verification statuses are ordered from the worse to the best, except for
5023     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5024     */
5025    private int bestDomainVerificationStatus(int status1, int status2) {
5026        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5027            return status2;
5028        }
5029        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5030            return status1;
5031        }
5032        return (int) MathUtils.max(status1, status2);
5033    }
5034
5035    private boolean isUserEnabled(int userId) {
5036        long callingId = Binder.clearCallingIdentity();
5037        try {
5038            UserInfo userInfo = sUserManager.getUserInfo(userId);
5039            return userInfo != null && userInfo.isEnabled();
5040        } finally {
5041            Binder.restoreCallingIdentity(callingId);
5042        }
5043    }
5044
5045    /**
5046     * Filter out activities with systemUserOnly flag set, when current user is not System.
5047     *
5048     * @return filtered list
5049     */
5050    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5051        if (userId == UserHandle.USER_SYSTEM) {
5052            return resolveInfos;
5053        }
5054        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5055            ResolveInfo info = resolveInfos.get(i);
5056            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5057                resolveInfos.remove(i);
5058            }
5059        }
5060        return resolveInfos;
5061    }
5062
5063    /**
5064     * @param resolveInfos list of resolve infos in descending priority order
5065     * @return if the list contains a resolve info with non-negative priority
5066     */
5067    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5068        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5069    }
5070
5071    private static boolean hasWebURI(Intent intent) {
5072        if (intent.getData() == null) {
5073            return false;
5074        }
5075        final String scheme = intent.getScheme();
5076        if (TextUtils.isEmpty(scheme)) {
5077            return false;
5078        }
5079        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5080    }
5081
5082    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5083            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5084            int userId) {
5085        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5086
5087        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5088            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5089                    candidates.size());
5090        }
5091
5092        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5093        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5094        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5095        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5096        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5097        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5098
5099        synchronized (mPackages) {
5100            final int count = candidates.size();
5101            // First, try to use linked apps. Partition the candidates into four lists:
5102            // one for the final results, one for the "do not use ever", one for "undefined status"
5103            // and finally one for "browser app type".
5104            for (int n=0; n<count; n++) {
5105                ResolveInfo info = candidates.get(n);
5106                String packageName = info.activityInfo.packageName;
5107                PackageSetting ps = mSettings.mPackages.get(packageName);
5108                if (ps != null) {
5109                    // Add to the special match all list (Browser use case)
5110                    if (info.handleAllWebDataURI) {
5111                        matchAllList.add(info);
5112                        continue;
5113                    }
5114                    // Try to get the status from User settings first
5115                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5116                    int status = (int)(packedStatus >> 32);
5117                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5118                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5119                        if (DEBUG_DOMAIN_VERIFICATION) {
5120                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5121                                    + " : linkgen=" + linkGeneration);
5122                        }
5123                        // Use link-enabled generation as preferredOrder, i.e.
5124                        // prefer newly-enabled over earlier-enabled.
5125                        info.preferredOrder = linkGeneration;
5126                        alwaysList.add(info);
5127                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5128                        if (DEBUG_DOMAIN_VERIFICATION) {
5129                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5130                        }
5131                        neverList.add(info);
5132                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5133                        if (DEBUG_DOMAIN_VERIFICATION) {
5134                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5135                        }
5136                        alwaysAskList.add(info);
5137                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5138                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5139                        if (DEBUG_DOMAIN_VERIFICATION) {
5140                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5141                        }
5142                        undefinedList.add(info);
5143                    }
5144                }
5145            }
5146
5147            // We'll want to include browser possibilities in a few cases
5148            boolean includeBrowser = false;
5149
5150            // First try to add the "always" resolution(s) for the current user, if any
5151            if (alwaysList.size() > 0) {
5152                result.addAll(alwaysList);
5153            } else {
5154                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5155                result.addAll(undefinedList);
5156                // Maybe add one for the other profile.
5157                if (xpDomainInfo != null && (
5158                        xpDomainInfo.bestDomainVerificationStatus
5159                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5160                    result.add(xpDomainInfo.resolveInfo);
5161                }
5162                includeBrowser = true;
5163            }
5164
5165            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5166            // If there were 'always' entries their preferred order has been set, so we also
5167            // back that off to make the alternatives equivalent
5168            if (alwaysAskList.size() > 0) {
5169                for (ResolveInfo i : result) {
5170                    i.preferredOrder = 0;
5171                }
5172                result.addAll(alwaysAskList);
5173                includeBrowser = true;
5174            }
5175
5176            if (includeBrowser) {
5177                // Also add browsers (all of them or only the default one)
5178                if (DEBUG_DOMAIN_VERIFICATION) {
5179                    Slog.v(TAG, "   ...including browsers in candidate set");
5180                }
5181                if ((matchFlags & MATCH_ALL) != 0) {
5182                    result.addAll(matchAllList);
5183                } else {
5184                    // Browser/generic handling case.  If there's a default browser, go straight
5185                    // to that (but only if there is no other higher-priority match).
5186                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5187                    int maxMatchPrio = 0;
5188                    ResolveInfo defaultBrowserMatch = null;
5189                    final int numCandidates = matchAllList.size();
5190                    for (int n = 0; n < numCandidates; n++) {
5191                        ResolveInfo info = matchAllList.get(n);
5192                        // track the highest overall match priority...
5193                        if (info.priority > maxMatchPrio) {
5194                            maxMatchPrio = info.priority;
5195                        }
5196                        // ...and the highest-priority default browser match
5197                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5198                            if (defaultBrowserMatch == null
5199                                    || (defaultBrowserMatch.priority < info.priority)) {
5200                                if (debug) {
5201                                    Slog.v(TAG, "Considering default browser match " + info);
5202                                }
5203                                defaultBrowserMatch = info;
5204                            }
5205                        }
5206                    }
5207                    if (defaultBrowserMatch != null
5208                            && defaultBrowserMatch.priority >= maxMatchPrio
5209                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5210                    {
5211                        if (debug) {
5212                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5213                        }
5214                        result.add(defaultBrowserMatch);
5215                    } else {
5216                        result.addAll(matchAllList);
5217                    }
5218                }
5219
5220                // If there is nothing selected, add all candidates and remove the ones that the user
5221                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5222                if (result.size() == 0) {
5223                    result.addAll(candidates);
5224                    result.removeAll(neverList);
5225                }
5226            }
5227        }
5228        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5229            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5230                    result.size());
5231            for (ResolveInfo info : result) {
5232                Slog.v(TAG, "  + " + info.activityInfo);
5233            }
5234        }
5235        return result;
5236    }
5237
5238    // Returns a packed value as a long:
5239    //
5240    // high 'int'-sized word: link status: undefined/ask/never/always.
5241    // low 'int'-sized word: relative priority among 'always' results.
5242    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5243        long result = ps.getDomainVerificationStatusForUser(userId);
5244        // if none available, get the master status
5245        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5246            if (ps.getIntentFilterVerificationInfo() != null) {
5247                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5248            }
5249        }
5250        return result;
5251    }
5252
5253    private ResolveInfo querySkipCurrentProfileIntents(
5254            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5255            int flags, int sourceUserId) {
5256        if (matchingFilters != null) {
5257            int size = matchingFilters.size();
5258            for (int i = 0; i < size; i ++) {
5259                CrossProfileIntentFilter filter = matchingFilters.get(i);
5260                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5261                    // Checking if there are activities in the target user that can handle the
5262                    // intent.
5263                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5264                            resolvedType, flags, sourceUserId);
5265                    if (resolveInfo != null) {
5266                        return resolveInfo;
5267                    }
5268                }
5269            }
5270        }
5271        return null;
5272    }
5273
5274    // Return matching ResolveInfo in target user if any.
5275    private ResolveInfo queryCrossProfileIntents(
5276            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5277            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5278        if (matchingFilters != null) {
5279            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5280            // match the same intent. For performance reasons, it is better not to
5281            // run queryIntent twice for the same userId
5282            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5283            int size = matchingFilters.size();
5284            for (int i = 0; i < size; i++) {
5285                CrossProfileIntentFilter filter = matchingFilters.get(i);
5286                int targetUserId = filter.getTargetUserId();
5287                boolean skipCurrentProfile =
5288                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5289                boolean skipCurrentProfileIfNoMatchFound =
5290                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5291                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5292                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5293                    // Checking if there are activities in the target user that can handle the
5294                    // intent.
5295                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5296                            resolvedType, flags, sourceUserId);
5297                    if (resolveInfo != null) return resolveInfo;
5298                    alreadyTriedUserIds.put(targetUserId, true);
5299                }
5300            }
5301        }
5302        return null;
5303    }
5304
5305    /**
5306     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5307     * will forward the intent to the filter's target user.
5308     * Otherwise, returns null.
5309     */
5310    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5311            String resolvedType, int flags, int sourceUserId) {
5312        int targetUserId = filter.getTargetUserId();
5313        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5314                resolvedType, flags, targetUserId);
5315        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5316                && isUserEnabled(targetUserId)) {
5317            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5318        }
5319        return null;
5320    }
5321
5322    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5323            int sourceUserId, int targetUserId) {
5324        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5325        long ident = Binder.clearCallingIdentity();
5326        boolean targetIsProfile;
5327        try {
5328            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5329        } finally {
5330            Binder.restoreCallingIdentity(ident);
5331        }
5332        String className;
5333        if (targetIsProfile) {
5334            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5335        } else {
5336            className = FORWARD_INTENT_TO_PARENT;
5337        }
5338        ComponentName forwardingActivityComponentName = new ComponentName(
5339                mAndroidApplication.packageName, className);
5340        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5341                sourceUserId);
5342        if (!targetIsProfile) {
5343            forwardingActivityInfo.showUserIcon = targetUserId;
5344            forwardingResolveInfo.noResourceId = true;
5345        }
5346        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5347        forwardingResolveInfo.priority = 0;
5348        forwardingResolveInfo.preferredOrder = 0;
5349        forwardingResolveInfo.match = 0;
5350        forwardingResolveInfo.isDefault = true;
5351        forwardingResolveInfo.filter = filter;
5352        forwardingResolveInfo.targetUserId = targetUserId;
5353        return forwardingResolveInfo;
5354    }
5355
5356    @Override
5357    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5358            Intent[] specifics, String[] specificTypes, Intent intent,
5359            String resolvedType, int flags, int userId) {
5360        if (!sUserManager.exists(userId)) return Collections.emptyList();
5361        flags = augmentFlagsForUser(flags, userId);
5362        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5363                false, "query intent activity options");
5364        final String resultsAction = intent.getAction();
5365
5366        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5367                | PackageManager.GET_RESOLVED_FILTER, userId);
5368
5369        if (DEBUG_INTENT_MATCHING) {
5370            Log.v(TAG, "Query " + intent + ": " + results);
5371        }
5372
5373        int specificsPos = 0;
5374        int N;
5375
5376        // todo: note that the algorithm used here is O(N^2).  This
5377        // isn't a problem in our current environment, but if we start running
5378        // into situations where we have more than 5 or 10 matches then this
5379        // should probably be changed to something smarter...
5380
5381        // First we go through and resolve each of the specific items
5382        // that were supplied, taking care of removing any corresponding
5383        // duplicate items in the generic resolve list.
5384        if (specifics != null) {
5385            for (int i=0; i<specifics.length; i++) {
5386                final Intent sintent = specifics[i];
5387                if (sintent == null) {
5388                    continue;
5389                }
5390
5391                if (DEBUG_INTENT_MATCHING) {
5392                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5393                }
5394
5395                String action = sintent.getAction();
5396                if (resultsAction != null && resultsAction.equals(action)) {
5397                    // If this action was explicitly requested, then don't
5398                    // remove things that have it.
5399                    action = null;
5400                }
5401
5402                ResolveInfo ri = null;
5403                ActivityInfo ai = null;
5404
5405                ComponentName comp = sintent.getComponent();
5406                if (comp == null) {
5407                    ri = resolveIntent(
5408                        sintent,
5409                        specificTypes != null ? specificTypes[i] : null,
5410                            flags, userId);
5411                    if (ri == null) {
5412                        continue;
5413                    }
5414                    if (ri == mResolveInfo) {
5415                        // ACK!  Must do something better with this.
5416                    }
5417                    ai = ri.activityInfo;
5418                    comp = new ComponentName(ai.applicationInfo.packageName,
5419                            ai.name);
5420                } else {
5421                    ai = getActivityInfo(comp, flags, userId);
5422                    if (ai == null) {
5423                        continue;
5424                    }
5425                }
5426
5427                // Look for any generic query activities that are duplicates
5428                // of this specific one, and remove them from the results.
5429                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5430                N = results.size();
5431                int j;
5432                for (j=specificsPos; j<N; j++) {
5433                    ResolveInfo sri = results.get(j);
5434                    if ((sri.activityInfo.name.equals(comp.getClassName())
5435                            && sri.activityInfo.applicationInfo.packageName.equals(
5436                                    comp.getPackageName()))
5437                        || (action != null && sri.filter.matchAction(action))) {
5438                        results.remove(j);
5439                        if (DEBUG_INTENT_MATCHING) Log.v(
5440                            TAG, "Removing duplicate item from " + j
5441                            + " due to specific " + specificsPos);
5442                        if (ri == null) {
5443                            ri = sri;
5444                        }
5445                        j--;
5446                        N--;
5447                    }
5448                }
5449
5450                // Add this specific item to its proper place.
5451                if (ri == null) {
5452                    ri = new ResolveInfo();
5453                    ri.activityInfo = ai;
5454                }
5455                results.add(specificsPos, ri);
5456                ri.specificIndex = i;
5457                specificsPos++;
5458            }
5459        }
5460
5461        // Now we go through the remaining generic results and remove any
5462        // duplicate actions that are found here.
5463        N = results.size();
5464        for (int i=specificsPos; i<N-1; i++) {
5465            final ResolveInfo rii = results.get(i);
5466            if (rii.filter == null) {
5467                continue;
5468            }
5469
5470            // Iterate over all of the actions of this result's intent
5471            // filter...  typically this should be just one.
5472            final Iterator<String> it = rii.filter.actionsIterator();
5473            if (it == null) {
5474                continue;
5475            }
5476            while (it.hasNext()) {
5477                final String action = it.next();
5478                if (resultsAction != null && resultsAction.equals(action)) {
5479                    // If this action was explicitly requested, then don't
5480                    // remove things that have it.
5481                    continue;
5482                }
5483                for (int j=i+1; j<N; j++) {
5484                    final ResolveInfo rij = results.get(j);
5485                    if (rij.filter != null && rij.filter.hasAction(action)) {
5486                        results.remove(j);
5487                        if (DEBUG_INTENT_MATCHING) Log.v(
5488                            TAG, "Removing duplicate item from " + j
5489                            + " due to action " + action + " at " + i);
5490                        j--;
5491                        N--;
5492                    }
5493                }
5494            }
5495
5496            // If the caller didn't request filter information, drop it now
5497            // so we don't have to marshall/unmarshall it.
5498            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5499                rii.filter = null;
5500            }
5501        }
5502
5503        // Filter out the caller activity if so requested.
5504        if (caller != null) {
5505            N = results.size();
5506            for (int i=0; i<N; i++) {
5507                ActivityInfo ainfo = results.get(i).activityInfo;
5508                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5509                        && caller.getClassName().equals(ainfo.name)) {
5510                    results.remove(i);
5511                    break;
5512                }
5513            }
5514        }
5515
5516        // If the caller didn't request filter information,
5517        // drop them now so we don't have to
5518        // marshall/unmarshall it.
5519        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5520            N = results.size();
5521            for (int i=0; i<N; i++) {
5522                results.get(i).filter = null;
5523            }
5524        }
5525
5526        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5527        return results;
5528    }
5529
5530    @Override
5531    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5532            int userId) {
5533        if (!sUserManager.exists(userId)) return Collections.emptyList();
5534        flags = augmentFlagsForUser(flags, userId);
5535        ComponentName comp = intent.getComponent();
5536        if (comp == null) {
5537            if (intent.getSelector() != null) {
5538                intent = intent.getSelector();
5539                comp = intent.getComponent();
5540            }
5541        }
5542        if (comp != null) {
5543            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5544            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5545            if (ai != null) {
5546                ResolveInfo ri = new ResolveInfo();
5547                ri.activityInfo = ai;
5548                list.add(ri);
5549            }
5550            return list;
5551        }
5552
5553        // reader
5554        synchronized (mPackages) {
5555            String pkgName = intent.getPackage();
5556            if (pkgName == null) {
5557                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5558            }
5559            final PackageParser.Package pkg = mPackages.get(pkgName);
5560            if (pkg != null) {
5561                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5562                        userId);
5563            }
5564            return null;
5565        }
5566    }
5567
5568    @Override
5569    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5570        if (!sUserManager.exists(userId)) return null;
5571        flags = augmentFlagsForUser(flags, userId);
5572        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5573        if (query != null) {
5574            if (query.size() >= 1) {
5575                // If there is more than one service with the same priority,
5576                // just arbitrarily pick the first one.
5577                return query.get(0);
5578            }
5579        }
5580        return null;
5581    }
5582
5583    @Override
5584    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5585            int userId) {
5586        if (!sUserManager.exists(userId)) return Collections.emptyList();
5587        flags = augmentFlagsForUser(flags, userId);
5588        ComponentName comp = intent.getComponent();
5589        if (comp == null) {
5590            if (intent.getSelector() != null) {
5591                intent = intent.getSelector();
5592                comp = intent.getComponent();
5593            }
5594        }
5595        if (comp != null) {
5596            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5597            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5598            if (si != null) {
5599                final ResolveInfo ri = new ResolveInfo();
5600                ri.serviceInfo = si;
5601                list.add(ri);
5602            }
5603            return list;
5604        }
5605
5606        // reader
5607        synchronized (mPackages) {
5608            String pkgName = intent.getPackage();
5609            if (pkgName == null) {
5610                return mServices.queryIntent(intent, resolvedType, flags, userId);
5611            }
5612            final PackageParser.Package pkg = mPackages.get(pkgName);
5613            if (pkg != null) {
5614                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5615                        userId);
5616            }
5617            return null;
5618        }
5619    }
5620
5621    @Override
5622    public List<ResolveInfo> queryIntentContentProviders(
5623            Intent intent, String resolvedType, int flags, int userId) {
5624        if (!sUserManager.exists(userId)) return Collections.emptyList();
5625        flags = augmentFlagsForUser(flags, userId);
5626        ComponentName comp = intent.getComponent();
5627        if (comp == null) {
5628            if (intent.getSelector() != null) {
5629                intent = intent.getSelector();
5630                comp = intent.getComponent();
5631            }
5632        }
5633        if (comp != null) {
5634            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5635            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5636            if (pi != null) {
5637                final ResolveInfo ri = new ResolveInfo();
5638                ri.providerInfo = pi;
5639                list.add(ri);
5640            }
5641            return list;
5642        }
5643
5644        // reader
5645        synchronized (mPackages) {
5646            String pkgName = intent.getPackage();
5647            if (pkgName == null) {
5648                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5649            }
5650            final PackageParser.Package pkg = mPackages.get(pkgName);
5651            if (pkg != null) {
5652                return mProviders.queryIntentForPackage(
5653                        intent, resolvedType, flags, pkg.providers, userId);
5654            }
5655            return null;
5656        }
5657    }
5658
5659    @Override
5660    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5661        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5662
5663        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5664
5665        // writer
5666        synchronized (mPackages) {
5667            ArrayList<PackageInfo> list;
5668            if (listUninstalled) {
5669                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5670                for (PackageSetting ps : mSettings.mPackages.values()) {
5671                    PackageInfo pi;
5672                    if (ps.pkg != null) {
5673                        pi = generatePackageInfo(ps.pkg, flags, userId);
5674                    } else {
5675                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5676                    }
5677                    if (pi != null) {
5678                        list.add(pi);
5679                    }
5680                }
5681            } else {
5682                list = new ArrayList<PackageInfo>(mPackages.size());
5683                for (PackageParser.Package p : mPackages.values()) {
5684                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5685                    if (pi != null) {
5686                        list.add(pi);
5687                    }
5688                }
5689            }
5690
5691            return new ParceledListSlice<PackageInfo>(list);
5692        }
5693    }
5694
5695    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5696            String[] permissions, boolean[] tmp, int flags, int userId) {
5697        int numMatch = 0;
5698        final PermissionsState permissionsState = ps.getPermissionsState();
5699        for (int i=0; i<permissions.length; i++) {
5700            final String permission = permissions[i];
5701            if (permissionsState.hasPermission(permission, userId)) {
5702                tmp[i] = true;
5703                numMatch++;
5704            } else {
5705                tmp[i] = false;
5706            }
5707        }
5708        if (numMatch == 0) {
5709            return;
5710        }
5711        PackageInfo pi;
5712        if (ps.pkg != null) {
5713            pi = generatePackageInfo(ps.pkg, flags, userId);
5714        } else {
5715            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5716        }
5717        // The above might return null in cases of uninstalled apps or install-state
5718        // skew across users/profiles.
5719        if (pi != null) {
5720            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5721                if (numMatch == permissions.length) {
5722                    pi.requestedPermissions = permissions;
5723                } else {
5724                    pi.requestedPermissions = new String[numMatch];
5725                    numMatch = 0;
5726                    for (int i=0; i<permissions.length; i++) {
5727                        if (tmp[i]) {
5728                            pi.requestedPermissions[numMatch] = permissions[i];
5729                            numMatch++;
5730                        }
5731                    }
5732                }
5733            }
5734            list.add(pi);
5735        }
5736    }
5737
5738    @Override
5739    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5740            String[] permissions, int flags, int userId) {
5741        if (!sUserManager.exists(userId)) return null;
5742        flags = augmentFlagsForUser(flags, userId);
5743        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5744
5745        // writer
5746        synchronized (mPackages) {
5747            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5748            boolean[] tmpBools = new boolean[permissions.length];
5749            if (listUninstalled) {
5750                for (PackageSetting ps : mSettings.mPackages.values()) {
5751                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5752                }
5753            } else {
5754                for (PackageParser.Package pkg : mPackages.values()) {
5755                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5756                    if (ps != null) {
5757                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5758                                userId);
5759                    }
5760                }
5761            }
5762
5763            return new ParceledListSlice<PackageInfo>(list);
5764        }
5765    }
5766
5767    @Override
5768    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5769        if (!sUserManager.exists(userId)) return null;
5770        flags = augmentFlagsForUser(flags, userId);
5771        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5772
5773        // writer
5774        synchronized (mPackages) {
5775            ArrayList<ApplicationInfo> list;
5776            if (listUninstalled) {
5777                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5778                for (PackageSetting ps : mSettings.mPackages.values()) {
5779                    ApplicationInfo ai;
5780                    if (ps.pkg != null) {
5781                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5782                                ps.readUserState(userId), userId);
5783                    } else {
5784                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5785                    }
5786                    if (ai != null) {
5787                        list.add(ai);
5788                    }
5789                }
5790            } else {
5791                list = new ArrayList<ApplicationInfo>(mPackages.size());
5792                for (PackageParser.Package p : mPackages.values()) {
5793                    if (p.mExtras != null) {
5794                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5795                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5796                        if (ai != null) {
5797                            list.add(ai);
5798                        }
5799                    }
5800                }
5801            }
5802
5803            return new ParceledListSlice<ApplicationInfo>(list);
5804        }
5805    }
5806
5807    @Override
5808    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5809        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5810                "getEphemeralApplications");
5811        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5812                "getEphemeralApplications");
5813        synchronized (mPackages) {
5814            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5815                    .getEphemeralApplicationsLPw(userId);
5816            if (ephemeralApps != null) {
5817                return new ParceledListSlice<>(ephemeralApps);
5818            }
5819        }
5820        return null;
5821    }
5822
5823    @Override
5824    public boolean isEphemeralApplication(String packageName, int userId) {
5825        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5826                "isEphemeral");
5827        if (!isCallerSameApp(packageName)) {
5828            return false;
5829        }
5830        synchronized (mPackages) {
5831            PackageParser.Package pkg = mPackages.get(packageName);
5832            if (pkg != null) {
5833                return pkg.applicationInfo.isEphemeralApp();
5834            }
5835        }
5836        return false;
5837    }
5838
5839    @Override
5840    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5841        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5842                "getCookie");
5843        if (!isCallerSameApp(packageName)) {
5844            return null;
5845        }
5846        synchronized (mPackages) {
5847            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5848                    packageName, userId);
5849        }
5850    }
5851
5852    @Override
5853    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5854        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5855                "setCookie");
5856        if (!isCallerSameApp(packageName)) {
5857            return false;
5858        }
5859        synchronized (mPackages) {
5860            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5861                    packageName, cookie, userId);
5862        }
5863    }
5864
5865    @Override
5866    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5867        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5868                "getEphemeralApplicationIcon");
5869        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5870                "getEphemeralApplicationIcon");
5871        synchronized (mPackages) {
5872            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5873                    packageName, userId);
5874        }
5875    }
5876
5877    private boolean isCallerSameApp(String packageName) {
5878        PackageParser.Package pkg = mPackages.get(packageName);
5879        return pkg != null
5880                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5881    }
5882
5883    public List<ApplicationInfo> getPersistentApplications(int flags) {
5884        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5885
5886        // reader
5887        synchronized (mPackages) {
5888            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5889            final int userId = UserHandle.getCallingUserId();
5890            while (i.hasNext()) {
5891                final PackageParser.Package p = i.next();
5892                if (p.applicationInfo != null
5893                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5894                        && (!mSafeMode || isSystemApp(p))) {
5895                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5896                    if (ps != null) {
5897                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5898                                ps.readUserState(userId), userId);
5899                        if (ai != null) {
5900                            finalList.add(ai);
5901                        }
5902                    }
5903                }
5904            }
5905        }
5906
5907        return finalList;
5908    }
5909
5910    @Override
5911    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5912        if (!sUserManager.exists(userId)) return null;
5913        flags = augmentFlagsForUser(flags, userId);
5914        // reader
5915        synchronized (mPackages) {
5916            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5917            PackageSetting ps = provider != null
5918                    ? mSettings.mPackages.get(provider.owner.packageName)
5919                    : null;
5920            return ps != null
5921                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5922                    && (!mSafeMode || (provider.info.applicationInfo.flags
5923                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5924                    ? PackageParser.generateProviderInfo(provider, flags,
5925                            ps.readUserState(userId), userId)
5926                    : null;
5927        }
5928    }
5929
5930    /**
5931     * @deprecated
5932     */
5933    @Deprecated
5934    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5935        // reader
5936        synchronized (mPackages) {
5937            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5938                    .entrySet().iterator();
5939            final int userId = UserHandle.getCallingUserId();
5940            while (i.hasNext()) {
5941                Map.Entry<String, PackageParser.Provider> entry = i.next();
5942                PackageParser.Provider p = entry.getValue();
5943                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5944
5945                if (ps != null && p.syncable
5946                        && (!mSafeMode || (p.info.applicationInfo.flags
5947                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5948                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5949                            ps.readUserState(userId), userId);
5950                    if (info != null) {
5951                        outNames.add(entry.getKey());
5952                        outInfo.add(info);
5953                    }
5954                }
5955            }
5956        }
5957    }
5958
5959    @Override
5960    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5961            int uid, int flags) {
5962        final int userId = processName != null ? UserHandle.getUserId(uid)
5963                : UserHandle.getCallingUserId();
5964        if (!sUserManager.exists(userId)) return null;
5965        flags = augmentFlagsForUser(flags, userId);
5966
5967        ArrayList<ProviderInfo> finalList = null;
5968        // reader
5969        synchronized (mPackages) {
5970            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5971            while (i.hasNext()) {
5972                final PackageParser.Provider p = i.next();
5973                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5974                if (ps != null && p.info.authority != null
5975                        && (processName == null
5976                                || (p.info.processName.equals(processName)
5977                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5978                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5979                        && (!mSafeMode
5980                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5981                    if (finalList == null) {
5982                        finalList = new ArrayList<ProviderInfo>(3);
5983                    }
5984                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5985                            ps.readUserState(userId), userId);
5986                    if (info != null) {
5987                        finalList.add(info);
5988                    }
5989                }
5990            }
5991        }
5992
5993        if (finalList != null) {
5994            Collections.sort(finalList, mProviderInitOrderSorter);
5995            return new ParceledListSlice<ProviderInfo>(finalList);
5996        }
5997
5998        return null;
5999    }
6000
6001    @Override
6002    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
6003            int flags) {
6004        // reader
6005        synchronized (mPackages) {
6006            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6007            return PackageParser.generateInstrumentationInfo(i, flags);
6008        }
6009    }
6010
6011    @Override
6012    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6013            int flags) {
6014        ArrayList<InstrumentationInfo> finalList =
6015            new ArrayList<InstrumentationInfo>();
6016
6017        // reader
6018        synchronized (mPackages) {
6019            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6020            while (i.hasNext()) {
6021                final PackageParser.Instrumentation p = i.next();
6022                if (targetPackage == null
6023                        || targetPackage.equals(p.info.targetPackage)) {
6024                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6025                            flags);
6026                    if (ii != null) {
6027                        finalList.add(ii);
6028                    }
6029                }
6030            }
6031        }
6032
6033        return finalList;
6034    }
6035
6036    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6037        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6038        if (overlays == null) {
6039            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6040            return;
6041        }
6042        for (PackageParser.Package opkg : overlays.values()) {
6043            // Not much to do if idmap fails: we already logged the error
6044            // and we certainly don't want to abort installation of pkg simply
6045            // because an overlay didn't fit properly. For these reasons,
6046            // ignore the return value of createIdmapForPackagePairLI.
6047            createIdmapForPackagePairLI(pkg, opkg);
6048        }
6049    }
6050
6051    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6052            PackageParser.Package opkg) {
6053        if (!opkg.mTrustedOverlay) {
6054            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6055                    opkg.baseCodePath + ": overlay not trusted");
6056            return false;
6057        }
6058        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6059        if (overlaySet == null) {
6060            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6061                    opkg.baseCodePath + " but target package has no known overlays");
6062            return false;
6063        }
6064        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6065        // TODO: generate idmap for split APKs
6066        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6067            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6068                    + opkg.baseCodePath);
6069            return false;
6070        }
6071        PackageParser.Package[] overlayArray =
6072            overlaySet.values().toArray(new PackageParser.Package[0]);
6073        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6074            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6075                return p1.mOverlayPriority - p2.mOverlayPriority;
6076            }
6077        };
6078        Arrays.sort(overlayArray, cmp);
6079
6080        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6081        int i = 0;
6082        for (PackageParser.Package p : overlayArray) {
6083            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6084        }
6085        return true;
6086    }
6087
6088    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6089        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6090        try {
6091            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6092        } finally {
6093            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6094        }
6095    }
6096
6097    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6098        final File[] files = dir.listFiles();
6099        if (ArrayUtils.isEmpty(files)) {
6100            Log.d(TAG, "No files in app dir " + dir);
6101            return;
6102        }
6103
6104        if (DEBUG_PACKAGE_SCANNING) {
6105            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6106                    + " flags=0x" + Integer.toHexString(parseFlags));
6107        }
6108
6109        for (File file : files) {
6110            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6111                    && !PackageInstallerService.isStageName(file.getName());
6112            if (!isPackage) {
6113                // Ignore entries which are not packages
6114                continue;
6115            }
6116            try {
6117                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6118                        scanFlags, currentTime, null);
6119            } catch (PackageManagerException e) {
6120                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6121
6122                // Delete invalid userdata apps
6123                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6124                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6125                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6126                    if (file.isDirectory()) {
6127                        mInstaller.rmPackageDir(file.getAbsolutePath());
6128                    } else {
6129                        file.delete();
6130                    }
6131                }
6132            }
6133        }
6134    }
6135
6136    private static File getSettingsProblemFile() {
6137        File dataDir = Environment.getDataDirectory();
6138        File systemDir = new File(dataDir, "system");
6139        File fname = new File(systemDir, "uiderrors.txt");
6140        return fname;
6141    }
6142
6143    static void reportSettingsProblem(int priority, String msg) {
6144        logCriticalInfo(priority, msg);
6145    }
6146
6147    static void logCriticalInfo(int priority, String msg) {
6148        Slog.println(priority, TAG, msg);
6149        EventLogTags.writePmCriticalInfo(msg);
6150        try {
6151            File fname = getSettingsProblemFile();
6152            FileOutputStream out = new FileOutputStream(fname, true);
6153            PrintWriter pw = new FastPrintWriter(out);
6154            SimpleDateFormat formatter = new SimpleDateFormat();
6155            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6156            pw.println(dateString + ": " + msg);
6157            pw.close();
6158            FileUtils.setPermissions(
6159                    fname.toString(),
6160                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6161                    -1, -1);
6162        } catch (java.io.IOException e) {
6163        }
6164    }
6165
6166    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6167            PackageParser.Package pkg, File srcFile, int parseFlags)
6168            throws PackageManagerException {
6169        if (ps != null
6170                && ps.codePath.equals(srcFile)
6171                && ps.timeStamp == srcFile.lastModified()
6172                && !isCompatSignatureUpdateNeeded(pkg)
6173                && !isRecoverSignatureUpdateNeeded(pkg)) {
6174            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6175            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6176            ArraySet<PublicKey> signingKs;
6177            synchronized (mPackages) {
6178                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6179            }
6180            if (ps.signatures.mSignatures != null
6181                    && ps.signatures.mSignatures.length != 0
6182                    && signingKs != null) {
6183                // Optimization: reuse the existing cached certificates
6184                // if the package appears to be unchanged.
6185                pkg.mSignatures = ps.signatures.mSignatures;
6186                pkg.mSigningKeys = signingKs;
6187                return;
6188            }
6189
6190            Slog.w(TAG, "PackageSetting for " + ps.name
6191                    + " is missing signatures.  Collecting certs again to recover them.");
6192        } else {
6193            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6194        }
6195
6196        try {
6197            pp.collectCertificates(pkg, parseFlags);
6198            pp.collectManifestDigest(pkg);
6199        } catch (PackageParserException e) {
6200            throw PackageManagerException.from(e);
6201        }
6202    }
6203
6204    /**
6205     *  Traces a package scan.
6206     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6207     */
6208    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6209            long currentTime, UserHandle user) throws PackageManagerException {
6210        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6211        try {
6212            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6213        } finally {
6214            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6215        }
6216    }
6217
6218    /**
6219     *  Scans a package and returns the newly parsed package.
6220     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6221     */
6222    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6223            long currentTime, UserHandle user) throws PackageManagerException {
6224        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6225        parseFlags |= mDefParseFlags;
6226        PackageParser pp = new PackageParser();
6227        pp.setSeparateProcesses(mSeparateProcesses);
6228        pp.setOnlyCoreApps(mOnlyCore);
6229        pp.setDisplayMetrics(mMetrics);
6230
6231        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6232            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6233        }
6234
6235        final PackageParser.Package pkg;
6236        try {
6237            pkg = pp.parsePackage(scanFile, parseFlags);
6238        } catch (PackageParserException e) {
6239            throw PackageManagerException.from(e);
6240        }
6241
6242        PackageSetting ps = null;
6243        PackageSetting updatedPkg;
6244        // reader
6245        synchronized (mPackages) {
6246            // Look to see if we already know about this package.
6247            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6248            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6249                // This package has been renamed to its original name.  Let's
6250                // use that.
6251                ps = mSettings.peekPackageLPr(oldName);
6252            }
6253            // If there was no original package, see one for the real package name.
6254            if (ps == null) {
6255                ps = mSettings.peekPackageLPr(pkg.packageName);
6256            }
6257            // Check to see if this package could be hiding/updating a system
6258            // package.  Must look for it either under the original or real
6259            // package name depending on our state.
6260            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6261            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6262        }
6263        boolean updatedPkgBetter = false;
6264        // First check if this is a system package that may involve an update
6265        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6266            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6267            // it needs to drop FLAG_PRIVILEGED.
6268            if (locationIsPrivileged(scanFile)) {
6269                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6270            } else {
6271                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6272            }
6273
6274            if (ps != null && !ps.codePath.equals(scanFile)) {
6275                // The path has changed from what was last scanned...  check the
6276                // version of the new path against what we have stored to determine
6277                // what to do.
6278                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6279                if (pkg.mVersionCode <= ps.versionCode) {
6280                    // The system package has been updated and the code path does not match
6281                    // Ignore entry. Skip it.
6282                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6283                            + " ignored: updated version " + ps.versionCode
6284                            + " better than this " + pkg.mVersionCode);
6285                    if (!updatedPkg.codePath.equals(scanFile)) {
6286                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6287                                + ps.name + " changing from " + updatedPkg.codePathString
6288                                + " to " + scanFile);
6289                        updatedPkg.codePath = scanFile;
6290                        updatedPkg.codePathString = scanFile.toString();
6291                        updatedPkg.resourcePath = scanFile;
6292                        updatedPkg.resourcePathString = scanFile.toString();
6293                    }
6294                    updatedPkg.pkg = pkg;
6295                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6296                            "Package " + ps.name + " at " + scanFile
6297                                    + " ignored: updated version " + ps.versionCode
6298                                    + " better than this " + pkg.mVersionCode);
6299                } else {
6300                    // The current app on the system partition is better than
6301                    // what we have updated to on the data partition; switch
6302                    // back to the system partition version.
6303                    // At this point, its safely assumed that package installation for
6304                    // apps in system partition will go through. If not there won't be a working
6305                    // version of the app
6306                    // writer
6307                    synchronized (mPackages) {
6308                        // Just remove the loaded entries from package lists.
6309                        mPackages.remove(ps.name);
6310                    }
6311
6312                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6313                            + " reverting from " + ps.codePathString
6314                            + ": new version " + pkg.mVersionCode
6315                            + " better than installed " + ps.versionCode);
6316
6317                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6318                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6319                    synchronized (mInstallLock) {
6320                        args.cleanUpResourcesLI();
6321                    }
6322                    synchronized (mPackages) {
6323                        mSettings.enableSystemPackageLPw(ps.name);
6324                    }
6325                    updatedPkgBetter = true;
6326                }
6327            }
6328        }
6329
6330        if (updatedPkg != null) {
6331            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6332            // initially
6333            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6334
6335            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6336            // flag set initially
6337            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6338                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6339            }
6340        }
6341
6342        // Verify certificates against what was last scanned
6343        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6344
6345        /*
6346         * A new system app appeared, but we already had a non-system one of the
6347         * same name installed earlier.
6348         */
6349        boolean shouldHideSystemApp = false;
6350        if (updatedPkg == null && ps != null
6351                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6352            /*
6353             * Check to make sure the signatures match first. If they don't,
6354             * wipe the installed application and its data.
6355             */
6356            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6357                    != PackageManager.SIGNATURE_MATCH) {
6358                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6359                        + " signatures don't match existing userdata copy; removing");
6360                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6361                ps = null;
6362            } else {
6363                /*
6364                 * If the newly-added system app is an older version than the
6365                 * already installed version, hide it. It will be scanned later
6366                 * and re-added like an update.
6367                 */
6368                if (pkg.mVersionCode <= ps.versionCode) {
6369                    shouldHideSystemApp = true;
6370                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6371                            + " but new version " + pkg.mVersionCode + " better than installed "
6372                            + ps.versionCode + "; hiding system");
6373                } else {
6374                    /*
6375                     * The newly found system app is a newer version that the
6376                     * one previously installed. Simply remove the
6377                     * already-installed application and replace it with our own
6378                     * while keeping the application data.
6379                     */
6380                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6381                            + " reverting from " + ps.codePathString + ": new version "
6382                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6383                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6384                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6385                    synchronized (mInstallLock) {
6386                        args.cleanUpResourcesLI();
6387                    }
6388                }
6389            }
6390        }
6391
6392        // The apk is forward locked (not public) if its code and resources
6393        // are kept in different files. (except for app in either system or
6394        // vendor path).
6395        // TODO grab this value from PackageSettings
6396        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6397            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6398                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6399            }
6400        }
6401
6402        // TODO: extend to support forward-locked splits
6403        String resourcePath = null;
6404        String baseResourcePath = null;
6405        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6406            if (ps != null && ps.resourcePathString != null) {
6407                resourcePath = ps.resourcePathString;
6408                baseResourcePath = ps.resourcePathString;
6409            } else {
6410                // Should not happen at all. Just log an error.
6411                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6412            }
6413        } else {
6414            resourcePath = pkg.codePath;
6415            baseResourcePath = pkg.baseCodePath;
6416        }
6417
6418        // Set application objects path explicitly.
6419        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6420        pkg.applicationInfo.setCodePath(pkg.codePath);
6421        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6422        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6423        pkg.applicationInfo.setResourcePath(resourcePath);
6424        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6425        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6426
6427        // Note that we invoke the following method only if we are about to unpack an application
6428        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6429                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6430
6431        /*
6432         * If the system app should be overridden by a previously installed
6433         * data, hide the system app now and let the /data/app scan pick it up
6434         * again.
6435         */
6436        if (shouldHideSystemApp) {
6437            synchronized (mPackages) {
6438                mSettings.disableSystemPackageLPw(pkg.packageName);
6439            }
6440        }
6441
6442        return scannedPkg;
6443    }
6444
6445    private static String fixProcessName(String defProcessName,
6446            String processName, int uid) {
6447        if (processName == null) {
6448            return defProcessName;
6449        }
6450        return processName;
6451    }
6452
6453    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6454            throws PackageManagerException {
6455        if (pkgSetting.signatures.mSignatures != null) {
6456            // Already existing package. Make sure signatures match
6457            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6458                    == PackageManager.SIGNATURE_MATCH;
6459            if (!match) {
6460                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6461                        == PackageManager.SIGNATURE_MATCH;
6462            }
6463            if (!match) {
6464                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6465                        == PackageManager.SIGNATURE_MATCH;
6466            }
6467            if (!match) {
6468                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6469                        + pkg.packageName + " signatures do not match the "
6470                        + "previously installed version; ignoring!");
6471            }
6472        }
6473
6474        // Check for shared user signatures
6475        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6476            // Already existing package. Make sure signatures match
6477            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6478                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6479            if (!match) {
6480                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6481                        == PackageManager.SIGNATURE_MATCH;
6482            }
6483            if (!match) {
6484                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6485                        == PackageManager.SIGNATURE_MATCH;
6486            }
6487            if (!match) {
6488                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6489                        "Package " + pkg.packageName
6490                        + " has no signatures that match those in shared user "
6491                        + pkgSetting.sharedUser.name + "; ignoring!");
6492            }
6493        }
6494    }
6495
6496    /**
6497     * Enforces that only the system UID or root's UID can call a method exposed
6498     * via Binder.
6499     *
6500     * @param message used as message if SecurityException is thrown
6501     * @throws SecurityException if the caller is not system or root
6502     */
6503    private static final void enforceSystemOrRoot(String message) {
6504        final int uid = Binder.getCallingUid();
6505        if (uid != Process.SYSTEM_UID && uid != 0) {
6506            throw new SecurityException(message);
6507        }
6508    }
6509
6510    @Override
6511    public void performFstrimIfNeeded() {
6512        enforceSystemOrRoot("Only the system can request fstrim");
6513
6514        // Before everything else, see whether we need to fstrim.
6515        try {
6516            IMountService ms = PackageHelper.getMountService();
6517            if (ms != null) {
6518                final boolean isUpgrade = isUpgrade();
6519                boolean doTrim = isUpgrade;
6520                if (doTrim) {
6521                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6522                } else {
6523                    final long interval = android.provider.Settings.Global.getLong(
6524                            mContext.getContentResolver(),
6525                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6526                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6527                    if (interval > 0) {
6528                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6529                        if (timeSinceLast > interval) {
6530                            doTrim = true;
6531                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6532                                    + "; running immediately");
6533                        }
6534                    }
6535                }
6536                if (doTrim) {
6537                    if (!isFirstBoot()) {
6538                        try {
6539                            ActivityManagerNative.getDefault().showBootMessage(
6540                                    mContext.getResources().getString(
6541                                            R.string.android_upgrading_fstrim), true);
6542                        } catch (RemoteException e) {
6543                        }
6544                    }
6545                    ms.runMaintenance();
6546                }
6547            } else {
6548                Slog.e(TAG, "Mount service unavailable!");
6549            }
6550        } catch (RemoteException e) {
6551            // Can't happen; MountService is local
6552        }
6553    }
6554
6555    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6556        List<ResolveInfo> ris = null;
6557        try {
6558            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6559                    intent, null, 0, userId);
6560        } catch (RemoteException e) {
6561        }
6562        ArraySet<String> pkgNames = new ArraySet<String>();
6563        if (ris != null) {
6564            for (ResolveInfo ri : ris) {
6565                pkgNames.add(ri.activityInfo.packageName);
6566            }
6567        }
6568        return pkgNames;
6569    }
6570
6571    @Override
6572    public void notifyPackageUse(String packageName) {
6573        synchronized (mPackages) {
6574            PackageParser.Package p = mPackages.get(packageName);
6575            if (p == null) {
6576                return;
6577            }
6578            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6579        }
6580    }
6581
6582    @Override
6583    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6584        return performDexOptTraced(packageName, instructionSet);
6585    }
6586
6587    public boolean performDexOpt(String packageName, String instructionSet) {
6588        return performDexOptTraced(packageName, instructionSet);
6589    }
6590
6591    private boolean performDexOptTraced(String packageName, String instructionSet) {
6592        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6593        try {
6594            return performDexOptInternal(packageName, instructionSet);
6595        } finally {
6596            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6597        }
6598    }
6599
6600    private boolean performDexOptInternal(String packageName, String instructionSet) {
6601        PackageParser.Package p;
6602        final String targetInstructionSet;
6603        synchronized (mPackages) {
6604            p = mPackages.get(packageName);
6605            if (p == null) {
6606                return false;
6607            }
6608            mPackageUsage.write(false);
6609
6610            targetInstructionSet = instructionSet != null ? instructionSet :
6611                    getPrimaryInstructionSet(p.applicationInfo);
6612            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6613                return false;
6614            }
6615        }
6616        long callingId = Binder.clearCallingIdentity();
6617        try {
6618            synchronized (mInstallLock) {
6619                final String[] instructionSets = new String[] { targetInstructionSet };
6620                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6621                        true /* inclDependencies */);
6622                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6623            }
6624        } finally {
6625            Binder.restoreCallingIdentity(callingId);
6626        }
6627    }
6628
6629    public ArraySet<String> getPackagesThatNeedDexOpt() {
6630        ArraySet<String> pkgs = null;
6631        synchronized (mPackages) {
6632            for (PackageParser.Package p : mPackages.values()) {
6633                if (DEBUG_DEXOPT) {
6634                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6635                }
6636                if (!p.mDexOptPerformed.isEmpty()) {
6637                    continue;
6638                }
6639                if (pkgs == null) {
6640                    pkgs = new ArraySet<String>();
6641                }
6642                pkgs.add(p.packageName);
6643            }
6644        }
6645        return pkgs;
6646    }
6647
6648    public void shutdown() {
6649        mPackageUsage.write(true);
6650    }
6651
6652    @Override
6653    public void forceDexOpt(String packageName) {
6654        enforceSystemOrRoot("forceDexOpt");
6655
6656        PackageParser.Package pkg;
6657        synchronized (mPackages) {
6658            pkg = mPackages.get(packageName);
6659            if (pkg == null) {
6660                throw new IllegalArgumentException("Missing package: " + packageName);
6661            }
6662        }
6663
6664        synchronized (mInstallLock) {
6665            final String[] instructionSets = new String[] {
6666                    getPrimaryInstructionSet(pkg.applicationInfo) };
6667
6668            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6669
6670            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6671                    true /* inclDependencies */);
6672
6673            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6674            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6675                throw new IllegalStateException("Failed to dexopt: " + res);
6676            }
6677        }
6678    }
6679
6680    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6681        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6682            Slog.w(TAG, "Unable to update from " + oldPkg.name
6683                    + " to " + newPkg.packageName
6684                    + ": old package not in system partition");
6685            return false;
6686        } else if (mPackages.get(oldPkg.name) != null) {
6687            Slog.w(TAG, "Unable to update from " + oldPkg.name
6688                    + " to " + newPkg.packageName
6689                    + ": old package still exists");
6690            return false;
6691        }
6692        return true;
6693    }
6694
6695    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6696            throws PackageManagerException {
6697        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6698        if (res != 0) {
6699            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6700                    "Failed to install " + packageName + ": " + res);
6701        }
6702
6703        final int[] users = sUserManager.getUserIds();
6704        for (int user : users) {
6705            if (user != 0) {
6706                res = mInstaller.createUserData(volumeUuid, packageName,
6707                        UserHandle.getUid(user, uid), user, seinfo);
6708                if (res != 0) {
6709                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6710                            "Failed to createUserData " + packageName + ": " + res);
6711                }
6712            }
6713        }
6714    }
6715
6716    private int removeDataDirsLI(String volumeUuid, String packageName) {
6717        int[] users = sUserManager.getUserIds();
6718        int res = 0;
6719        for (int user : users) {
6720            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6721            if (resInner < 0) {
6722                res = resInner;
6723            }
6724        }
6725
6726        return res;
6727    }
6728
6729    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6730        int[] users = sUserManager.getUserIds();
6731        int res = 0;
6732        for (int user : users) {
6733            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6734            if (resInner < 0) {
6735                res = resInner;
6736            }
6737        }
6738        return res;
6739    }
6740
6741    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6742            PackageParser.Package changingLib) {
6743        if (file.path != null) {
6744            usesLibraryFiles.add(file.path);
6745            return;
6746        }
6747        PackageParser.Package p = mPackages.get(file.apk);
6748        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6749            // If we are doing this while in the middle of updating a library apk,
6750            // then we need to make sure to use that new apk for determining the
6751            // dependencies here.  (We haven't yet finished committing the new apk
6752            // to the package manager state.)
6753            if (p == null || p.packageName.equals(changingLib.packageName)) {
6754                p = changingLib;
6755            }
6756        }
6757        if (p != null) {
6758            usesLibraryFiles.addAll(p.getAllCodePaths());
6759        }
6760    }
6761
6762    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6763            PackageParser.Package changingLib) throws PackageManagerException {
6764        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6765            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6766            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6767            for (int i=0; i<N; i++) {
6768                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6769                if (file == null) {
6770                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6771                            "Package " + pkg.packageName + " requires unavailable shared library "
6772                            + pkg.usesLibraries.get(i) + "; failing!");
6773                }
6774                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6775            }
6776            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6777            for (int i=0; i<N; i++) {
6778                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6779                if (file == null) {
6780                    Slog.w(TAG, "Package " + pkg.packageName
6781                            + " desires unavailable shared library "
6782                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6783                } else {
6784                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6785                }
6786            }
6787            N = usesLibraryFiles.size();
6788            if (N > 0) {
6789                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6790            } else {
6791                pkg.usesLibraryFiles = null;
6792            }
6793        }
6794    }
6795
6796    private static boolean hasString(List<String> list, List<String> which) {
6797        if (list == null) {
6798            return false;
6799        }
6800        for (int i=list.size()-1; i>=0; i--) {
6801            for (int j=which.size()-1; j>=0; j--) {
6802                if (which.get(j).equals(list.get(i))) {
6803                    return true;
6804                }
6805            }
6806        }
6807        return false;
6808    }
6809
6810    private void updateAllSharedLibrariesLPw() {
6811        for (PackageParser.Package pkg : mPackages.values()) {
6812            try {
6813                updateSharedLibrariesLPw(pkg, null);
6814            } catch (PackageManagerException e) {
6815                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6816            }
6817        }
6818    }
6819
6820    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6821            PackageParser.Package changingPkg) {
6822        ArrayList<PackageParser.Package> res = null;
6823        for (PackageParser.Package pkg : mPackages.values()) {
6824            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6825                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6826                if (res == null) {
6827                    res = new ArrayList<PackageParser.Package>();
6828                }
6829                res.add(pkg);
6830                try {
6831                    updateSharedLibrariesLPw(pkg, changingPkg);
6832                } catch (PackageManagerException e) {
6833                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6834                }
6835            }
6836        }
6837        return res;
6838    }
6839
6840    /**
6841     * Derive the value of the {@code cpuAbiOverride} based on the provided
6842     * value and an optional stored value from the package settings.
6843     */
6844    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6845        String cpuAbiOverride = null;
6846
6847        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6848            cpuAbiOverride = null;
6849        } else if (abiOverride != null) {
6850            cpuAbiOverride = abiOverride;
6851        } else if (settings != null) {
6852            cpuAbiOverride = settings.cpuAbiOverrideString;
6853        }
6854
6855        return cpuAbiOverride;
6856    }
6857
6858    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6859            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6860        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6861        try {
6862            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6863        } finally {
6864            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6865        }
6866    }
6867
6868    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6869            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6870        boolean success = false;
6871        try {
6872            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6873                    currentTime, user);
6874            success = true;
6875            return res;
6876        } finally {
6877            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6878                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6879            }
6880        }
6881    }
6882
6883    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6884            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6885        final File scanFile = new File(pkg.codePath);
6886        if (pkg.applicationInfo.getCodePath() == null ||
6887                pkg.applicationInfo.getResourcePath() == null) {
6888            // Bail out. The resource and code paths haven't been set.
6889            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6890                    "Code and resource paths haven't been set correctly");
6891        }
6892
6893        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6894            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6895        } else {
6896            // Only allow system apps to be flagged as core apps.
6897            pkg.coreApp = false;
6898        }
6899
6900        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6901            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6902        }
6903
6904        if (mCustomResolverComponentName != null &&
6905                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6906            setUpCustomResolverActivity(pkg);
6907        }
6908
6909        if (pkg.packageName.equals("android")) {
6910            synchronized (mPackages) {
6911                if (mAndroidApplication != null) {
6912                    Slog.w(TAG, "*************************************************");
6913                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6914                    Slog.w(TAG, " file=" + scanFile);
6915                    Slog.w(TAG, "*************************************************");
6916                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6917                            "Core android package being redefined.  Skipping.");
6918                }
6919
6920                // Set up information for our fall-back user intent resolution activity.
6921                mPlatformPackage = pkg;
6922                pkg.mVersionCode = mSdkVersion;
6923                mAndroidApplication = pkg.applicationInfo;
6924
6925                if (!mResolverReplaced) {
6926                    mResolveActivity.applicationInfo = mAndroidApplication;
6927                    mResolveActivity.name = ResolverActivity.class.getName();
6928                    mResolveActivity.packageName = mAndroidApplication.packageName;
6929                    mResolveActivity.processName = "system:ui";
6930                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6931                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6932                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6933                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6934                    mResolveActivity.exported = true;
6935                    mResolveActivity.enabled = true;
6936                    mResolveInfo.activityInfo = mResolveActivity;
6937                    mResolveInfo.priority = 0;
6938                    mResolveInfo.preferredOrder = 0;
6939                    mResolveInfo.match = 0;
6940                    mResolveComponentName = new ComponentName(
6941                            mAndroidApplication.packageName, mResolveActivity.name);
6942                }
6943            }
6944        }
6945
6946        if (DEBUG_PACKAGE_SCANNING) {
6947            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6948                Log.d(TAG, "Scanning package " + pkg.packageName);
6949        }
6950
6951        if (mPackages.containsKey(pkg.packageName)
6952                || mSharedLibraries.containsKey(pkg.packageName)) {
6953            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6954                    "Application package " + pkg.packageName
6955                    + " already installed.  Skipping duplicate.");
6956        }
6957
6958        // If we're only installing presumed-existing packages, require that the
6959        // scanned APK is both already known and at the path previously established
6960        // for it.  Previously unknown packages we pick up normally, but if we have an
6961        // a priori expectation about this package's install presence, enforce it.
6962        // With a singular exception for new system packages. When an OTA contains
6963        // a new system package, we allow the codepath to change from a system location
6964        // to the user-installed location. If we don't allow this change, any newer,
6965        // user-installed version of the application will be ignored.
6966        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6967            if (mExpectingBetter.containsKey(pkg.packageName)) {
6968                logCriticalInfo(Log.WARN,
6969                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6970            } else {
6971                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6972                if (known != null) {
6973                    if (DEBUG_PACKAGE_SCANNING) {
6974                        Log.d(TAG, "Examining " + pkg.codePath
6975                                + " and requiring known paths " + known.codePathString
6976                                + " & " + known.resourcePathString);
6977                    }
6978                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6979                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6980                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6981                                "Application package " + pkg.packageName
6982                                + " found at " + pkg.applicationInfo.getCodePath()
6983                                + " but expected at " + known.codePathString + "; ignoring.");
6984                    }
6985                }
6986            }
6987        }
6988
6989        // Initialize package source and resource directories
6990        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6991        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6992
6993        SharedUserSetting suid = null;
6994        PackageSetting pkgSetting = null;
6995
6996        if (!isSystemApp(pkg)) {
6997            // Only system apps can use these features.
6998            pkg.mOriginalPackages = null;
6999            pkg.mRealPackage = null;
7000            pkg.mAdoptPermissions = null;
7001        }
7002
7003        // writer
7004        synchronized (mPackages) {
7005            if (pkg.mSharedUserId != null) {
7006                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7007                if (suid == null) {
7008                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7009                            "Creating application package " + pkg.packageName
7010                            + " for shared user failed");
7011                }
7012                if (DEBUG_PACKAGE_SCANNING) {
7013                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7014                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7015                                + "): packages=" + suid.packages);
7016                }
7017            }
7018
7019            // Check if we are renaming from an original package name.
7020            PackageSetting origPackage = null;
7021            String realName = null;
7022            if (pkg.mOriginalPackages != null) {
7023                // This package may need to be renamed to a previously
7024                // installed name.  Let's check on that...
7025                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7026                if (pkg.mOriginalPackages.contains(renamed)) {
7027                    // This package had originally been installed as the
7028                    // original name, and we have already taken care of
7029                    // transitioning to the new one.  Just update the new
7030                    // one to continue using the old name.
7031                    realName = pkg.mRealPackage;
7032                    if (!pkg.packageName.equals(renamed)) {
7033                        // Callers into this function may have already taken
7034                        // care of renaming the package; only do it here if
7035                        // it is not already done.
7036                        pkg.setPackageName(renamed);
7037                    }
7038
7039                } else {
7040                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7041                        if ((origPackage = mSettings.peekPackageLPr(
7042                                pkg.mOriginalPackages.get(i))) != null) {
7043                            // We do have the package already installed under its
7044                            // original name...  should we use it?
7045                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7046                                // New package is not compatible with original.
7047                                origPackage = null;
7048                                continue;
7049                            } else if (origPackage.sharedUser != null) {
7050                                // Make sure uid is compatible between packages.
7051                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7052                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7053                                            + " to " + pkg.packageName + ": old uid "
7054                                            + origPackage.sharedUser.name
7055                                            + " differs from " + pkg.mSharedUserId);
7056                                    origPackage = null;
7057                                    continue;
7058                                }
7059                            } else {
7060                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7061                                        + pkg.packageName + " to old name " + origPackage.name);
7062                            }
7063                            break;
7064                        }
7065                    }
7066                }
7067            }
7068
7069            if (mTransferedPackages.contains(pkg.packageName)) {
7070                Slog.w(TAG, "Package " + pkg.packageName
7071                        + " was transferred to another, but its .apk remains");
7072            }
7073
7074            // Just create the setting, don't add it yet. For already existing packages
7075            // the PkgSetting exists already and doesn't have to be created.
7076            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7077                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7078                    pkg.applicationInfo.primaryCpuAbi,
7079                    pkg.applicationInfo.secondaryCpuAbi,
7080                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7081                    user, false);
7082            if (pkgSetting == null) {
7083                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7084                        "Creating application package " + pkg.packageName + " failed");
7085            }
7086
7087            if (pkgSetting.origPackage != null) {
7088                // If we are first transitioning from an original package,
7089                // fix up the new package's name now.  We need to do this after
7090                // looking up the package under its new name, so getPackageLP
7091                // can take care of fiddling things correctly.
7092                pkg.setPackageName(origPackage.name);
7093
7094                // File a report about this.
7095                String msg = "New package " + pkgSetting.realName
7096                        + " renamed to replace old package " + pkgSetting.name;
7097                reportSettingsProblem(Log.WARN, msg);
7098
7099                // Make a note of it.
7100                mTransferedPackages.add(origPackage.name);
7101
7102                // No longer need to retain this.
7103                pkgSetting.origPackage = null;
7104            }
7105
7106            if (realName != null) {
7107                // Make a note of it.
7108                mTransferedPackages.add(pkg.packageName);
7109            }
7110
7111            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7112                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7113            }
7114
7115            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7116                // Check all shared libraries and map to their actual file path.
7117                // We only do this here for apps not on a system dir, because those
7118                // are the only ones that can fail an install due to this.  We
7119                // will take care of the system apps by updating all of their
7120                // library paths after the scan is done.
7121                updateSharedLibrariesLPw(pkg, null);
7122            }
7123
7124            if (mFoundPolicyFile) {
7125                SELinuxMMAC.assignSeinfoValue(pkg);
7126            }
7127
7128            pkg.applicationInfo.uid = pkgSetting.appId;
7129            pkg.mExtras = pkgSetting;
7130            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7131                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7132                    // We just determined the app is signed correctly, so bring
7133                    // over the latest parsed certs.
7134                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7135                } else {
7136                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7137                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7138                                "Package " + pkg.packageName + " upgrade keys do not match the "
7139                                + "previously installed version");
7140                    } else {
7141                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7142                        String msg = "System package " + pkg.packageName
7143                            + " signature changed; retaining data.";
7144                        reportSettingsProblem(Log.WARN, msg);
7145                    }
7146                }
7147            } else {
7148                try {
7149                    verifySignaturesLP(pkgSetting, pkg);
7150                    // We just determined the app is signed correctly, so bring
7151                    // over the latest parsed certs.
7152                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7153                } catch (PackageManagerException e) {
7154                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7155                        throw e;
7156                    }
7157                    // The signature has changed, but this package is in the system
7158                    // image...  let's recover!
7159                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7160                    // However...  if this package is part of a shared user, but it
7161                    // doesn't match the signature of the shared user, let's fail.
7162                    // What this means is that you can't change the signatures
7163                    // associated with an overall shared user, which doesn't seem all
7164                    // that unreasonable.
7165                    if (pkgSetting.sharedUser != null) {
7166                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7167                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7168                            throw new PackageManagerException(
7169                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7170                                            "Signature mismatch for shared user : "
7171                                            + pkgSetting.sharedUser);
7172                        }
7173                    }
7174                    // File a report about this.
7175                    String msg = "System package " + pkg.packageName
7176                        + " signature changed; retaining data.";
7177                    reportSettingsProblem(Log.WARN, msg);
7178                }
7179            }
7180            // Verify that this new package doesn't have any content providers
7181            // that conflict with existing packages.  Only do this if the
7182            // package isn't already installed, since we don't want to break
7183            // things that are installed.
7184            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7185                final int N = pkg.providers.size();
7186                int i;
7187                for (i=0; i<N; i++) {
7188                    PackageParser.Provider p = pkg.providers.get(i);
7189                    if (p.info.authority != null) {
7190                        String names[] = p.info.authority.split(";");
7191                        for (int j = 0; j < names.length; j++) {
7192                            if (mProvidersByAuthority.containsKey(names[j])) {
7193                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7194                                final String otherPackageName =
7195                                        ((other != null && other.getComponentName() != null) ?
7196                                                other.getComponentName().getPackageName() : "?");
7197                                throw new PackageManagerException(
7198                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7199                                                "Can't install because provider name " + names[j]
7200                                                + " (in package " + pkg.applicationInfo.packageName
7201                                                + ") is already used by " + otherPackageName);
7202                            }
7203                        }
7204                    }
7205                }
7206            }
7207
7208            if (pkg.mAdoptPermissions != null) {
7209                // This package wants to adopt ownership of permissions from
7210                // another package.
7211                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7212                    final String origName = pkg.mAdoptPermissions.get(i);
7213                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7214                    if (orig != null) {
7215                        if (verifyPackageUpdateLPr(orig, pkg)) {
7216                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7217                                    + pkg.packageName);
7218                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7219                        }
7220                    }
7221                }
7222            }
7223        }
7224
7225        final String pkgName = pkg.packageName;
7226
7227        final long scanFileTime = scanFile.lastModified();
7228        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7229        pkg.applicationInfo.processName = fixProcessName(
7230                pkg.applicationInfo.packageName,
7231                pkg.applicationInfo.processName,
7232                pkg.applicationInfo.uid);
7233
7234        if (pkg != mPlatformPackage) {
7235            // This is a normal package, need to make its data directory.
7236            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7237                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7238
7239            boolean uidError = false;
7240            if (dataPath.exists()) {
7241                int currentUid = 0;
7242                try {
7243                    StructStat stat = Os.stat(dataPath.getPath());
7244                    currentUid = stat.st_uid;
7245                } catch (ErrnoException e) {
7246                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7247                }
7248
7249                // If we have mismatched owners for the data path, we have a problem.
7250                if (currentUid != pkg.applicationInfo.uid) {
7251                    boolean recovered = false;
7252                    if (currentUid == 0) {
7253                        // The directory somehow became owned by root.  Wow.
7254                        // This is probably because the system was stopped while
7255                        // installd was in the middle of messing with its libs
7256                        // directory.  Ask installd to fix that.
7257                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7258                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7259                        if (ret >= 0) {
7260                            recovered = true;
7261                            String msg = "Package " + pkg.packageName
7262                                    + " unexpectedly changed to uid 0; recovered to " +
7263                                    + pkg.applicationInfo.uid;
7264                            reportSettingsProblem(Log.WARN, msg);
7265                        }
7266                    }
7267                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7268                            || (scanFlags&SCAN_BOOTING) != 0)) {
7269                        // If this is a system app, we can at least delete its
7270                        // current data so the application will still work.
7271                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7272                        if (ret >= 0) {
7273                            // TODO: Kill the processes first
7274                            // Old data gone!
7275                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7276                                    ? "System package " : "Third party package ";
7277                            String msg = prefix + pkg.packageName
7278                                    + " has changed from uid: "
7279                                    + currentUid + " to "
7280                                    + pkg.applicationInfo.uid + "; old data erased";
7281                            reportSettingsProblem(Log.WARN, msg);
7282                            recovered = true;
7283                        }
7284                        if (!recovered) {
7285                            mHasSystemUidErrors = true;
7286                        }
7287                    } else if (!recovered) {
7288                        // If we allow this install to proceed, we will be broken.
7289                        // Abort, abort!
7290                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7291                                "scanPackageLI");
7292                    }
7293                    if (!recovered) {
7294                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7295                            + pkg.applicationInfo.uid + "/fs_"
7296                            + currentUid;
7297                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7298                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7299                        String msg = "Package " + pkg.packageName
7300                                + " has mismatched uid: "
7301                                + currentUid + " on disk, "
7302                                + pkg.applicationInfo.uid + " in settings";
7303                        // writer
7304                        synchronized (mPackages) {
7305                            mSettings.mReadMessages.append(msg);
7306                            mSettings.mReadMessages.append('\n');
7307                            uidError = true;
7308                            if (!pkgSetting.uidError) {
7309                                reportSettingsProblem(Log.ERROR, msg);
7310                            }
7311                        }
7312                    }
7313                }
7314
7315                // Ensure that directories are prepared
7316                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7317                        pkg.applicationInfo.seinfo);
7318
7319                if (mShouldRestoreconData) {
7320                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7321                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7322                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7323                }
7324            } else {
7325                if (DEBUG_PACKAGE_SCANNING) {
7326                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7327                        Log.v(TAG, "Want this data dir: " + dataPath);
7328                }
7329                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7330                        pkg.applicationInfo.seinfo);
7331            }
7332
7333            // Get all of our default paths setup
7334            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7335
7336            pkgSetting.uidError = uidError;
7337        }
7338
7339        final String path = scanFile.getPath();
7340        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7341
7342        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7343            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7344
7345            // Some system apps still use directory structure for native libraries
7346            // in which case we might end up not detecting abi solely based on apk
7347            // structure. Try to detect abi based on directory structure.
7348            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7349                    pkg.applicationInfo.primaryCpuAbi == null) {
7350                setBundledAppAbisAndRoots(pkg, pkgSetting);
7351                setNativeLibraryPaths(pkg);
7352            }
7353
7354        } else {
7355            if ((scanFlags & SCAN_MOVE) != 0) {
7356                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7357                // but we already have this packages package info in the PackageSetting. We just
7358                // use that and derive the native library path based on the new codepath.
7359                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7360                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7361            }
7362
7363            // Set native library paths again. For moves, the path will be updated based on the
7364            // ABIs we've determined above. For non-moves, the path will be updated based on the
7365            // ABIs we determined during compilation, but the path will depend on the final
7366            // package path (after the rename away from the stage path).
7367            setNativeLibraryPaths(pkg);
7368        }
7369
7370        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7371        final int[] userIds = sUserManager.getUserIds();
7372        synchronized (mInstallLock) {
7373            // Make sure all user data directories are ready to roll; we're okay
7374            // if they already exist
7375            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7376                for (int userId : userIds) {
7377                    if (userId != UserHandle.USER_SYSTEM) {
7378                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7379                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7380                                pkg.applicationInfo.seinfo);
7381                    }
7382                }
7383            }
7384
7385            // Create a native library symlink only if we have native libraries
7386            // and if the native libraries are 32 bit libraries. We do not provide
7387            // this symlink for 64 bit libraries.
7388            if (pkg.applicationInfo.primaryCpuAbi != null &&
7389                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7390                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7391                try {
7392                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7393                    for (int userId : userIds) {
7394                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7395                                nativeLibPath, userId) < 0) {
7396                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7397                                    "Failed linking native library dir (user=" + userId + ")");
7398                        }
7399                    }
7400                } finally {
7401                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7402                }
7403            }
7404        }
7405
7406        // This is a special case for the "system" package, where the ABI is
7407        // dictated by the zygote configuration (and init.rc). We should keep track
7408        // of this ABI so that we can deal with "normal" applications that run under
7409        // the same UID correctly.
7410        if (mPlatformPackage == pkg) {
7411            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7412                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7413        }
7414
7415        // If there's a mismatch between the abi-override in the package setting
7416        // and the abiOverride specified for the install. Warn about this because we
7417        // would've already compiled the app without taking the package setting into
7418        // account.
7419        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7420            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7421                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7422                        " for package: " + pkg.packageName);
7423            }
7424        }
7425
7426        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7427        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7428        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7429
7430        // Copy the derived override back to the parsed package, so that we can
7431        // update the package settings accordingly.
7432        pkg.cpuAbiOverride = cpuAbiOverride;
7433
7434        if (DEBUG_ABI_SELECTION) {
7435            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7436                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7437                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7438        }
7439
7440        // Push the derived path down into PackageSettings so we know what to
7441        // clean up at uninstall time.
7442        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7443
7444        if (DEBUG_ABI_SELECTION) {
7445            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7446                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7447                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7448        }
7449
7450        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7451            // We don't do this here during boot because we can do it all
7452            // at once after scanning all existing packages.
7453            //
7454            // We also do this *before* we perform dexopt on this package, so that
7455            // we can avoid redundant dexopts, and also to make sure we've got the
7456            // code and package path correct.
7457            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7458                    pkg, true /* boot complete */);
7459        }
7460
7461        if (mFactoryTest && pkg.requestedPermissions.contains(
7462                android.Manifest.permission.FACTORY_TEST)) {
7463            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7464        }
7465
7466        ArrayList<PackageParser.Package> clientLibPkgs = null;
7467
7468        // writer
7469        synchronized (mPackages) {
7470            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7471                // Only system apps can add new shared libraries.
7472                if (pkg.libraryNames != null) {
7473                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7474                        String name = pkg.libraryNames.get(i);
7475                        boolean allowed = false;
7476                        if (pkg.isUpdatedSystemApp()) {
7477                            // New library entries can only be added through the
7478                            // system image.  This is important to get rid of a lot
7479                            // of nasty edge cases: for example if we allowed a non-
7480                            // system update of the app to add a library, then uninstalling
7481                            // the update would make the library go away, and assumptions
7482                            // we made such as through app install filtering would now
7483                            // have allowed apps on the device which aren't compatible
7484                            // with it.  Better to just have the restriction here, be
7485                            // conservative, and create many fewer cases that can negatively
7486                            // impact the user experience.
7487                            final PackageSetting sysPs = mSettings
7488                                    .getDisabledSystemPkgLPr(pkg.packageName);
7489                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7490                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7491                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7492                                        allowed = true;
7493                                        break;
7494                                    }
7495                                }
7496                            }
7497                        } else {
7498                            allowed = true;
7499                        }
7500                        if (allowed) {
7501                            if (!mSharedLibraries.containsKey(name)) {
7502                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7503                            } else if (!name.equals(pkg.packageName)) {
7504                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7505                                        + name + " already exists; skipping");
7506                            }
7507                        } else {
7508                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7509                                    + name + " that is not declared on system image; skipping");
7510                        }
7511                    }
7512                    if ((scanFlags & SCAN_BOOTING) == 0) {
7513                        // If we are not booting, we need to update any applications
7514                        // that are clients of our shared library.  If we are booting,
7515                        // this will all be done once the scan is complete.
7516                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7517                    }
7518                }
7519            }
7520        }
7521
7522        // Request the ActivityManager to kill the process(only for existing packages)
7523        // so that we do not end up in a confused state while the user is still using the older
7524        // version of the application while the new one gets installed.
7525        if ((scanFlags & SCAN_REPLACING) != 0) {
7526            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7527
7528            killApplication(pkg.applicationInfo.packageName,
7529                        pkg.applicationInfo.uid, "replace pkg");
7530
7531            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7532        }
7533
7534        // Also need to kill any apps that are dependent on the library.
7535        if (clientLibPkgs != null) {
7536            for (int i=0; i<clientLibPkgs.size(); i++) {
7537                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7538                killApplication(clientPkg.applicationInfo.packageName,
7539                        clientPkg.applicationInfo.uid, "update lib");
7540            }
7541        }
7542
7543        // Make sure we're not adding any bogus keyset info
7544        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7545        ksms.assertScannedPackageValid(pkg);
7546
7547        // writer
7548        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7549
7550        boolean createIdmapFailed = false;
7551        synchronized (mPackages) {
7552            // We don't expect installation to fail beyond this point
7553
7554            // Add the new setting to mSettings
7555            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7556            // Add the new setting to mPackages
7557            mPackages.put(pkg.applicationInfo.packageName, pkg);
7558            // Make sure we don't accidentally delete its data.
7559            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7560            while (iter.hasNext()) {
7561                PackageCleanItem item = iter.next();
7562                if (pkgName.equals(item.packageName)) {
7563                    iter.remove();
7564                }
7565            }
7566
7567            // Take care of first install / last update times.
7568            if (currentTime != 0) {
7569                if (pkgSetting.firstInstallTime == 0) {
7570                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7571                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7572                    pkgSetting.lastUpdateTime = currentTime;
7573                }
7574            } else if (pkgSetting.firstInstallTime == 0) {
7575                // We need *something*.  Take time time stamp of the file.
7576                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7577            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7578                if (scanFileTime != pkgSetting.timeStamp) {
7579                    // A package on the system image has changed; consider this
7580                    // to be an update.
7581                    pkgSetting.lastUpdateTime = scanFileTime;
7582                }
7583            }
7584
7585            // Add the package's KeySets to the global KeySetManagerService
7586            ksms.addScannedPackageLPw(pkg);
7587
7588            int N = pkg.providers.size();
7589            StringBuilder r = null;
7590            int i;
7591            for (i=0; i<N; i++) {
7592                PackageParser.Provider p = pkg.providers.get(i);
7593                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7594                        p.info.processName, pkg.applicationInfo.uid);
7595                mProviders.addProvider(p);
7596                p.syncable = p.info.isSyncable;
7597                if (p.info.authority != null) {
7598                    String names[] = p.info.authority.split(";");
7599                    p.info.authority = null;
7600                    for (int j = 0; j < names.length; j++) {
7601                        if (j == 1 && p.syncable) {
7602                            // We only want the first authority for a provider to possibly be
7603                            // syncable, so if we already added this provider using a different
7604                            // authority clear the syncable flag. We copy the provider before
7605                            // changing it because the mProviders object contains a reference
7606                            // to a provider that we don't want to change.
7607                            // Only do this for the second authority since the resulting provider
7608                            // object can be the same for all future authorities for this provider.
7609                            p = new PackageParser.Provider(p);
7610                            p.syncable = false;
7611                        }
7612                        if (!mProvidersByAuthority.containsKey(names[j])) {
7613                            mProvidersByAuthority.put(names[j], p);
7614                            if (p.info.authority == null) {
7615                                p.info.authority = names[j];
7616                            } else {
7617                                p.info.authority = p.info.authority + ";" + names[j];
7618                            }
7619                            if (DEBUG_PACKAGE_SCANNING) {
7620                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7621                                    Log.d(TAG, "Registered content provider: " + names[j]
7622                                            + ", className = " + p.info.name + ", isSyncable = "
7623                                            + p.info.isSyncable);
7624                            }
7625                        } else {
7626                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7627                            Slog.w(TAG, "Skipping provider name " + names[j] +
7628                                    " (in package " + pkg.applicationInfo.packageName +
7629                                    "): name already used by "
7630                                    + ((other != null && other.getComponentName() != null)
7631                                            ? other.getComponentName().getPackageName() : "?"));
7632                        }
7633                    }
7634                }
7635                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7636                    if (r == null) {
7637                        r = new StringBuilder(256);
7638                    } else {
7639                        r.append(' ');
7640                    }
7641                    r.append(p.info.name);
7642                }
7643            }
7644            if (r != null) {
7645                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7646            }
7647
7648            N = pkg.services.size();
7649            r = null;
7650            for (i=0; i<N; i++) {
7651                PackageParser.Service s = pkg.services.get(i);
7652                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7653                        s.info.processName, pkg.applicationInfo.uid);
7654                mServices.addService(s);
7655                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7656                    if (r == null) {
7657                        r = new StringBuilder(256);
7658                    } else {
7659                        r.append(' ');
7660                    }
7661                    r.append(s.info.name);
7662                }
7663            }
7664            if (r != null) {
7665                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7666            }
7667
7668            N = pkg.receivers.size();
7669            r = null;
7670            for (i=0; i<N; i++) {
7671                PackageParser.Activity a = pkg.receivers.get(i);
7672                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7673                        a.info.processName, pkg.applicationInfo.uid);
7674                mReceivers.addActivity(a, "receiver");
7675                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7676                    if (r == null) {
7677                        r = new StringBuilder(256);
7678                    } else {
7679                        r.append(' ');
7680                    }
7681                    r.append(a.info.name);
7682                }
7683            }
7684            if (r != null) {
7685                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7686            }
7687
7688            N = pkg.activities.size();
7689            r = null;
7690            for (i=0; i<N; i++) {
7691                PackageParser.Activity a = pkg.activities.get(i);
7692                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7693                        a.info.processName, pkg.applicationInfo.uid);
7694                mActivities.addActivity(a, "activity");
7695                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7696                    if (r == null) {
7697                        r = new StringBuilder(256);
7698                    } else {
7699                        r.append(' ');
7700                    }
7701                    r.append(a.info.name);
7702                }
7703            }
7704            if (r != null) {
7705                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7706            }
7707
7708            N = pkg.permissionGroups.size();
7709            r = null;
7710            for (i=0; i<N; i++) {
7711                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7712                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7713                if (cur == null) {
7714                    mPermissionGroups.put(pg.info.name, pg);
7715                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7716                        if (r == null) {
7717                            r = new StringBuilder(256);
7718                        } else {
7719                            r.append(' ');
7720                        }
7721                        r.append(pg.info.name);
7722                    }
7723                } else {
7724                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7725                            + pg.info.packageName + " ignored: original from "
7726                            + cur.info.packageName);
7727                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7728                        if (r == null) {
7729                            r = new StringBuilder(256);
7730                        } else {
7731                            r.append(' ');
7732                        }
7733                        r.append("DUP:");
7734                        r.append(pg.info.name);
7735                    }
7736                }
7737            }
7738            if (r != null) {
7739                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7740            }
7741
7742            N = pkg.permissions.size();
7743            r = null;
7744            for (i=0; i<N; i++) {
7745                PackageParser.Permission p = pkg.permissions.get(i);
7746
7747                // Assume by default that we did not install this permission into the system.
7748                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7749
7750                // Now that permission groups have a special meaning, we ignore permission
7751                // groups for legacy apps to prevent unexpected behavior. In particular,
7752                // permissions for one app being granted to someone just becuase they happen
7753                // to be in a group defined by another app (before this had no implications).
7754                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7755                    p.group = mPermissionGroups.get(p.info.group);
7756                    // Warn for a permission in an unknown group.
7757                    if (p.info.group != null && p.group == null) {
7758                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7759                                + p.info.packageName + " in an unknown group " + p.info.group);
7760                    }
7761                }
7762
7763                ArrayMap<String, BasePermission> permissionMap =
7764                        p.tree ? mSettings.mPermissionTrees
7765                                : mSettings.mPermissions;
7766                BasePermission bp = permissionMap.get(p.info.name);
7767
7768                // Allow system apps to redefine non-system permissions
7769                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7770                    final boolean currentOwnerIsSystem = (bp.perm != null
7771                            && isSystemApp(bp.perm.owner));
7772                    if (isSystemApp(p.owner)) {
7773                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7774                            // It's a built-in permission and no owner, take ownership now
7775                            bp.packageSetting = pkgSetting;
7776                            bp.perm = p;
7777                            bp.uid = pkg.applicationInfo.uid;
7778                            bp.sourcePackage = p.info.packageName;
7779                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7780                        } else if (!currentOwnerIsSystem) {
7781                            String msg = "New decl " + p.owner + " of permission  "
7782                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7783                            reportSettingsProblem(Log.WARN, msg);
7784                            bp = null;
7785                        }
7786                    }
7787                }
7788
7789                if (bp == null) {
7790                    bp = new BasePermission(p.info.name, p.info.packageName,
7791                            BasePermission.TYPE_NORMAL);
7792                    permissionMap.put(p.info.name, bp);
7793                }
7794
7795                if (bp.perm == null) {
7796                    if (bp.sourcePackage == null
7797                            || bp.sourcePackage.equals(p.info.packageName)) {
7798                        BasePermission tree = findPermissionTreeLP(p.info.name);
7799                        if (tree == null
7800                                || tree.sourcePackage.equals(p.info.packageName)) {
7801                            bp.packageSetting = pkgSetting;
7802                            bp.perm = p;
7803                            bp.uid = pkg.applicationInfo.uid;
7804                            bp.sourcePackage = p.info.packageName;
7805                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7806                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7807                                if (r == null) {
7808                                    r = new StringBuilder(256);
7809                                } else {
7810                                    r.append(' ');
7811                                }
7812                                r.append(p.info.name);
7813                            }
7814                        } else {
7815                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7816                                    + p.info.packageName + " ignored: base tree "
7817                                    + tree.name + " is from package "
7818                                    + tree.sourcePackage);
7819                        }
7820                    } else {
7821                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7822                                + p.info.packageName + " ignored: original from "
7823                                + bp.sourcePackage);
7824                    }
7825                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7826                    if (r == null) {
7827                        r = new StringBuilder(256);
7828                    } else {
7829                        r.append(' ');
7830                    }
7831                    r.append("DUP:");
7832                    r.append(p.info.name);
7833                }
7834                if (bp.perm == p) {
7835                    bp.protectionLevel = p.info.protectionLevel;
7836                }
7837            }
7838
7839            if (r != null) {
7840                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7841            }
7842
7843            N = pkg.instrumentation.size();
7844            r = null;
7845            for (i=0; i<N; i++) {
7846                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7847                a.info.packageName = pkg.applicationInfo.packageName;
7848                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7849                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7850                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7851                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7852                a.info.dataDir = pkg.applicationInfo.dataDir;
7853                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7854                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7855
7856                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7857                // need other information about the application, like the ABI and what not ?
7858                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7859                mInstrumentation.put(a.getComponentName(), a);
7860                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7861                    if (r == null) {
7862                        r = new StringBuilder(256);
7863                    } else {
7864                        r.append(' ');
7865                    }
7866                    r.append(a.info.name);
7867                }
7868            }
7869            if (r != null) {
7870                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7871            }
7872
7873            if (pkg.protectedBroadcasts != null) {
7874                N = pkg.protectedBroadcasts.size();
7875                for (i=0; i<N; i++) {
7876                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7877                }
7878            }
7879
7880            pkgSetting.setTimeStamp(scanFileTime);
7881
7882            // Create idmap files for pairs of (packages, overlay packages).
7883            // Note: "android", ie framework-res.apk, is handled by native layers.
7884            if (pkg.mOverlayTarget != null) {
7885                // This is an overlay package.
7886                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7887                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7888                        mOverlays.put(pkg.mOverlayTarget,
7889                                new ArrayMap<String, PackageParser.Package>());
7890                    }
7891                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7892                    map.put(pkg.packageName, pkg);
7893                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7894                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7895                        createIdmapFailed = true;
7896                    }
7897                }
7898            } else if (mOverlays.containsKey(pkg.packageName) &&
7899                    !pkg.packageName.equals("android")) {
7900                // This is a regular package, with one or more known overlay packages.
7901                createIdmapsForPackageLI(pkg);
7902            }
7903        }
7904
7905        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7906
7907        if (createIdmapFailed) {
7908            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7909                    "scanPackageLI failed to createIdmap");
7910        }
7911        return pkg;
7912    }
7913
7914    /**
7915     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7916     * is derived purely on the basis of the contents of {@code scanFile} and
7917     * {@code cpuAbiOverride}.
7918     *
7919     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7920     */
7921    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7922                                 String cpuAbiOverride, boolean extractLibs)
7923            throws PackageManagerException {
7924        // TODO: We can probably be smarter about this stuff. For installed apps,
7925        // we can calculate this information at install time once and for all. For
7926        // system apps, we can probably assume that this information doesn't change
7927        // after the first boot scan. As things stand, we do lots of unnecessary work.
7928
7929        // Give ourselves some initial paths; we'll come back for another
7930        // pass once we've determined ABI below.
7931        setNativeLibraryPaths(pkg);
7932
7933        // We would never need to extract libs for forward-locked and external packages,
7934        // since the container service will do it for us. We shouldn't attempt to
7935        // extract libs from system app when it was not updated.
7936        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7937                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7938            extractLibs = false;
7939        }
7940
7941        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7942        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7943
7944        NativeLibraryHelper.Handle handle = null;
7945        try {
7946            handle = NativeLibraryHelper.Handle.create(pkg);
7947            // TODO(multiArch): This can be null for apps that didn't go through the
7948            // usual installation process. We can calculate it again, like we
7949            // do during install time.
7950            //
7951            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7952            // unnecessary.
7953            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7954
7955            // Null out the abis so that they can be recalculated.
7956            pkg.applicationInfo.primaryCpuAbi = null;
7957            pkg.applicationInfo.secondaryCpuAbi = null;
7958            if (isMultiArch(pkg.applicationInfo)) {
7959                // Warn if we've set an abiOverride for multi-lib packages..
7960                // By definition, we need to copy both 32 and 64 bit libraries for
7961                // such packages.
7962                if (pkg.cpuAbiOverride != null
7963                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7964                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7965                }
7966
7967                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7968                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7969                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7970                    if (extractLibs) {
7971                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7972                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7973                                useIsaSpecificSubdirs);
7974                    } else {
7975                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7976                    }
7977                }
7978
7979                maybeThrowExceptionForMultiArchCopy(
7980                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7981
7982                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7983                    if (extractLibs) {
7984                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7985                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7986                                useIsaSpecificSubdirs);
7987                    } else {
7988                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7989                    }
7990                }
7991
7992                maybeThrowExceptionForMultiArchCopy(
7993                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7994
7995                if (abi64 >= 0) {
7996                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7997                }
7998
7999                if (abi32 >= 0) {
8000                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8001                    if (abi64 >= 0) {
8002                        pkg.applicationInfo.secondaryCpuAbi = abi;
8003                    } else {
8004                        pkg.applicationInfo.primaryCpuAbi = abi;
8005                    }
8006                }
8007            } else {
8008                String[] abiList = (cpuAbiOverride != null) ?
8009                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8010
8011                // Enable gross and lame hacks for apps that are built with old
8012                // SDK tools. We must scan their APKs for renderscript bitcode and
8013                // not launch them if it's present. Don't bother checking on devices
8014                // that don't have 64 bit support.
8015                boolean needsRenderScriptOverride = false;
8016                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8017                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8018                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8019                    needsRenderScriptOverride = true;
8020                }
8021
8022                final int copyRet;
8023                if (extractLibs) {
8024                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8025                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8026                } else {
8027                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8028                }
8029
8030                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8031                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8032                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8033                }
8034
8035                if (copyRet >= 0) {
8036                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8037                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8038                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8039                } else if (needsRenderScriptOverride) {
8040                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8041                }
8042            }
8043        } catch (IOException ioe) {
8044            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8045        } finally {
8046            IoUtils.closeQuietly(handle);
8047        }
8048
8049        // Now that we've calculated the ABIs and determined if it's an internal app,
8050        // we will go ahead and populate the nativeLibraryPath.
8051        setNativeLibraryPaths(pkg);
8052    }
8053
8054    /**
8055     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8056     * i.e, so that all packages can be run inside a single process if required.
8057     *
8058     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8059     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8060     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8061     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8062     * updating a package that belongs to a shared user.
8063     *
8064     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8065     * adds unnecessary complexity.
8066     */
8067    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8068            PackageParser.Package scannedPackage, boolean bootComplete) {
8069        String requiredInstructionSet = null;
8070        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8071            requiredInstructionSet = VMRuntime.getInstructionSet(
8072                     scannedPackage.applicationInfo.primaryCpuAbi);
8073        }
8074
8075        PackageSetting requirer = null;
8076        for (PackageSetting ps : packagesForUser) {
8077            // If packagesForUser contains scannedPackage, we skip it. This will happen
8078            // when scannedPackage is an update of an existing package. Without this check,
8079            // we will never be able to change the ABI of any package belonging to a shared
8080            // user, even if it's compatible with other packages.
8081            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8082                if (ps.primaryCpuAbiString == null) {
8083                    continue;
8084                }
8085
8086                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8087                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8088                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8089                    // this but there's not much we can do.
8090                    String errorMessage = "Instruction set mismatch, "
8091                            + ((requirer == null) ? "[caller]" : requirer)
8092                            + " requires " + requiredInstructionSet + " whereas " + ps
8093                            + " requires " + instructionSet;
8094                    Slog.w(TAG, errorMessage);
8095                }
8096
8097                if (requiredInstructionSet == null) {
8098                    requiredInstructionSet = instructionSet;
8099                    requirer = ps;
8100                }
8101            }
8102        }
8103
8104        if (requiredInstructionSet != null) {
8105            String adjustedAbi;
8106            if (requirer != null) {
8107                // requirer != null implies that either scannedPackage was null or that scannedPackage
8108                // did not require an ABI, in which case we have to adjust scannedPackage to match
8109                // the ABI of the set (which is the same as requirer's ABI)
8110                adjustedAbi = requirer.primaryCpuAbiString;
8111                if (scannedPackage != null) {
8112                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8113                }
8114            } else {
8115                // requirer == null implies that we're updating all ABIs in the set to
8116                // match scannedPackage.
8117                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8118            }
8119
8120            for (PackageSetting ps : packagesForUser) {
8121                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8122                    if (ps.primaryCpuAbiString != null) {
8123                        continue;
8124                    }
8125
8126                    ps.primaryCpuAbiString = adjustedAbi;
8127                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8128                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8129                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8130                        mInstaller.rmdex(ps.codePathString,
8131                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8132                    }
8133                }
8134            }
8135        }
8136    }
8137
8138    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8139        synchronized (mPackages) {
8140            mResolverReplaced = true;
8141            // Set up information for custom user intent resolution activity.
8142            mResolveActivity.applicationInfo = pkg.applicationInfo;
8143            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8144            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8145            mResolveActivity.processName = pkg.applicationInfo.packageName;
8146            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8147            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8148                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8149            mResolveActivity.theme = 0;
8150            mResolveActivity.exported = true;
8151            mResolveActivity.enabled = true;
8152            mResolveInfo.activityInfo = mResolveActivity;
8153            mResolveInfo.priority = 0;
8154            mResolveInfo.preferredOrder = 0;
8155            mResolveInfo.match = 0;
8156            mResolveComponentName = mCustomResolverComponentName;
8157            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8158                    mResolveComponentName);
8159        }
8160    }
8161
8162    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8163        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8164
8165        // Set up information for ephemeral installer activity
8166        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8167        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8168        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8169        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8170        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8171        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8172                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8173        mEphemeralInstallerActivity.theme = 0;
8174        mEphemeralInstallerActivity.exported = true;
8175        mEphemeralInstallerActivity.enabled = true;
8176        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8177        mEphemeralInstallerInfo.priority = 0;
8178        mEphemeralInstallerInfo.preferredOrder = 0;
8179        mEphemeralInstallerInfo.match = 0;
8180
8181        if (DEBUG_EPHEMERAL) {
8182            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8183        }
8184    }
8185
8186    private static String calculateBundledApkRoot(final String codePathString) {
8187        final File codePath = new File(codePathString);
8188        final File codeRoot;
8189        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8190            codeRoot = Environment.getRootDirectory();
8191        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8192            codeRoot = Environment.getOemDirectory();
8193        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8194            codeRoot = Environment.getVendorDirectory();
8195        } else {
8196            // Unrecognized code path; take its top real segment as the apk root:
8197            // e.g. /something/app/blah.apk => /something
8198            try {
8199                File f = codePath.getCanonicalFile();
8200                File parent = f.getParentFile();    // non-null because codePath is a file
8201                File tmp;
8202                while ((tmp = parent.getParentFile()) != null) {
8203                    f = parent;
8204                    parent = tmp;
8205                }
8206                codeRoot = f;
8207                Slog.w(TAG, "Unrecognized code path "
8208                        + codePath + " - using " + codeRoot);
8209            } catch (IOException e) {
8210                // Can't canonicalize the code path -- shenanigans?
8211                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8212                return Environment.getRootDirectory().getPath();
8213            }
8214        }
8215        return codeRoot.getPath();
8216    }
8217
8218    /**
8219     * Derive and set the location of native libraries for the given package,
8220     * which varies depending on where and how the package was installed.
8221     */
8222    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8223        final ApplicationInfo info = pkg.applicationInfo;
8224        final String codePath = pkg.codePath;
8225        final File codeFile = new File(codePath);
8226        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8227        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8228
8229        info.nativeLibraryRootDir = null;
8230        info.nativeLibraryRootRequiresIsa = false;
8231        info.nativeLibraryDir = null;
8232        info.secondaryNativeLibraryDir = null;
8233
8234        if (isApkFile(codeFile)) {
8235            // Monolithic install
8236            if (bundledApp) {
8237                // If "/system/lib64/apkname" exists, assume that is the per-package
8238                // native library directory to use; otherwise use "/system/lib/apkname".
8239                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8240                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8241                        getPrimaryInstructionSet(info));
8242
8243                // This is a bundled system app so choose the path based on the ABI.
8244                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8245                // is just the default path.
8246                final String apkName = deriveCodePathName(codePath);
8247                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8248                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8249                        apkName).getAbsolutePath();
8250
8251                if (info.secondaryCpuAbi != null) {
8252                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8253                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8254                            secondaryLibDir, apkName).getAbsolutePath();
8255                }
8256            } else if (asecApp) {
8257                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8258                        .getAbsolutePath();
8259            } else {
8260                final String apkName = deriveCodePathName(codePath);
8261                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8262                        .getAbsolutePath();
8263            }
8264
8265            info.nativeLibraryRootRequiresIsa = false;
8266            info.nativeLibraryDir = info.nativeLibraryRootDir;
8267        } else {
8268            // Cluster install
8269            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8270            info.nativeLibraryRootRequiresIsa = true;
8271
8272            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8273                    getPrimaryInstructionSet(info)).getAbsolutePath();
8274
8275            if (info.secondaryCpuAbi != null) {
8276                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8277                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8278            }
8279        }
8280    }
8281
8282    /**
8283     * Calculate the abis and roots for a bundled app. These can uniquely
8284     * be determined from the contents of the system partition, i.e whether
8285     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8286     * of this information, and instead assume that the system was built
8287     * sensibly.
8288     */
8289    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8290                                           PackageSetting pkgSetting) {
8291        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8292
8293        // If "/system/lib64/apkname" exists, assume that is the per-package
8294        // native library directory to use; otherwise use "/system/lib/apkname".
8295        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8296        setBundledAppAbi(pkg, apkRoot, apkName);
8297        // pkgSetting might be null during rescan following uninstall of updates
8298        // to a bundled app, so accommodate that possibility.  The settings in
8299        // that case will be established later from the parsed package.
8300        //
8301        // If the settings aren't null, sync them up with what we've just derived.
8302        // note that apkRoot isn't stored in the package settings.
8303        if (pkgSetting != null) {
8304            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8305            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8306        }
8307    }
8308
8309    /**
8310     * Deduces the ABI of a bundled app and sets the relevant fields on the
8311     * parsed pkg object.
8312     *
8313     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8314     *        under which system libraries are installed.
8315     * @param apkName the name of the installed package.
8316     */
8317    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8318        final File codeFile = new File(pkg.codePath);
8319
8320        final boolean has64BitLibs;
8321        final boolean has32BitLibs;
8322        if (isApkFile(codeFile)) {
8323            // Monolithic install
8324            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8325            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8326        } else {
8327            // Cluster install
8328            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8329            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8330                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8331                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8332                has64BitLibs = (new File(rootDir, isa)).exists();
8333            } else {
8334                has64BitLibs = false;
8335            }
8336            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8337                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8338                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8339                has32BitLibs = (new File(rootDir, isa)).exists();
8340            } else {
8341                has32BitLibs = false;
8342            }
8343        }
8344
8345        if (has64BitLibs && !has32BitLibs) {
8346            // The package has 64 bit libs, but not 32 bit libs. Its primary
8347            // ABI should be 64 bit. We can safely assume here that the bundled
8348            // native libraries correspond to the most preferred ABI in the list.
8349
8350            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8351            pkg.applicationInfo.secondaryCpuAbi = null;
8352        } else if (has32BitLibs && !has64BitLibs) {
8353            // The package has 32 bit libs but not 64 bit libs. Its primary
8354            // ABI should be 32 bit.
8355
8356            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8357            pkg.applicationInfo.secondaryCpuAbi = null;
8358        } else if (has32BitLibs && has64BitLibs) {
8359            // The application has both 64 and 32 bit bundled libraries. We check
8360            // here that the app declares multiArch support, and warn if it doesn't.
8361            //
8362            // We will be lenient here and record both ABIs. The primary will be the
8363            // ABI that's higher on the list, i.e, a device that's configured to prefer
8364            // 64 bit apps will see a 64 bit primary ABI,
8365
8366            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8367                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8368            }
8369
8370            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8371                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8372                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8373            } else {
8374                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8375                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8376            }
8377        } else {
8378            pkg.applicationInfo.primaryCpuAbi = null;
8379            pkg.applicationInfo.secondaryCpuAbi = null;
8380        }
8381    }
8382
8383    private void killApplication(String pkgName, int appId, String reason) {
8384        // Request the ActivityManager to kill the process(only for existing packages)
8385        // so that we do not end up in a confused state while the user is still using the older
8386        // version of the application while the new one gets installed.
8387        IActivityManager am = ActivityManagerNative.getDefault();
8388        if (am != null) {
8389            try {
8390                am.killApplicationWithAppId(pkgName, appId, reason);
8391            } catch (RemoteException e) {
8392            }
8393        }
8394    }
8395
8396    void removePackageLI(PackageSetting ps, boolean chatty) {
8397        if (DEBUG_INSTALL) {
8398            if (chatty)
8399                Log.d(TAG, "Removing package " + ps.name);
8400        }
8401
8402        // writer
8403        synchronized (mPackages) {
8404            mPackages.remove(ps.name);
8405            final PackageParser.Package pkg = ps.pkg;
8406            if (pkg != null) {
8407                cleanPackageDataStructuresLILPw(pkg, chatty);
8408            }
8409        }
8410    }
8411
8412    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8413        if (DEBUG_INSTALL) {
8414            if (chatty)
8415                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8416        }
8417
8418        // writer
8419        synchronized (mPackages) {
8420            mPackages.remove(pkg.applicationInfo.packageName);
8421            cleanPackageDataStructuresLILPw(pkg, chatty);
8422        }
8423    }
8424
8425    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8426        int N = pkg.providers.size();
8427        StringBuilder r = null;
8428        int i;
8429        for (i=0; i<N; i++) {
8430            PackageParser.Provider p = pkg.providers.get(i);
8431            mProviders.removeProvider(p);
8432            if (p.info.authority == null) {
8433
8434                /* There was another ContentProvider with this authority when
8435                 * this app was installed so this authority is null,
8436                 * Ignore it as we don't have to unregister the provider.
8437                 */
8438                continue;
8439            }
8440            String names[] = p.info.authority.split(";");
8441            for (int j = 0; j < names.length; j++) {
8442                if (mProvidersByAuthority.get(names[j]) == p) {
8443                    mProvidersByAuthority.remove(names[j]);
8444                    if (DEBUG_REMOVE) {
8445                        if (chatty)
8446                            Log.d(TAG, "Unregistered content provider: " + names[j]
8447                                    + ", className = " + p.info.name + ", isSyncable = "
8448                                    + p.info.isSyncable);
8449                    }
8450                }
8451            }
8452            if (DEBUG_REMOVE && chatty) {
8453                if (r == null) {
8454                    r = new StringBuilder(256);
8455                } else {
8456                    r.append(' ');
8457                }
8458                r.append(p.info.name);
8459            }
8460        }
8461        if (r != null) {
8462            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8463        }
8464
8465        N = pkg.services.size();
8466        r = null;
8467        for (i=0; i<N; i++) {
8468            PackageParser.Service s = pkg.services.get(i);
8469            mServices.removeService(s);
8470            if (chatty) {
8471                if (r == null) {
8472                    r = new StringBuilder(256);
8473                } else {
8474                    r.append(' ');
8475                }
8476                r.append(s.info.name);
8477            }
8478        }
8479        if (r != null) {
8480            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8481        }
8482
8483        N = pkg.receivers.size();
8484        r = null;
8485        for (i=0; i<N; i++) {
8486            PackageParser.Activity a = pkg.receivers.get(i);
8487            mReceivers.removeActivity(a, "receiver");
8488            if (DEBUG_REMOVE && chatty) {
8489                if (r == null) {
8490                    r = new StringBuilder(256);
8491                } else {
8492                    r.append(' ');
8493                }
8494                r.append(a.info.name);
8495            }
8496        }
8497        if (r != null) {
8498            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8499        }
8500
8501        N = pkg.activities.size();
8502        r = null;
8503        for (i=0; i<N; i++) {
8504            PackageParser.Activity a = pkg.activities.get(i);
8505            mActivities.removeActivity(a, "activity");
8506            if (DEBUG_REMOVE && chatty) {
8507                if (r == null) {
8508                    r = new StringBuilder(256);
8509                } else {
8510                    r.append(' ');
8511                }
8512                r.append(a.info.name);
8513            }
8514        }
8515        if (r != null) {
8516            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8517        }
8518
8519        N = pkg.permissions.size();
8520        r = null;
8521        for (i=0; i<N; i++) {
8522            PackageParser.Permission p = pkg.permissions.get(i);
8523            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8524            if (bp == null) {
8525                bp = mSettings.mPermissionTrees.get(p.info.name);
8526            }
8527            if (bp != null && bp.perm == p) {
8528                bp.perm = null;
8529                if (DEBUG_REMOVE && chatty) {
8530                    if (r == null) {
8531                        r = new StringBuilder(256);
8532                    } else {
8533                        r.append(' ');
8534                    }
8535                    r.append(p.info.name);
8536                }
8537            }
8538            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8539                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8540                if (appOpPkgs != null) {
8541                    appOpPkgs.remove(pkg.packageName);
8542                }
8543            }
8544        }
8545        if (r != null) {
8546            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8547        }
8548
8549        N = pkg.requestedPermissions.size();
8550        r = null;
8551        for (i=0; i<N; i++) {
8552            String perm = pkg.requestedPermissions.get(i);
8553            BasePermission bp = mSettings.mPermissions.get(perm);
8554            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8555                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8556                if (appOpPkgs != null) {
8557                    appOpPkgs.remove(pkg.packageName);
8558                    if (appOpPkgs.isEmpty()) {
8559                        mAppOpPermissionPackages.remove(perm);
8560                    }
8561                }
8562            }
8563        }
8564        if (r != null) {
8565            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8566        }
8567
8568        N = pkg.instrumentation.size();
8569        r = null;
8570        for (i=0; i<N; i++) {
8571            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8572            mInstrumentation.remove(a.getComponentName());
8573            if (DEBUG_REMOVE && chatty) {
8574                if (r == null) {
8575                    r = new StringBuilder(256);
8576                } else {
8577                    r.append(' ');
8578                }
8579                r.append(a.info.name);
8580            }
8581        }
8582        if (r != null) {
8583            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8584        }
8585
8586        r = null;
8587        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8588            // Only system apps can hold shared libraries.
8589            if (pkg.libraryNames != null) {
8590                for (i=0; i<pkg.libraryNames.size(); i++) {
8591                    String name = pkg.libraryNames.get(i);
8592                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8593                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8594                        mSharedLibraries.remove(name);
8595                        if (DEBUG_REMOVE && chatty) {
8596                            if (r == null) {
8597                                r = new StringBuilder(256);
8598                            } else {
8599                                r.append(' ');
8600                            }
8601                            r.append(name);
8602                        }
8603                    }
8604                }
8605            }
8606        }
8607        if (r != null) {
8608            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8609        }
8610    }
8611
8612    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8613        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8614            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8615                return true;
8616            }
8617        }
8618        return false;
8619    }
8620
8621    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8622    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8623    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8624
8625    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8626            int flags) {
8627        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8628        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8629    }
8630
8631    private void updatePermissionsLPw(String changingPkg,
8632            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8633        // Make sure there are no dangling permission trees.
8634        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8635        while (it.hasNext()) {
8636            final BasePermission bp = it.next();
8637            if (bp.packageSetting == null) {
8638                // We may not yet have parsed the package, so just see if
8639                // we still know about its settings.
8640                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8641            }
8642            if (bp.packageSetting == null) {
8643                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8644                        + " from package " + bp.sourcePackage);
8645                it.remove();
8646            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8647                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8648                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8649                            + " from package " + bp.sourcePackage);
8650                    flags |= UPDATE_PERMISSIONS_ALL;
8651                    it.remove();
8652                }
8653            }
8654        }
8655
8656        // Make sure all dynamic permissions have been assigned to a package,
8657        // and make sure there are no dangling permissions.
8658        it = mSettings.mPermissions.values().iterator();
8659        while (it.hasNext()) {
8660            final BasePermission bp = it.next();
8661            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8662                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8663                        + bp.name + " pkg=" + bp.sourcePackage
8664                        + " info=" + bp.pendingInfo);
8665                if (bp.packageSetting == null && bp.pendingInfo != null) {
8666                    final BasePermission tree = findPermissionTreeLP(bp.name);
8667                    if (tree != null && tree.perm != null) {
8668                        bp.packageSetting = tree.packageSetting;
8669                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8670                                new PermissionInfo(bp.pendingInfo));
8671                        bp.perm.info.packageName = tree.perm.info.packageName;
8672                        bp.perm.info.name = bp.name;
8673                        bp.uid = tree.uid;
8674                    }
8675                }
8676            }
8677            if (bp.packageSetting == null) {
8678                // We may not yet have parsed the package, so just see if
8679                // we still know about its settings.
8680                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8681            }
8682            if (bp.packageSetting == null) {
8683                Slog.w(TAG, "Removing dangling permission: " + bp.name
8684                        + " from package " + bp.sourcePackage);
8685                it.remove();
8686            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8687                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8688                    Slog.i(TAG, "Removing old permission: " + bp.name
8689                            + " from package " + bp.sourcePackage);
8690                    flags |= UPDATE_PERMISSIONS_ALL;
8691                    it.remove();
8692                }
8693            }
8694        }
8695
8696        // Now update the permissions for all packages, in particular
8697        // replace the granted permissions of the system packages.
8698        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8699            for (PackageParser.Package pkg : mPackages.values()) {
8700                if (pkg != pkgInfo) {
8701                    // Only replace for packages on requested volume
8702                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8703                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8704                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8705                    grantPermissionsLPw(pkg, replace, changingPkg);
8706                }
8707            }
8708        }
8709
8710        if (pkgInfo != null) {
8711            // Only replace for packages on requested volume
8712            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8713            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8714                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8715            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8716        }
8717    }
8718
8719    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8720            String packageOfInterest) {
8721        // IMPORTANT: There are two types of permissions: install and runtime.
8722        // Install time permissions are granted when the app is installed to
8723        // all device users and users added in the future. Runtime permissions
8724        // are granted at runtime explicitly to specific users. Normal and signature
8725        // protected permissions are install time permissions. Dangerous permissions
8726        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8727        // otherwise they are runtime permissions. This function does not manage
8728        // runtime permissions except for the case an app targeting Lollipop MR1
8729        // being upgraded to target a newer SDK, in which case dangerous permissions
8730        // are transformed from install time to runtime ones.
8731
8732        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8733        if (ps == null) {
8734            return;
8735        }
8736
8737        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8738
8739        PermissionsState permissionsState = ps.getPermissionsState();
8740        PermissionsState origPermissions = permissionsState;
8741
8742        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8743
8744        boolean runtimePermissionsRevoked = false;
8745        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8746
8747        boolean changedInstallPermission = false;
8748
8749        if (replace) {
8750            ps.installPermissionsFixed = false;
8751            if (!ps.isSharedUser()) {
8752                origPermissions = new PermissionsState(permissionsState);
8753                permissionsState.reset();
8754            } else {
8755                // We need to know only about runtime permission changes since the
8756                // calling code always writes the install permissions state but
8757                // the runtime ones are written only if changed. The only cases of
8758                // changed runtime permissions here are promotion of an install to
8759                // runtime and revocation of a runtime from a shared user.
8760                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8761                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8762                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8763                    runtimePermissionsRevoked = true;
8764                }
8765            }
8766        }
8767
8768        permissionsState.setGlobalGids(mGlobalGids);
8769
8770        final int N = pkg.requestedPermissions.size();
8771        for (int i=0; i<N; i++) {
8772            final String name = pkg.requestedPermissions.get(i);
8773            final BasePermission bp = mSettings.mPermissions.get(name);
8774
8775            if (DEBUG_INSTALL) {
8776                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8777            }
8778
8779            if (bp == null || bp.packageSetting == null) {
8780                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8781                    Slog.w(TAG, "Unknown permission " + name
8782                            + " in package " + pkg.packageName);
8783                }
8784                continue;
8785            }
8786
8787            final String perm = bp.name;
8788            boolean allowedSig = false;
8789            int grant = GRANT_DENIED;
8790
8791            // Keep track of app op permissions.
8792            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8793                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8794                if (pkgs == null) {
8795                    pkgs = new ArraySet<>();
8796                    mAppOpPermissionPackages.put(bp.name, pkgs);
8797                }
8798                pkgs.add(pkg.packageName);
8799            }
8800
8801            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8802            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8803                    >= Build.VERSION_CODES.M;
8804            switch (level) {
8805                case PermissionInfo.PROTECTION_NORMAL: {
8806                    // For all apps normal permissions are install time ones.
8807                    grant = GRANT_INSTALL;
8808                } break;
8809
8810                case PermissionInfo.PROTECTION_DANGEROUS: {
8811                    // If a permission review is required for legacy apps we represent
8812                    // their permissions as always granted runtime ones since we need
8813                    // to keep the review required permission flag per user while an
8814                    // install permission's state is shared across all users.
8815                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8816                        // For legacy apps dangerous permissions are install time ones.
8817                        grant = GRANT_INSTALL;
8818                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8819                        // For legacy apps that became modern, install becomes runtime.
8820                        grant = GRANT_UPGRADE;
8821                    } else if (mPromoteSystemApps
8822                            && isSystemApp(ps)
8823                            && mExistingSystemPackages.contains(ps.name)) {
8824                        // For legacy system apps, install becomes runtime.
8825                        // We cannot check hasInstallPermission() for system apps since those
8826                        // permissions were granted implicitly and not persisted pre-M.
8827                        grant = GRANT_UPGRADE;
8828                    } else {
8829                        // For modern apps keep runtime permissions unchanged.
8830                        grant = GRANT_RUNTIME;
8831                    }
8832                } break;
8833
8834                case PermissionInfo.PROTECTION_SIGNATURE: {
8835                    // For all apps signature permissions are install time ones.
8836                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8837                    if (allowedSig) {
8838                        grant = GRANT_INSTALL;
8839                    }
8840                } break;
8841            }
8842
8843            if (DEBUG_INSTALL) {
8844                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8845            }
8846
8847            if (grant != GRANT_DENIED) {
8848                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8849                    // If this is an existing, non-system package, then
8850                    // we can't add any new permissions to it.
8851                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8852                        // Except...  if this is a permission that was added
8853                        // to the platform (note: need to only do this when
8854                        // updating the platform).
8855                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8856                            grant = GRANT_DENIED;
8857                        }
8858                    }
8859                }
8860
8861                switch (grant) {
8862                    case GRANT_INSTALL: {
8863                        // Revoke this as runtime permission to handle the case of
8864                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8865                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8866                            if (origPermissions.getRuntimePermissionState(
8867                                    bp.name, userId) != null) {
8868                                // Revoke the runtime permission and clear the flags.
8869                                origPermissions.revokeRuntimePermission(bp, userId);
8870                                origPermissions.updatePermissionFlags(bp, userId,
8871                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8872                                // If we revoked a permission permission, we have to write.
8873                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8874                                        changedRuntimePermissionUserIds, userId);
8875                            }
8876                        }
8877                        // Grant an install permission.
8878                        if (permissionsState.grantInstallPermission(bp) !=
8879                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8880                            changedInstallPermission = true;
8881                        }
8882                    } break;
8883
8884                    case GRANT_RUNTIME: {
8885                        // Grant previously granted runtime permissions.
8886                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8887                            PermissionState permissionState = origPermissions
8888                                    .getRuntimePermissionState(bp.name, userId);
8889                            int flags = permissionState != null
8890                                    ? permissionState.getFlags() : 0;
8891                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8892                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8893                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8894                                    // If we cannot put the permission as it was, we have to write.
8895                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8896                                            changedRuntimePermissionUserIds, userId);
8897                                }
8898                                // If the app supports runtime permissions no need for a review.
8899                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8900                                        && appSupportsRuntimePermissions
8901                                        && (flags & PackageManager
8902                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8903                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8904                                    // Since we changed the flags, we have to write.
8905                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8906                                            changedRuntimePermissionUserIds, userId);
8907                                }
8908                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8909                                    && !appSupportsRuntimePermissions) {
8910                                // For legacy apps that need a permission review, every new
8911                                // runtime permission is granted but it is pending a review.
8912                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8913                                    permissionsState.grantRuntimePermission(bp, userId);
8914                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8915                                    // We changed the permission and flags, hence have to write.
8916                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8917                                            changedRuntimePermissionUserIds, userId);
8918                                }
8919                            }
8920                            // Propagate the permission flags.
8921                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8922                        }
8923                    } break;
8924
8925                    case GRANT_UPGRADE: {
8926                        // Grant runtime permissions for a previously held install permission.
8927                        PermissionState permissionState = origPermissions
8928                                .getInstallPermissionState(bp.name);
8929                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8930
8931                        if (origPermissions.revokeInstallPermission(bp)
8932                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8933                            // We will be transferring the permission flags, so clear them.
8934                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8935                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8936                            changedInstallPermission = true;
8937                        }
8938
8939                        // If the permission is not to be promoted to runtime we ignore it and
8940                        // also its other flags as they are not applicable to install permissions.
8941                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8942                            for (int userId : currentUserIds) {
8943                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8944                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8945                                    // Transfer the permission flags.
8946                                    permissionsState.updatePermissionFlags(bp, userId,
8947                                            flags, flags);
8948                                    // If we granted the permission, we have to write.
8949                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8950                                            changedRuntimePermissionUserIds, userId);
8951                                }
8952                            }
8953                        }
8954                    } break;
8955
8956                    default: {
8957                        if (packageOfInterest == null
8958                                || packageOfInterest.equals(pkg.packageName)) {
8959                            Slog.w(TAG, "Not granting permission " + perm
8960                                    + " to package " + pkg.packageName
8961                                    + " because it was previously installed without");
8962                        }
8963                    } break;
8964                }
8965            } else {
8966                if (permissionsState.revokeInstallPermission(bp) !=
8967                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8968                    // Also drop the permission flags.
8969                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8970                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8971                    changedInstallPermission = true;
8972                    Slog.i(TAG, "Un-granting permission " + perm
8973                            + " from package " + pkg.packageName
8974                            + " (protectionLevel=" + bp.protectionLevel
8975                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8976                            + ")");
8977                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8978                    // Don't print warning for app op permissions, since it is fine for them
8979                    // not to be granted, there is a UI for the user to decide.
8980                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8981                        Slog.w(TAG, "Not granting permission " + perm
8982                                + " to package " + pkg.packageName
8983                                + " (protectionLevel=" + bp.protectionLevel
8984                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8985                                + ")");
8986                    }
8987                }
8988            }
8989        }
8990
8991        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8992                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8993            // This is the first that we have heard about this package, so the
8994            // permissions we have now selected are fixed until explicitly
8995            // changed.
8996            ps.installPermissionsFixed = true;
8997        }
8998
8999        // Persist the runtime permissions state for users with changes. If permissions
9000        // were revoked because no app in the shared user declares them we have to
9001        // write synchronously to avoid losing runtime permissions state.
9002        for (int userId : changedRuntimePermissionUserIds) {
9003            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9004        }
9005
9006        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9007    }
9008
9009    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9010        boolean allowed = false;
9011        final int NP = PackageParser.NEW_PERMISSIONS.length;
9012        for (int ip=0; ip<NP; ip++) {
9013            final PackageParser.NewPermissionInfo npi
9014                    = PackageParser.NEW_PERMISSIONS[ip];
9015            if (npi.name.equals(perm)
9016                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9017                allowed = true;
9018                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9019                        + pkg.packageName);
9020                break;
9021            }
9022        }
9023        return allowed;
9024    }
9025
9026    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9027            BasePermission bp, PermissionsState origPermissions) {
9028        boolean allowed;
9029        allowed = (compareSignatures(
9030                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9031                        == PackageManager.SIGNATURE_MATCH)
9032                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9033                        == PackageManager.SIGNATURE_MATCH);
9034        if (!allowed && (bp.protectionLevel
9035                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9036            if (isSystemApp(pkg)) {
9037                // For updated system applications, a system permission
9038                // is granted only if it had been defined by the original application.
9039                if (pkg.isUpdatedSystemApp()) {
9040                    final PackageSetting sysPs = mSettings
9041                            .getDisabledSystemPkgLPr(pkg.packageName);
9042                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9043                        // If the original was granted this permission, we take
9044                        // that grant decision as read and propagate it to the
9045                        // update.
9046                        if (sysPs.isPrivileged()) {
9047                            allowed = true;
9048                        }
9049                    } else {
9050                        // The system apk may have been updated with an older
9051                        // version of the one on the data partition, but which
9052                        // granted a new system permission that it didn't have
9053                        // before.  In this case we do want to allow the app to
9054                        // now get the new permission if the ancestral apk is
9055                        // privileged to get it.
9056                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9057                            for (int j=0;
9058                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9059                                if (perm.equals(
9060                                        sysPs.pkg.requestedPermissions.get(j))) {
9061                                    allowed = true;
9062                                    break;
9063                                }
9064                            }
9065                        }
9066                    }
9067                } else {
9068                    allowed = isPrivilegedApp(pkg);
9069                }
9070            }
9071        }
9072        if (!allowed) {
9073            if (!allowed && (bp.protectionLevel
9074                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9075                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9076                // If this was a previously normal/dangerous permission that got moved
9077                // to a system permission as part of the runtime permission redesign, then
9078                // we still want to blindly grant it to old apps.
9079                allowed = true;
9080            }
9081            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9082                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9083                // If this permission is to be granted to the system installer and
9084                // this app is an installer, then it gets the permission.
9085                allowed = true;
9086            }
9087            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9088                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9089                // If this permission is to be granted to the system verifier and
9090                // this app is a verifier, then it gets the permission.
9091                allowed = true;
9092            }
9093            if (!allowed && (bp.protectionLevel
9094                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9095                    && isSystemApp(pkg)) {
9096                // Any pre-installed system app is allowed to get this permission.
9097                allowed = true;
9098            }
9099            if (!allowed && (bp.protectionLevel
9100                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9101                // For development permissions, a development permission
9102                // is granted only if it was already granted.
9103                allowed = origPermissions.hasInstallPermission(perm);
9104            }
9105        }
9106        return allowed;
9107    }
9108
9109    final class ActivityIntentResolver
9110            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9111        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9112                boolean defaultOnly, int userId) {
9113            if (!sUserManager.exists(userId)) return null;
9114            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9115            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9116        }
9117
9118        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9119                int userId) {
9120            if (!sUserManager.exists(userId)) return null;
9121            mFlags = flags;
9122            return super.queryIntent(intent, resolvedType,
9123                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9124        }
9125
9126        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9127                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9128            if (!sUserManager.exists(userId)) return null;
9129            if (packageActivities == null) {
9130                return null;
9131            }
9132            mFlags = flags;
9133            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9134            final int N = packageActivities.size();
9135            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9136                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9137
9138            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9139            for (int i = 0; i < N; ++i) {
9140                intentFilters = packageActivities.get(i).intents;
9141                if (intentFilters != null && intentFilters.size() > 0) {
9142                    PackageParser.ActivityIntentInfo[] array =
9143                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9144                    intentFilters.toArray(array);
9145                    listCut.add(array);
9146                }
9147            }
9148            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9149        }
9150
9151        public final void addActivity(PackageParser.Activity a, String type) {
9152            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9153            mActivities.put(a.getComponentName(), a);
9154            if (DEBUG_SHOW_INFO)
9155                Log.v(
9156                TAG, "  " + type + " " +
9157                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9158            if (DEBUG_SHOW_INFO)
9159                Log.v(TAG, "    Class=" + a.info.name);
9160            final int NI = a.intents.size();
9161            for (int j=0; j<NI; j++) {
9162                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9163                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9164                    intent.setPriority(0);
9165                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9166                            + a.className + " with priority > 0, forcing to 0");
9167                }
9168                if (DEBUG_SHOW_INFO) {
9169                    Log.v(TAG, "    IntentFilter:");
9170                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9171                }
9172                if (!intent.debugCheck()) {
9173                    Log.w(TAG, "==> For Activity " + a.info.name);
9174                }
9175                addFilter(intent);
9176            }
9177        }
9178
9179        public final void removeActivity(PackageParser.Activity a, String type) {
9180            mActivities.remove(a.getComponentName());
9181            if (DEBUG_SHOW_INFO) {
9182                Log.v(TAG, "  " + type + " "
9183                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9184                                : a.info.name) + ":");
9185                Log.v(TAG, "    Class=" + a.info.name);
9186            }
9187            final int NI = a.intents.size();
9188            for (int j=0; j<NI; j++) {
9189                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9190                if (DEBUG_SHOW_INFO) {
9191                    Log.v(TAG, "    IntentFilter:");
9192                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9193                }
9194                removeFilter(intent);
9195            }
9196        }
9197
9198        @Override
9199        protected boolean allowFilterResult(
9200                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9201            ActivityInfo filterAi = filter.activity.info;
9202            for (int i=dest.size()-1; i>=0; i--) {
9203                ActivityInfo destAi = dest.get(i).activityInfo;
9204                if (destAi.name == filterAi.name
9205                        && destAi.packageName == filterAi.packageName) {
9206                    return false;
9207                }
9208            }
9209            return true;
9210        }
9211
9212        @Override
9213        protected ActivityIntentInfo[] newArray(int size) {
9214            return new ActivityIntentInfo[size];
9215        }
9216
9217        @Override
9218        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9219            if (!sUserManager.exists(userId)) return true;
9220            PackageParser.Package p = filter.activity.owner;
9221            if (p != null) {
9222                PackageSetting ps = (PackageSetting)p.mExtras;
9223                if (ps != null) {
9224                    // System apps are never considered stopped for purposes of
9225                    // filtering, because there may be no way for the user to
9226                    // actually re-launch them.
9227                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9228                            && ps.getStopped(userId);
9229                }
9230            }
9231            return false;
9232        }
9233
9234        @Override
9235        protected boolean isPackageForFilter(String packageName,
9236                PackageParser.ActivityIntentInfo info) {
9237            return packageName.equals(info.activity.owner.packageName);
9238        }
9239
9240        @Override
9241        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9242                int match, int userId) {
9243            if (!sUserManager.exists(userId)) return null;
9244            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9245                return null;
9246            }
9247            final PackageParser.Activity activity = info.activity;
9248            if (mSafeMode && (activity.info.applicationInfo.flags
9249                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9250                return null;
9251            }
9252            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9253            if (ps == null) {
9254                return null;
9255            }
9256            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9257                    ps.readUserState(userId), userId);
9258            if (ai == null) {
9259                return null;
9260            }
9261            final ResolveInfo res = new ResolveInfo();
9262            res.activityInfo = ai;
9263            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9264                res.filter = info;
9265            }
9266            if (info != null) {
9267                res.handleAllWebDataURI = info.handleAllWebDataURI();
9268            }
9269            res.priority = info.getPriority();
9270            res.preferredOrder = activity.owner.mPreferredOrder;
9271            //System.out.println("Result: " + res.activityInfo.className +
9272            //                   " = " + res.priority);
9273            res.match = match;
9274            res.isDefault = info.hasDefault;
9275            res.labelRes = info.labelRes;
9276            res.nonLocalizedLabel = info.nonLocalizedLabel;
9277            if (userNeedsBadging(userId)) {
9278                res.noResourceId = true;
9279            } else {
9280                res.icon = info.icon;
9281            }
9282            res.iconResourceId = info.icon;
9283            res.system = res.activityInfo.applicationInfo.isSystemApp();
9284            return res;
9285        }
9286
9287        @Override
9288        protected void sortResults(List<ResolveInfo> results) {
9289            Collections.sort(results, mResolvePrioritySorter);
9290        }
9291
9292        @Override
9293        protected void dumpFilter(PrintWriter out, String prefix,
9294                PackageParser.ActivityIntentInfo filter) {
9295            out.print(prefix); out.print(
9296                    Integer.toHexString(System.identityHashCode(filter.activity)));
9297                    out.print(' ');
9298                    filter.activity.printComponentShortName(out);
9299                    out.print(" filter ");
9300                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9301        }
9302
9303        @Override
9304        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9305            return filter.activity;
9306        }
9307
9308        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9309            PackageParser.Activity activity = (PackageParser.Activity)label;
9310            out.print(prefix); out.print(
9311                    Integer.toHexString(System.identityHashCode(activity)));
9312                    out.print(' ');
9313                    activity.printComponentShortName(out);
9314            if (count > 1) {
9315                out.print(" ("); out.print(count); out.print(" filters)");
9316            }
9317            out.println();
9318        }
9319
9320//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9321//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9322//            final List<ResolveInfo> retList = Lists.newArrayList();
9323//            while (i.hasNext()) {
9324//                final ResolveInfo resolveInfo = i.next();
9325//                if (isEnabledLP(resolveInfo.activityInfo)) {
9326//                    retList.add(resolveInfo);
9327//                }
9328//            }
9329//            return retList;
9330//        }
9331
9332        // Keys are String (activity class name), values are Activity.
9333        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9334                = new ArrayMap<ComponentName, PackageParser.Activity>();
9335        private int mFlags;
9336    }
9337
9338    private final class ServiceIntentResolver
9339            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9340        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9341                boolean defaultOnly, int userId) {
9342            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9343            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9344        }
9345
9346        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9347                int userId) {
9348            if (!sUserManager.exists(userId)) return null;
9349            mFlags = flags;
9350            return super.queryIntent(intent, resolvedType,
9351                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9352        }
9353
9354        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9355                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9356            if (!sUserManager.exists(userId)) return null;
9357            if (packageServices == null) {
9358                return null;
9359            }
9360            mFlags = flags;
9361            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9362            final int N = packageServices.size();
9363            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9364                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9365
9366            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9367            for (int i = 0; i < N; ++i) {
9368                intentFilters = packageServices.get(i).intents;
9369                if (intentFilters != null && intentFilters.size() > 0) {
9370                    PackageParser.ServiceIntentInfo[] array =
9371                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9372                    intentFilters.toArray(array);
9373                    listCut.add(array);
9374                }
9375            }
9376            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9377        }
9378
9379        public final void addService(PackageParser.Service s) {
9380            mServices.put(s.getComponentName(), s);
9381            if (DEBUG_SHOW_INFO) {
9382                Log.v(TAG, "  "
9383                        + (s.info.nonLocalizedLabel != null
9384                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9385                Log.v(TAG, "    Class=" + s.info.name);
9386            }
9387            final int NI = s.intents.size();
9388            int j;
9389            for (j=0; j<NI; j++) {
9390                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9391                if (DEBUG_SHOW_INFO) {
9392                    Log.v(TAG, "    IntentFilter:");
9393                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9394                }
9395                if (!intent.debugCheck()) {
9396                    Log.w(TAG, "==> For Service " + s.info.name);
9397                }
9398                addFilter(intent);
9399            }
9400        }
9401
9402        public final void removeService(PackageParser.Service s) {
9403            mServices.remove(s.getComponentName());
9404            if (DEBUG_SHOW_INFO) {
9405                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9406                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9407                Log.v(TAG, "    Class=" + s.info.name);
9408            }
9409            final int NI = s.intents.size();
9410            int j;
9411            for (j=0; j<NI; j++) {
9412                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9413                if (DEBUG_SHOW_INFO) {
9414                    Log.v(TAG, "    IntentFilter:");
9415                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9416                }
9417                removeFilter(intent);
9418            }
9419        }
9420
9421        @Override
9422        protected boolean allowFilterResult(
9423                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9424            ServiceInfo filterSi = filter.service.info;
9425            for (int i=dest.size()-1; i>=0; i--) {
9426                ServiceInfo destAi = dest.get(i).serviceInfo;
9427                if (destAi.name == filterSi.name
9428                        && destAi.packageName == filterSi.packageName) {
9429                    return false;
9430                }
9431            }
9432            return true;
9433        }
9434
9435        @Override
9436        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9437            return new PackageParser.ServiceIntentInfo[size];
9438        }
9439
9440        @Override
9441        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9442            if (!sUserManager.exists(userId)) return true;
9443            PackageParser.Package p = filter.service.owner;
9444            if (p != null) {
9445                PackageSetting ps = (PackageSetting)p.mExtras;
9446                if (ps != null) {
9447                    // System apps are never considered stopped for purposes of
9448                    // filtering, because there may be no way for the user to
9449                    // actually re-launch them.
9450                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9451                            && ps.getStopped(userId);
9452                }
9453            }
9454            return false;
9455        }
9456
9457        @Override
9458        protected boolean isPackageForFilter(String packageName,
9459                PackageParser.ServiceIntentInfo info) {
9460            return packageName.equals(info.service.owner.packageName);
9461        }
9462
9463        @Override
9464        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9465                int match, int userId) {
9466            if (!sUserManager.exists(userId)) return null;
9467            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9468            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9469                return null;
9470            }
9471            final PackageParser.Service service = info.service;
9472            if (mSafeMode && (service.info.applicationInfo.flags
9473                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9474                return null;
9475            }
9476            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9477            if (ps == null) {
9478                return null;
9479            }
9480            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9481                    ps.readUserState(userId), userId);
9482            if (si == null) {
9483                return null;
9484            }
9485            final ResolveInfo res = new ResolveInfo();
9486            res.serviceInfo = si;
9487            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9488                res.filter = filter;
9489            }
9490            res.priority = info.getPriority();
9491            res.preferredOrder = service.owner.mPreferredOrder;
9492            res.match = match;
9493            res.isDefault = info.hasDefault;
9494            res.labelRes = info.labelRes;
9495            res.nonLocalizedLabel = info.nonLocalizedLabel;
9496            res.icon = info.icon;
9497            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9498            return res;
9499        }
9500
9501        @Override
9502        protected void sortResults(List<ResolveInfo> results) {
9503            Collections.sort(results, mResolvePrioritySorter);
9504        }
9505
9506        @Override
9507        protected void dumpFilter(PrintWriter out, String prefix,
9508                PackageParser.ServiceIntentInfo filter) {
9509            out.print(prefix); out.print(
9510                    Integer.toHexString(System.identityHashCode(filter.service)));
9511                    out.print(' ');
9512                    filter.service.printComponentShortName(out);
9513                    out.print(" filter ");
9514                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9515        }
9516
9517        @Override
9518        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9519            return filter.service;
9520        }
9521
9522        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9523            PackageParser.Service service = (PackageParser.Service)label;
9524            out.print(prefix); out.print(
9525                    Integer.toHexString(System.identityHashCode(service)));
9526                    out.print(' ');
9527                    service.printComponentShortName(out);
9528            if (count > 1) {
9529                out.print(" ("); out.print(count); out.print(" filters)");
9530            }
9531            out.println();
9532        }
9533
9534//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9535//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9536//            final List<ResolveInfo> retList = Lists.newArrayList();
9537//            while (i.hasNext()) {
9538//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9539//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9540//                    retList.add(resolveInfo);
9541//                }
9542//            }
9543//            return retList;
9544//        }
9545
9546        // Keys are String (activity class name), values are Activity.
9547        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9548                = new ArrayMap<ComponentName, PackageParser.Service>();
9549        private int mFlags;
9550    };
9551
9552    private final class ProviderIntentResolver
9553            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9554        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9555                boolean defaultOnly, int userId) {
9556            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9557            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9558        }
9559
9560        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9561                int userId) {
9562            if (!sUserManager.exists(userId))
9563                return null;
9564            mFlags = flags;
9565            return super.queryIntent(intent, resolvedType,
9566                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9567        }
9568
9569        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9570                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9571            if (!sUserManager.exists(userId))
9572                return null;
9573            if (packageProviders == null) {
9574                return null;
9575            }
9576            mFlags = flags;
9577            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9578            final int N = packageProviders.size();
9579            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9580                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9581
9582            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9583            for (int i = 0; i < N; ++i) {
9584                intentFilters = packageProviders.get(i).intents;
9585                if (intentFilters != null && intentFilters.size() > 0) {
9586                    PackageParser.ProviderIntentInfo[] array =
9587                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9588                    intentFilters.toArray(array);
9589                    listCut.add(array);
9590                }
9591            }
9592            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9593        }
9594
9595        public final void addProvider(PackageParser.Provider p) {
9596            if (mProviders.containsKey(p.getComponentName())) {
9597                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9598                return;
9599            }
9600
9601            mProviders.put(p.getComponentName(), p);
9602            if (DEBUG_SHOW_INFO) {
9603                Log.v(TAG, "  "
9604                        + (p.info.nonLocalizedLabel != null
9605                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9606                Log.v(TAG, "    Class=" + p.info.name);
9607            }
9608            final int NI = p.intents.size();
9609            int j;
9610            for (j = 0; j < NI; j++) {
9611                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9612                if (DEBUG_SHOW_INFO) {
9613                    Log.v(TAG, "    IntentFilter:");
9614                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9615                }
9616                if (!intent.debugCheck()) {
9617                    Log.w(TAG, "==> For Provider " + p.info.name);
9618                }
9619                addFilter(intent);
9620            }
9621        }
9622
9623        public final void removeProvider(PackageParser.Provider p) {
9624            mProviders.remove(p.getComponentName());
9625            if (DEBUG_SHOW_INFO) {
9626                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9627                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9628                Log.v(TAG, "    Class=" + p.info.name);
9629            }
9630            final int NI = p.intents.size();
9631            int j;
9632            for (j = 0; j < NI; j++) {
9633                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9634                if (DEBUG_SHOW_INFO) {
9635                    Log.v(TAG, "    IntentFilter:");
9636                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9637                }
9638                removeFilter(intent);
9639            }
9640        }
9641
9642        @Override
9643        protected boolean allowFilterResult(
9644                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9645            ProviderInfo filterPi = filter.provider.info;
9646            for (int i = dest.size() - 1; i >= 0; i--) {
9647                ProviderInfo destPi = dest.get(i).providerInfo;
9648                if (destPi.name == filterPi.name
9649                        && destPi.packageName == filterPi.packageName) {
9650                    return false;
9651                }
9652            }
9653            return true;
9654        }
9655
9656        @Override
9657        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9658            return new PackageParser.ProviderIntentInfo[size];
9659        }
9660
9661        @Override
9662        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9663            if (!sUserManager.exists(userId))
9664                return true;
9665            PackageParser.Package p = filter.provider.owner;
9666            if (p != null) {
9667                PackageSetting ps = (PackageSetting) p.mExtras;
9668                if (ps != null) {
9669                    // System apps are never considered stopped for purposes of
9670                    // filtering, because there may be no way for the user to
9671                    // actually re-launch them.
9672                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9673                            && ps.getStopped(userId);
9674                }
9675            }
9676            return false;
9677        }
9678
9679        @Override
9680        protected boolean isPackageForFilter(String packageName,
9681                PackageParser.ProviderIntentInfo info) {
9682            return packageName.equals(info.provider.owner.packageName);
9683        }
9684
9685        @Override
9686        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9687                int match, int userId) {
9688            if (!sUserManager.exists(userId))
9689                return null;
9690            final PackageParser.ProviderIntentInfo info = filter;
9691            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9692                return null;
9693            }
9694            final PackageParser.Provider provider = info.provider;
9695            if (mSafeMode && (provider.info.applicationInfo.flags
9696                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9697                return null;
9698            }
9699            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9700            if (ps == null) {
9701                return null;
9702            }
9703            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9704                    ps.readUserState(userId), userId);
9705            if (pi == null) {
9706                return null;
9707            }
9708            final ResolveInfo res = new ResolveInfo();
9709            res.providerInfo = pi;
9710            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9711                res.filter = filter;
9712            }
9713            res.priority = info.getPriority();
9714            res.preferredOrder = provider.owner.mPreferredOrder;
9715            res.match = match;
9716            res.isDefault = info.hasDefault;
9717            res.labelRes = info.labelRes;
9718            res.nonLocalizedLabel = info.nonLocalizedLabel;
9719            res.icon = info.icon;
9720            res.system = res.providerInfo.applicationInfo.isSystemApp();
9721            return res;
9722        }
9723
9724        @Override
9725        protected void sortResults(List<ResolveInfo> results) {
9726            Collections.sort(results, mResolvePrioritySorter);
9727        }
9728
9729        @Override
9730        protected void dumpFilter(PrintWriter out, String prefix,
9731                PackageParser.ProviderIntentInfo filter) {
9732            out.print(prefix);
9733            out.print(
9734                    Integer.toHexString(System.identityHashCode(filter.provider)));
9735            out.print(' ');
9736            filter.provider.printComponentShortName(out);
9737            out.print(" filter ");
9738            out.println(Integer.toHexString(System.identityHashCode(filter)));
9739        }
9740
9741        @Override
9742        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9743            return filter.provider;
9744        }
9745
9746        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9747            PackageParser.Provider provider = (PackageParser.Provider)label;
9748            out.print(prefix); out.print(
9749                    Integer.toHexString(System.identityHashCode(provider)));
9750                    out.print(' ');
9751                    provider.printComponentShortName(out);
9752            if (count > 1) {
9753                out.print(" ("); out.print(count); out.print(" filters)");
9754            }
9755            out.println();
9756        }
9757
9758        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9759                = new ArrayMap<ComponentName, PackageParser.Provider>();
9760        private int mFlags;
9761    }
9762
9763    private static final class EphemeralIntentResolver
9764            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9765        @Override
9766        protected EphemeralResolveIntentInfo[] newArray(int size) {
9767            return new EphemeralResolveIntentInfo[size];
9768        }
9769
9770        @Override
9771        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9772            return true;
9773        }
9774
9775        @Override
9776        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9777                int userId) {
9778            if (!sUserManager.exists(userId)) {
9779                return null;
9780            }
9781            return info.getEphemeralResolveInfo();
9782        }
9783    }
9784
9785    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9786            new Comparator<ResolveInfo>() {
9787        public int compare(ResolveInfo r1, ResolveInfo r2) {
9788            int v1 = r1.priority;
9789            int v2 = r2.priority;
9790            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9791            if (v1 != v2) {
9792                return (v1 > v2) ? -1 : 1;
9793            }
9794            v1 = r1.preferredOrder;
9795            v2 = r2.preferredOrder;
9796            if (v1 != v2) {
9797                return (v1 > v2) ? -1 : 1;
9798            }
9799            if (r1.isDefault != r2.isDefault) {
9800                return r1.isDefault ? -1 : 1;
9801            }
9802            v1 = r1.match;
9803            v2 = r2.match;
9804            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9805            if (v1 != v2) {
9806                return (v1 > v2) ? -1 : 1;
9807            }
9808            if (r1.system != r2.system) {
9809                return r1.system ? -1 : 1;
9810            }
9811            if (r1.activityInfo != null) {
9812                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9813            }
9814            if (r1.serviceInfo != null) {
9815                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9816            }
9817            if (r1.providerInfo != null) {
9818                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9819            }
9820            return 0;
9821        }
9822    };
9823
9824    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9825            new Comparator<ProviderInfo>() {
9826        public int compare(ProviderInfo p1, ProviderInfo p2) {
9827            final int v1 = p1.initOrder;
9828            final int v2 = p2.initOrder;
9829            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9830        }
9831    };
9832
9833    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9834            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9835            final int[] userIds) {
9836        mHandler.post(new Runnable() {
9837            @Override
9838            public void run() {
9839                try {
9840                    final IActivityManager am = ActivityManagerNative.getDefault();
9841                    if (am == null) return;
9842                    final int[] resolvedUserIds;
9843                    if (userIds == null) {
9844                        resolvedUserIds = am.getRunningUserIds();
9845                    } else {
9846                        resolvedUserIds = userIds;
9847                    }
9848                    for (int id : resolvedUserIds) {
9849                        final Intent intent = new Intent(action,
9850                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9851                        if (extras != null) {
9852                            intent.putExtras(extras);
9853                        }
9854                        if (targetPkg != null) {
9855                            intent.setPackage(targetPkg);
9856                        }
9857                        // Modify the UID when posting to other users
9858                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9859                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9860                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9861                            intent.putExtra(Intent.EXTRA_UID, uid);
9862                        }
9863                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9864                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9865                        if (DEBUG_BROADCASTS) {
9866                            RuntimeException here = new RuntimeException("here");
9867                            here.fillInStackTrace();
9868                            Slog.d(TAG, "Sending to user " + id + ": "
9869                                    + intent.toShortString(false, true, false, false)
9870                                    + " " + intent.getExtras(), here);
9871                        }
9872                        am.broadcastIntent(null, intent, null, finishedReceiver,
9873                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9874                                null, finishedReceiver != null, false, id);
9875                    }
9876                } catch (RemoteException ex) {
9877                }
9878            }
9879        });
9880    }
9881
9882    /**
9883     * Check if the external storage media is available. This is true if there
9884     * is a mounted external storage medium or if the external storage is
9885     * emulated.
9886     */
9887    private boolean isExternalMediaAvailable() {
9888        return mMediaMounted || Environment.isExternalStorageEmulated();
9889    }
9890
9891    @Override
9892    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9893        // writer
9894        synchronized (mPackages) {
9895            if (!isExternalMediaAvailable()) {
9896                // If the external storage is no longer mounted at this point,
9897                // the caller may not have been able to delete all of this
9898                // packages files and can not delete any more.  Bail.
9899                return null;
9900            }
9901            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9902            if (lastPackage != null) {
9903                pkgs.remove(lastPackage);
9904            }
9905            if (pkgs.size() > 0) {
9906                return pkgs.get(0);
9907            }
9908        }
9909        return null;
9910    }
9911
9912    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9913        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9914                userId, andCode ? 1 : 0, packageName);
9915        if (mSystemReady) {
9916            msg.sendToTarget();
9917        } else {
9918            if (mPostSystemReadyMessages == null) {
9919                mPostSystemReadyMessages = new ArrayList<>();
9920            }
9921            mPostSystemReadyMessages.add(msg);
9922        }
9923    }
9924
9925    void startCleaningPackages() {
9926        // reader
9927        synchronized (mPackages) {
9928            if (!isExternalMediaAvailable()) {
9929                return;
9930            }
9931            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9932                return;
9933            }
9934        }
9935        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9936        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9937        IActivityManager am = ActivityManagerNative.getDefault();
9938        if (am != null) {
9939            try {
9940                am.startService(null, intent, null, mContext.getOpPackageName(),
9941                        UserHandle.USER_SYSTEM);
9942            } catch (RemoteException e) {
9943            }
9944        }
9945    }
9946
9947    @Override
9948    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9949            int installFlags, String installerPackageName, VerificationParams verificationParams,
9950            String packageAbiOverride) {
9951        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9952                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9953    }
9954
9955    @Override
9956    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9957            int installFlags, String installerPackageName, VerificationParams verificationParams,
9958            String packageAbiOverride, int userId) {
9959        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9960
9961        final int callingUid = Binder.getCallingUid();
9962        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9963
9964        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9965            try {
9966                if (observer != null) {
9967                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9968                }
9969            } catch (RemoteException re) {
9970            }
9971            return;
9972        }
9973
9974        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9975            installFlags |= PackageManager.INSTALL_FROM_ADB;
9976
9977        } else {
9978            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9979            // about installerPackageName.
9980
9981            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9982            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9983        }
9984
9985        UserHandle user;
9986        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9987            user = UserHandle.ALL;
9988        } else {
9989            user = new UserHandle(userId);
9990        }
9991
9992        // Only system components can circumvent runtime permissions when installing.
9993        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9994                && mContext.checkCallingOrSelfPermission(Manifest.permission
9995                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9996            throw new SecurityException("You need the "
9997                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9998                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9999        }
10000
10001        verificationParams.setInstallerUid(callingUid);
10002
10003        final File originFile = new File(originPath);
10004        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10005
10006        final Message msg = mHandler.obtainMessage(INIT_COPY);
10007        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10008                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10009        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10010        msg.obj = params;
10011
10012        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10013                System.identityHashCode(msg.obj));
10014        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10015                System.identityHashCode(msg.obj));
10016
10017        mHandler.sendMessage(msg);
10018    }
10019
10020    void installStage(String packageName, File stagedDir, String stagedCid,
10021            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10022            String installerPackageName, int installerUid, UserHandle user) {
10023        if (DEBUG_EPHEMERAL) {
10024            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10025                Slog.d(TAG, "Ephemeral install of " + packageName);
10026            }
10027        }
10028        final VerificationParams verifParams = new VerificationParams(
10029                null, sessionParams.originatingUri, sessionParams.referrerUri,
10030                sessionParams.originatingUid, null);
10031        verifParams.setInstallerUid(installerUid);
10032
10033        final OriginInfo origin;
10034        if (stagedDir != null) {
10035            origin = OriginInfo.fromStagedFile(stagedDir);
10036        } else {
10037            origin = OriginInfo.fromStagedContainer(stagedCid);
10038        }
10039
10040        final Message msg = mHandler.obtainMessage(INIT_COPY);
10041        final InstallParams params = new InstallParams(origin, null, observer,
10042                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10043                verifParams, user, sessionParams.abiOverride,
10044                sessionParams.grantedRuntimePermissions);
10045        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10046        msg.obj = params;
10047
10048        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10049                System.identityHashCode(msg.obj));
10050        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10051                System.identityHashCode(msg.obj));
10052
10053        mHandler.sendMessage(msg);
10054    }
10055
10056    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10057        Bundle extras = new Bundle(1);
10058        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10059
10060        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10061                packageName, extras, 0, null, null, new int[] {userId});
10062        try {
10063            IActivityManager am = ActivityManagerNative.getDefault();
10064            final boolean isSystem =
10065                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10066            if (isSystem && am.isUserRunning(userId, 0)) {
10067                // The just-installed/enabled app is bundled on the system, so presumed
10068                // to be able to run automatically without needing an explicit launch.
10069                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10070                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10071                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10072                        .setPackage(packageName);
10073                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10074                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10075            }
10076        } catch (RemoteException e) {
10077            // shouldn't happen
10078            Slog.w(TAG, "Unable to bootstrap installed package", e);
10079        }
10080    }
10081
10082    @Override
10083    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10084            int userId) {
10085        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10086        PackageSetting pkgSetting;
10087        final int uid = Binder.getCallingUid();
10088        enforceCrossUserPermission(uid, userId, true, true,
10089                "setApplicationHiddenSetting for user " + userId);
10090
10091        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10092            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10093            return false;
10094        }
10095
10096        long callingId = Binder.clearCallingIdentity();
10097        try {
10098            boolean sendAdded = false;
10099            boolean sendRemoved = false;
10100            // writer
10101            synchronized (mPackages) {
10102                pkgSetting = mSettings.mPackages.get(packageName);
10103                if (pkgSetting == null) {
10104                    return false;
10105                }
10106                if (pkgSetting.getHidden(userId) != hidden) {
10107                    pkgSetting.setHidden(hidden, userId);
10108                    mSettings.writePackageRestrictionsLPr(userId);
10109                    if (hidden) {
10110                        sendRemoved = true;
10111                    } else {
10112                        sendAdded = true;
10113                    }
10114                }
10115            }
10116            if (sendAdded) {
10117                sendPackageAddedForUser(packageName, pkgSetting, userId);
10118                return true;
10119            }
10120            if (sendRemoved) {
10121                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10122                        "hiding pkg");
10123                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10124                return true;
10125            }
10126        } finally {
10127            Binder.restoreCallingIdentity(callingId);
10128        }
10129        return false;
10130    }
10131
10132    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10133            int userId) {
10134        final PackageRemovedInfo info = new PackageRemovedInfo();
10135        info.removedPackage = packageName;
10136        info.removedUsers = new int[] {userId};
10137        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10138        info.sendBroadcast(false, false, false);
10139    }
10140
10141    /**
10142     * Returns true if application is not found or there was an error. Otherwise it returns
10143     * the hidden state of the package for the given user.
10144     */
10145    @Override
10146    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10147        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10148        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10149                false, "getApplicationHidden for user " + userId);
10150        PackageSetting pkgSetting;
10151        long callingId = Binder.clearCallingIdentity();
10152        try {
10153            // writer
10154            synchronized (mPackages) {
10155                pkgSetting = mSettings.mPackages.get(packageName);
10156                if (pkgSetting == null) {
10157                    return true;
10158                }
10159                return pkgSetting.getHidden(userId);
10160            }
10161        } finally {
10162            Binder.restoreCallingIdentity(callingId);
10163        }
10164    }
10165
10166    /**
10167     * @hide
10168     */
10169    @Override
10170    public int installExistingPackageAsUser(String packageName, int userId) {
10171        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10172                null);
10173        PackageSetting pkgSetting;
10174        final int uid = Binder.getCallingUid();
10175        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10176                + userId);
10177        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10178            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10179        }
10180
10181        long callingId = Binder.clearCallingIdentity();
10182        try {
10183            boolean sendAdded = false;
10184
10185            // writer
10186            synchronized (mPackages) {
10187                pkgSetting = mSettings.mPackages.get(packageName);
10188                if (pkgSetting == null) {
10189                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10190                }
10191                if (!pkgSetting.getInstalled(userId)) {
10192                    pkgSetting.setInstalled(true, userId);
10193                    pkgSetting.setHidden(false, userId);
10194                    mSettings.writePackageRestrictionsLPr(userId);
10195                    sendAdded = true;
10196                }
10197            }
10198
10199            if (sendAdded) {
10200                sendPackageAddedForUser(packageName, pkgSetting, userId);
10201            }
10202        } finally {
10203            Binder.restoreCallingIdentity(callingId);
10204        }
10205
10206        return PackageManager.INSTALL_SUCCEEDED;
10207    }
10208
10209    boolean isUserRestricted(int userId, String restrictionKey) {
10210        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10211        if (restrictions.getBoolean(restrictionKey, false)) {
10212            Log.w(TAG, "User is restricted: " + restrictionKey);
10213            return true;
10214        }
10215        return false;
10216    }
10217
10218    @Override
10219    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10220        mContext.enforceCallingOrSelfPermission(
10221                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10222                "Only package verification agents can verify applications");
10223
10224        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10225        final PackageVerificationResponse response = new PackageVerificationResponse(
10226                verificationCode, Binder.getCallingUid());
10227        msg.arg1 = id;
10228        msg.obj = response;
10229        mHandler.sendMessage(msg);
10230    }
10231
10232    @Override
10233    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10234            long millisecondsToDelay) {
10235        mContext.enforceCallingOrSelfPermission(
10236                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10237                "Only package verification agents can extend verification timeouts");
10238
10239        final PackageVerificationState state = mPendingVerification.get(id);
10240        final PackageVerificationResponse response = new PackageVerificationResponse(
10241                verificationCodeAtTimeout, Binder.getCallingUid());
10242
10243        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10244            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10245        }
10246        if (millisecondsToDelay < 0) {
10247            millisecondsToDelay = 0;
10248        }
10249        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10250                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10251            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10252        }
10253
10254        if ((state != null) && !state.timeoutExtended()) {
10255            state.extendTimeout();
10256
10257            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10258            msg.arg1 = id;
10259            msg.obj = response;
10260            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10261        }
10262    }
10263
10264    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10265            int verificationCode, UserHandle user) {
10266        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10267        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10268        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10269        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10270        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10271
10272        mContext.sendBroadcastAsUser(intent, user,
10273                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10274    }
10275
10276    private ComponentName matchComponentForVerifier(String packageName,
10277            List<ResolveInfo> receivers) {
10278        ActivityInfo targetReceiver = null;
10279
10280        final int NR = receivers.size();
10281        for (int i = 0; i < NR; i++) {
10282            final ResolveInfo info = receivers.get(i);
10283            if (info.activityInfo == null) {
10284                continue;
10285            }
10286
10287            if (packageName.equals(info.activityInfo.packageName)) {
10288                targetReceiver = info.activityInfo;
10289                break;
10290            }
10291        }
10292
10293        if (targetReceiver == null) {
10294            return null;
10295        }
10296
10297        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10298    }
10299
10300    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10301            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10302        if (pkgInfo.verifiers.length == 0) {
10303            return null;
10304        }
10305
10306        final int N = pkgInfo.verifiers.length;
10307        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10308        for (int i = 0; i < N; i++) {
10309            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10310
10311            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10312                    receivers);
10313            if (comp == null) {
10314                continue;
10315            }
10316
10317            final int verifierUid = getUidForVerifier(verifierInfo);
10318            if (verifierUid == -1) {
10319                continue;
10320            }
10321
10322            if (DEBUG_VERIFY) {
10323                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10324                        + " with the correct signature");
10325            }
10326            sufficientVerifiers.add(comp);
10327            verificationState.addSufficientVerifier(verifierUid);
10328        }
10329
10330        return sufficientVerifiers;
10331    }
10332
10333    private int getUidForVerifier(VerifierInfo verifierInfo) {
10334        synchronized (mPackages) {
10335            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10336            if (pkg == null) {
10337                return -1;
10338            } else if (pkg.mSignatures.length != 1) {
10339                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10340                        + " has more than one signature; ignoring");
10341                return -1;
10342            }
10343
10344            /*
10345             * If the public key of the package's signature does not match
10346             * our expected public key, then this is a different package and
10347             * we should skip.
10348             */
10349
10350            final byte[] expectedPublicKey;
10351            try {
10352                final Signature verifierSig = pkg.mSignatures[0];
10353                final PublicKey publicKey = verifierSig.getPublicKey();
10354                expectedPublicKey = publicKey.getEncoded();
10355            } catch (CertificateException e) {
10356                return -1;
10357            }
10358
10359            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10360
10361            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10362                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10363                        + " does not have the expected public key; ignoring");
10364                return -1;
10365            }
10366
10367            return pkg.applicationInfo.uid;
10368        }
10369    }
10370
10371    @Override
10372    public void finishPackageInstall(int token) {
10373        enforceSystemOrRoot("Only the system is allowed to finish installs");
10374
10375        if (DEBUG_INSTALL) {
10376            Slog.v(TAG, "BM finishing package install for " + token);
10377        }
10378        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10379
10380        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10381        mHandler.sendMessage(msg);
10382    }
10383
10384    /**
10385     * Get the verification agent timeout.
10386     *
10387     * @return verification timeout in milliseconds
10388     */
10389    private long getVerificationTimeout() {
10390        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10391                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10392                DEFAULT_VERIFICATION_TIMEOUT);
10393    }
10394
10395    /**
10396     * Get the default verification agent response code.
10397     *
10398     * @return default verification response code
10399     */
10400    private int getDefaultVerificationResponse() {
10401        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10402                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10403                DEFAULT_VERIFICATION_RESPONSE);
10404    }
10405
10406    /**
10407     * Check whether or not package verification has been enabled.
10408     *
10409     * @return true if verification should be performed
10410     */
10411    private boolean isVerificationEnabled(int userId, int installFlags) {
10412        if (!DEFAULT_VERIFY_ENABLE) {
10413            return false;
10414        }
10415        // TODO: fix b/25118622; don't bypass verification
10416        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10417            return false;
10418        }
10419        // Ephemeral apps don't get the full verification treatment
10420        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10421            if (DEBUG_EPHEMERAL) {
10422                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10423            }
10424            return false;
10425        }
10426
10427        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10428
10429        // Check if installing from ADB
10430        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10431            // Do not run verification in a test harness environment
10432            if (ActivityManager.isRunningInTestHarness()) {
10433                return false;
10434            }
10435            if (ensureVerifyAppsEnabled) {
10436                return true;
10437            }
10438            // Check if the developer does not want package verification for ADB installs
10439            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10440                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10441                return false;
10442            }
10443        }
10444
10445        if (ensureVerifyAppsEnabled) {
10446            return true;
10447        }
10448
10449        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10450                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10451    }
10452
10453    @Override
10454    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10455            throws RemoteException {
10456        mContext.enforceCallingOrSelfPermission(
10457                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10458                "Only intentfilter verification agents can verify applications");
10459
10460        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10461        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10462                Binder.getCallingUid(), verificationCode, failedDomains);
10463        msg.arg1 = id;
10464        msg.obj = response;
10465        mHandler.sendMessage(msg);
10466    }
10467
10468    @Override
10469    public int getIntentVerificationStatus(String packageName, int userId) {
10470        synchronized (mPackages) {
10471            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10472        }
10473    }
10474
10475    @Override
10476    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10477        mContext.enforceCallingOrSelfPermission(
10478                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10479
10480        boolean result = false;
10481        synchronized (mPackages) {
10482            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10483        }
10484        if (result) {
10485            scheduleWritePackageRestrictionsLocked(userId);
10486        }
10487        return result;
10488    }
10489
10490    @Override
10491    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10492        synchronized (mPackages) {
10493            return mSettings.getIntentFilterVerificationsLPr(packageName);
10494        }
10495    }
10496
10497    @Override
10498    public List<IntentFilter> getAllIntentFilters(String packageName) {
10499        if (TextUtils.isEmpty(packageName)) {
10500            return Collections.<IntentFilter>emptyList();
10501        }
10502        synchronized (mPackages) {
10503            PackageParser.Package pkg = mPackages.get(packageName);
10504            if (pkg == null || pkg.activities == null) {
10505                return Collections.<IntentFilter>emptyList();
10506            }
10507            final int count = pkg.activities.size();
10508            ArrayList<IntentFilter> result = new ArrayList<>();
10509            for (int n=0; n<count; n++) {
10510                PackageParser.Activity activity = pkg.activities.get(n);
10511                if (activity.intents != null && activity.intents.size() > 0) {
10512                    result.addAll(activity.intents);
10513                }
10514            }
10515            return result;
10516        }
10517    }
10518
10519    @Override
10520    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10521        mContext.enforceCallingOrSelfPermission(
10522                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10523
10524        synchronized (mPackages) {
10525            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10526            if (packageName != null) {
10527                result |= updateIntentVerificationStatus(packageName,
10528                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10529                        userId);
10530                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10531                        packageName, userId);
10532            }
10533            return result;
10534        }
10535    }
10536
10537    @Override
10538    public String getDefaultBrowserPackageName(int userId) {
10539        synchronized (mPackages) {
10540            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10541        }
10542    }
10543
10544    /**
10545     * Get the "allow unknown sources" setting.
10546     *
10547     * @return the current "allow unknown sources" setting
10548     */
10549    private int getUnknownSourcesSettings() {
10550        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10551                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10552                -1);
10553    }
10554
10555    @Override
10556    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10557        final int uid = Binder.getCallingUid();
10558        // writer
10559        synchronized (mPackages) {
10560            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10561            if (targetPackageSetting == null) {
10562                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10563            }
10564
10565            PackageSetting installerPackageSetting;
10566            if (installerPackageName != null) {
10567                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10568                if (installerPackageSetting == null) {
10569                    throw new IllegalArgumentException("Unknown installer package: "
10570                            + installerPackageName);
10571                }
10572            } else {
10573                installerPackageSetting = null;
10574            }
10575
10576            Signature[] callerSignature;
10577            Object obj = mSettings.getUserIdLPr(uid);
10578            if (obj != null) {
10579                if (obj instanceof SharedUserSetting) {
10580                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10581                } else if (obj instanceof PackageSetting) {
10582                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10583                } else {
10584                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10585                }
10586            } else {
10587                throw new SecurityException("Unknown calling uid " + uid);
10588            }
10589
10590            // Verify: can't set installerPackageName to a package that is
10591            // not signed with the same cert as the caller.
10592            if (installerPackageSetting != null) {
10593                if (compareSignatures(callerSignature,
10594                        installerPackageSetting.signatures.mSignatures)
10595                        != PackageManager.SIGNATURE_MATCH) {
10596                    throw new SecurityException(
10597                            "Caller does not have same cert as new installer package "
10598                            + installerPackageName);
10599                }
10600            }
10601
10602            // Verify: if target already has an installer package, it must
10603            // be signed with the same cert as the caller.
10604            if (targetPackageSetting.installerPackageName != null) {
10605                PackageSetting setting = mSettings.mPackages.get(
10606                        targetPackageSetting.installerPackageName);
10607                // If the currently set package isn't valid, then it's always
10608                // okay to change it.
10609                if (setting != null) {
10610                    if (compareSignatures(callerSignature,
10611                            setting.signatures.mSignatures)
10612                            != PackageManager.SIGNATURE_MATCH) {
10613                        throw new SecurityException(
10614                                "Caller does not have same cert as old installer package "
10615                                + targetPackageSetting.installerPackageName);
10616                    }
10617                }
10618            }
10619
10620            // Okay!
10621            targetPackageSetting.installerPackageName = installerPackageName;
10622            scheduleWriteSettingsLocked();
10623        }
10624    }
10625
10626    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10627        // Queue up an async operation since the package installation may take a little while.
10628        mHandler.post(new Runnable() {
10629            public void run() {
10630                mHandler.removeCallbacks(this);
10631                 // Result object to be returned
10632                PackageInstalledInfo res = new PackageInstalledInfo();
10633                res.returnCode = currentStatus;
10634                res.uid = -1;
10635                res.pkg = null;
10636                res.removedInfo = new PackageRemovedInfo();
10637                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10638                    args.doPreInstall(res.returnCode);
10639                    synchronized (mInstallLock) {
10640                        installPackageTracedLI(args, res);
10641                    }
10642                    args.doPostInstall(res.returnCode, res.uid);
10643                }
10644
10645                // A restore should be performed at this point if (a) the install
10646                // succeeded, (b) the operation is not an update, and (c) the new
10647                // package has not opted out of backup participation.
10648                final boolean update = res.removedInfo.removedPackage != null;
10649                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10650                boolean doRestore = !update
10651                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10652
10653                // Set up the post-install work request bookkeeping.  This will be used
10654                // and cleaned up by the post-install event handling regardless of whether
10655                // there's a restore pass performed.  Token values are >= 1.
10656                int token;
10657                if (mNextInstallToken < 0) mNextInstallToken = 1;
10658                token = mNextInstallToken++;
10659
10660                PostInstallData data = new PostInstallData(args, res);
10661                mRunningInstalls.put(token, data);
10662                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10663
10664                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10665                    // Pass responsibility to the Backup Manager.  It will perform a
10666                    // restore if appropriate, then pass responsibility back to the
10667                    // Package Manager to run the post-install observer callbacks
10668                    // and broadcasts.
10669                    IBackupManager bm = IBackupManager.Stub.asInterface(
10670                            ServiceManager.getService(Context.BACKUP_SERVICE));
10671                    if (bm != null) {
10672                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10673                                + " to BM for possible restore");
10674                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10675                        try {
10676                            // TODO: http://b/22388012
10677                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10678                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10679                            } else {
10680                                doRestore = false;
10681                            }
10682                        } catch (RemoteException e) {
10683                            // can't happen; the backup manager is local
10684                        } catch (Exception e) {
10685                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10686                            doRestore = false;
10687                        }
10688                    } else {
10689                        Slog.e(TAG, "Backup Manager not found!");
10690                        doRestore = false;
10691                    }
10692                }
10693
10694                if (!doRestore) {
10695                    // No restore possible, or the Backup Manager was mysteriously not
10696                    // available -- just fire the post-install work request directly.
10697                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10698
10699                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10700
10701                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10702                    mHandler.sendMessage(msg);
10703                }
10704            }
10705        });
10706    }
10707
10708    private abstract class HandlerParams {
10709        private static final int MAX_RETRIES = 4;
10710
10711        /**
10712         * Number of times startCopy() has been attempted and had a non-fatal
10713         * error.
10714         */
10715        private int mRetries = 0;
10716
10717        /** User handle for the user requesting the information or installation. */
10718        private final UserHandle mUser;
10719        String traceMethod;
10720        int traceCookie;
10721
10722        HandlerParams(UserHandle user) {
10723            mUser = user;
10724        }
10725
10726        UserHandle getUser() {
10727            return mUser;
10728        }
10729
10730        HandlerParams setTraceMethod(String traceMethod) {
10731            this.traceMethod = traceMethod;
10732            return this;
10733        }
10734
10735        HandlerParams setTraceCookie(int traceCookie) {
10736            this.traceCookie = traceCookie;
10737            return this;
10738        }
10739
10740        final boolean startCopy() {
10741            boolean res;
10742            try {
10743                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10744
10745                if (++mRetries > MAX_RETRIES) {
10746                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10747                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10748                    handleServiceError();
10749                    return false;
10750                } else {
10751                    handleStartCopy();
10752                    res = true;
10753                }
10754            } catch (RemoteException e) {
10755                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10756                mHandler.sendEmptyMessage(MCS_RECONNECT);
10757                res = false;
10758            }
10759            handleReturnCode();
10760            return res;
10761        }
10762
10763        final void serviceError() {
10764            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10765            handleServiceError();
10766            handleReturnCode();
10767        }
10768
10769        abstract void handleStartCopy() throws RemoteException;
10770        abstract void handleServiceError();
10771        abstract void handleReturnCode();
10772    }
10773
10774    class MeasureParams extends HandlerParams {
10775        private final PackageStats mStats;
10776        private boolean mSuccess;
10777
10778        private final IPackageStatsObserver mObserver;
10779
10780        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10781            super(new UserHandle(stats.userHandle));
10782            mObserver = observer;
10783            mStats = stats;
10784        }
10785
10786        @Override
10787        public String toString() {
10788            return "MeasureParams{"
10789                + Integer.toHexString(System.identityHashCode(this))
10790                + " " + mStats.packageName + "}";
10791        }
10792
10793        @Override
10794        void handleStartCopy() throws RemoteException {
10795            synchronized (mInstallLock) {
10796                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10797            }
10798
10799            if (mSuccess) {
10800                final boolean mounted;
10801                if (Environment.isExternalStorageEmulated()) {
10802                    mounted = true;
10803                } else {
10804                    final String status = Environment.getExternalStorageState();
10805                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10806                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10807                }
10808
10809                if (mounted) {
10810                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10811
10812                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10813                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10814
10815                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10816                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10817
10818                    // Always subtract cache size, since it's a subdirectory
10819                    mStats.externalDataSize -= mStats.externalCacheSize;
10820
10821                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10822                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10823
10824                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10825                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10826                }
10827            }
10828        }
10829
10830        @Override
10831        void handleReturnCode() {
10832            if (mObserver != null) {
10833                try {
10834                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10835                } catch (RemoteException e) {
10836                    Slog.i(TAG, "Observer no longer exists.");
10837                }
10838            }
10839        }
10840
10841        @Override
10842        void handleServiceError() {
10843            Slog.e(TAG, "Could not measure application " + mStats.packageName
10844                            + " external storage");
10845        }
10846    }
10847
10848    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10849            throws RemoteException {
10850        long result = 0;
10851        for (File path : paths) {
10852            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10853        }
10854        return result;
10855    }
10856
10857    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10858        for (File path : paths) {
10859            try {
10860                mcs.clearDirectory(path.getAbsolutePath());
10861            } catch (RemoteException e) {
10862            }
10863        }
10864    }
10865
10866    static class OriginInfo {
10867        /**
10868         * Location where install is coming from, before it has been
10869         * copied/renamed into place. This could be a single monolithic APK
10870         * file, or a cluster directory. This location may be untrusted.
10871         */
10872        final File file;
10873        final String cid;
10874
10875        /**
10876         * Flag indicating that {@link #file} or {@link #cid} has already been
10877         * staged, meaning downstream users don't need to defensively copy the
10878         * contents.
10879         */
10880        final boolean staged;
10881
10882        /**
10883         * Flag indicating that {@link #file} or {@link #cid} is an already
10884         * installed app that is being moved.
10885         */
10886        final boolean existing;
10887
10888        final String resolvedPath;
10889        final File resolvedFile;
10890
10891        static OriginInfo fromNothing() {
10892            return new OriginInfo(null, null, false, false);
10893        }
10894
10895        static OriginInfo fromUntrustedFile(File file) {
10896            return new OriginInfo(file, null, false, false);
10897        }
10898
10899        static OriginInfo fromExistingFile(File file) {
10900            return new OriginInfo(file, null, false, true);
10901        }
10902
10903        static OriginInfo fromStagedFile(File file) {
10904            return new OriginInfo(file, null, true, false);
10905        }
10906
10907        static OriginInfo fromStagedContainer(String cid) {
10908            return new OriginInfo(null, cid, true, false);
10909        }
10910
10911        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10912            this.file = file;
10913            this.cid = cid;
10914            this.staged = staged;
10915            this.existing = existing;
10916
10917            if (cid != null) {
10918                resolvedPath = PackageHelper.getSdDir(cid);
10919                resolvedFile = new File(resolvedPath);
10920            } else if (file != null) {
10921                resolvedPath = file.getAbsolutePath();
10922                resolvedFile = file;
10923            } else {
10924                resolvedPath = null;
10925                resolvedFile = null;
10926            }
10927        }
10928    }
10929
10930    static class MoveInfo {
10931        final int moveId;
10932        final String fromUuid;
10933        final String toUuid;
10934        final String packageName;
10935        final String dataAppName;
10936        final int appId;
10937        final String seinfo;
10938
10939        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10940                String dataAppName, int appId, String seinfo) {
10941            this.moveId = moveId;
10942            this.fromUuid = fromUuid;
10943            this.toUuid = toUuid;
10944            this.packageName = packageName;
10945            this.dataAppName = dataAppName;
10946            this.appId = appId;
10947            this.seinfo = seinfo;
10948        }
10949    }
10950
10951    class InstallParams extends HandlerParams {
10952        final OriginInfo origin;
10953        final MoveInfo move;
10954        final IPackageInstallObserver2 observer;
10955        int installFlags;
10956        final String installerPackageName;
10957        final String volumeUuid;
10958        final VerificationParams verificationParams;
10959        private InstallArgs mArgs;
10960        private int mRet;
10961        final String packageAbiOverride;
10962        final String[] grantedRuntimePermissions;
10963
10964        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10965                int installFlags, String installerPackageName, String volumeUuid,
10966                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10967                String[] grantedPermissions) {
10968            super(user);
10969            this.origin = origin;
10970            this.move = move;
10971            this.observer = observer;
10972            this.installFlags = installFlags;
10973            this.installerPackageName = installerPackageName;
10974            this.volumeUuid = volumeUuid;
10975            this.verificationParams = verificationParams;
10976            this.packageAbiOverride = packageAbiOverride;
10977            this.grantedRuntimePermissions = grantedPermissions;
10978        }
10979
10980        @Override
10981        public String toString() {
10982            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10983                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10984        }
10985
10986        public ManifestDigest getManifestDigest() {
10987            if (verificationParams == null) {
10988                return null;
10989            }
10990            return verificationParams.getManifestDigest();
10991        }
10992
10993        private int installLocationPolicy(PackageInfoLite pkgLite) {
10994            String packageName = pkgLite.packageName;
10995            int installLocation = pkgLite.installLocation;
10996            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10997            // reader
10998            synchronized (mPackages) {
10999                PackageParser.Package pkg = mPackages.get(packageName);
11000                if (pkg != null) {
11001                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11002                        // Check for downgrading.
11003                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11004                            try {
11005                                checkDowngrade(pkg, pkgLite);
11006                            } catch (PackageManagerException e) {
11007                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11008                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11009                            }
11010                        }
11011                        // Check for updated system application.
11012                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11013                            if (onSd) {
11014                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11015                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11016                            }
11017                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11018                        } else {
11019                            if (onSd) {
11020                                // Install flag overrides everything.
11021                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11022                            }
11023                            // If current upgrade specifies particular preference
11024                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11025                                // Application explicitly specified internal.
11026                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11027                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11028                                // App explictly prefers external. Let policy decide
11029                            } else {
11030                                // Prefer previous location
11031                                if (isExternal(pkg)) {
11032                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11033                                }
11034                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11035                            }
11036                        }
11037                    } else {
11038                        // Invalid install. Return error code
11039                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11040                    }
11041                }
11042            }
11043            // All the special cases have been taken care of.
11044            // Return result based on recommended install location.
11045            if (onSd) {
11046                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11047            }
11048            return pkgLite.recommendedInstallLocation;
11049        }
11050
11051        /*
11052         * Invoke remote method to get package information and install
11053         * location values. Override install location based on default
11054         * policy if needed and then create install arguments based
11055         * on the install location.
11056         */
11057        public void handleStartCopy() throws RemoteException {
11058            int ret = PackageManager.INSTALL_SUCCEEDED;
11059
11060            // If we're already staged, we've firmly committed to an install location
11061            if (origin.staged) {
11062                if (origin.file != null) {
11063                    installFlags |= PackageManager.INSTALL_INTERNAL;
11064                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11065                } else if (origin.cid != null) {
11066                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11067                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11068                } else {
11069                    throw new IllegalStateException("Invalid stage location");
11070                }
11071            }
11072
11073            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11074            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11075            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11076            PackageInfoLite pkgLite = null;
11077
11078            if (onInt && onSd) {
11079                // Check if both bits are set.
11080                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11081                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11082            } else if (onSd && ephemeral) {
11083                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11084                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11085            } else {
11086                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11087                        packageAbiOverride);
11088
11089                if (DEBUG_EPHEMERAL && ephemeral) {
11090                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11091                }
11092
11093                /*
11094                 * If we have too little free space, try to free cache
11095                 * before giving up.
11096                 */
11097                if (!origin.staged && pkgLite.recommendedInstallLocation
11098                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11099                    // TODO: focus freeing disk space on the target device
11100                    final StorageManager storage = StorageManager.from(mContext);
11101                    final long lowThreshold = storage.getStorageLowBytes(
11102                            Environment.getDataDirectory());
11103
11104                    final long sizeBytes = mContainerService.calculateInstalledSize(
11105                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11106
11107                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11108                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11109                                installFlags, packageAbiOverride);
11110                    }
11111
11112                    /*
11113                     * The cache free must have deleted the file we
11114                     * downloaded to install.
11115                     *
11116                     * TODO: fix the "freeCache" call to not delete
11117                     *       the file we care about.
11118                     */
11119                    if (pkgLite.recommendedInstallLocation
11120                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11121                        pkgLite.recommendedInstallLocation
11122                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11123                    }
11124                }
11125            }
11126
11127            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11128                int loc = pkgLite.recommendedInstallLocation;
11129                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11130                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11131                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11132                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11133                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11134                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11135                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11136                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11137                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11138                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11139                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11140                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11141                } else {
11142                    // Override with defaults if needed.
11143                    loc = installLocationPolicy(pkgLite);
11144                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11145                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11146                    } else if (!onSd && !onInt) {
11147                        // Override install location with flags
11148                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11149                            // Set the flag to install on external media.
11150                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11151                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11152                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11153                            if (DEBUG_EPHEMERAL) {
11154                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11155                            }
11156                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11157                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11158                                    |PackageManager.INSTALL_INTERNAL);
11159                        } else {
11160                            // Make sure the flag for installing on external
11161                            // media is unset
11162                            installFlags |= PackageManager.INSTALL_INTERNAL;
11163                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11164                        }
11165                    }
11166                }
11167            }
11168
11169            final InstallArgs args = createInstallArgs(this);
11170            mArgs = args;
11171
11172            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11173                // TODO: http://b/22976637
11174                // Apps installed for "all" users use the device owner to verify the app
11175                UserHandle verifierUser = getUser();
11176                if (verifierUser == UserHandle.ALL) {
11177                    verifierUser = UserHandle.SYSTEM;
11178                }
11179
11180                /*
11181                 * Determine if we have any installed package verifiers. If we
11182                 * do, then we'll defer to them to verify the packages.
11183                 */
11184                final int requiredUid = mRequiredVerifierPackage == null ? -1
11185                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11186                if (!origin.existing && requiredUid != -1
11187                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11188                    final Intent verification = new Intent(
11189                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11190                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11191                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11192                            PACKAGE_MIME_TYPE);
11193                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11194
11195                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11196                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11197                            verifierUser.getIdentifier());
11198
11199                    if (DEBUG_VERIFY) {
11200                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11201                                + verification.toString() + " with " + pkgLite.verifiers.length
11202                                + " optional verifiers");
11203                    }
11204
11205                    final int verificationId = mPendingVerificationToken++;
11206
11207                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11208
11209                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11210                            installerPackageName);
11211
11212                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11213                            installFlags);
11214
11215                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11216                            pkgLite.packageName);
11217
11218                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11219                            pkgLite.versionCode);
11220
11221                    if (verificationParams != null) {
11222                        if (verificationParams.getVerificationURI() != null) {
11223                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11224                                 verificationParams.getVerificationURI());
11225                        }
11226                        if (verificationParams.getOriginatingURI() != null) {
11227                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11228                                  verificationParams.getOriginatingURI());
11229                        }
11230                        if (verificationParams.getReferrer() != null) {
11231                            verification.putExtra(Intent.EXTRA_REFERRER,
11232                                  verificationParams.getReferrer());
11233                        }
11234                        if (verificationParams.getOriginatingUid() >= 0) {
11235                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11236                                  verificationParams.getOriginatingUid());
11237                        }
11238                        if (verificationParams.getInstallerUid() >= 0) {
11239                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11240                                  verificationParams.getInstallerUid());
11241                        }
11242                    }
11243
11244                    final PackageVerificationState verificationState = new PackageVerificationState(
11245                            requiredUid, args);
11246
11247                    mPendingVerification.append(verificationId, verificationState);
11248
11249                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11250                            receivers, verificationState);
11251
11252                    /*
11253                     * If any sufficient verifiers were listed in the package
11254                     * manifest, attempt to ask them.
11255                     */
11256                    if (sufficientVerifiers != null) {
11257                        final int N = sufficientVerifiers.size();
11258                        if (N == 0) {
11259                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11260                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11261                        } else {
11262                            for (int i = 0; i < N; i++) {
11263                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11264
11265                                final Intent sufficientIntent = new Intent(verification);
11266                                sufficientIntent.setComponent(verifierComponent);
11267                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11268                            }
11269                        }
11270                    }
11271
11272                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11273                            mRequiredVerifierPackage, receivers);
11274                    if (ret == PackageManager.INSTALL_SUCCEEDED
11275                            && mRequiredVerifierPackage != null) {
11276                        Trace.asyncTraceBegin(
11277                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11278                        /*
11279                         * Send the intent to the required verification agent,
11280                         * but only start the verification timeout after the
11281                         * target BroadcastReceivers have run.
11282                         */
11283                        verification.setComponent(requiredVerifierComponent);
11284                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11285                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11286                                new BroadcastReceiver() {
11287                                    @Override
11288                                    public void onReceive(Context context, Intent intent) {
11289                                        final Message msg = mHandler
11290                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11291                                        msg.arg1 = verificationId;
11292                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11293                                    }
11294                                }, null, 0, null, null);
11295
11296                        /*
11297                         * We don't want the copy to proceed until verification
11298                         * succeeds, so null out this field.
11299                         */
11300                        mArgs = null;
11301                    }
11302                } else {
11303                    /*
11304                     * No package verification is enabled, so immediately start
11305                     * the remote call to initiate copy using temporary file.
11306                     */
11307                    ret = args.copyApk(mContainerService, true);
11308                }
11309            }
11310
11311            mRet = ret;
11312        }
11313
11314        @Override
11315        void handleReturnCode() {
11316            // If mArgs is null, then MCS couldn't be reached. When it
11317            // reconnects, it will try again to install. At that point, this
11318            // will succeed.
11319            if (mArgs != null) {
11320                processPendingInstall(mArgs, mRet);
11321            }
11322        }
11323
11324        @Override
11325        void handleServiceError() {
11326            mArgs = createInstallArgs(this);
11327            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11328        }
11329
11330        public boolean isForwardLocked() {
11331            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11332        }
11333    }
11334
11335    /**
11336     * Used during creation of InstallArgs
11337     *
11338     * @param installFlags package installation flags
11339     * @return true if should be installed on external storage
11340     */
11341    private static boolean installOnExternalAsec(int installFlags) {
11342        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11343            return false;
11344        }
11345        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11346            return true;
11347        }
11348        return false;
11349    }
11350
11351    /**
11352     * Used during creation of InstallArgs
11353     *
11354     * @param installFlags package installation flags
11355     * @return true if should be installed as forward locked
11356     */
11357    private static boolean installForwardLocked(int installFlags) {
11358        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11359    }
11360
11361    private InstallArgs createInstallArgs(InstallParams params) {
11362        if (params.move != null) {
11363            return new MoveInstallArgs(params);
11364        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11365            return new AsecInstallArgs(params);
11366        } else {
11367            return new FileInstallArgs(params);
11368        }
11369    }
11370
11371    /**
11372     * Create args that describe an existing installed package. Typically used
11373     * when cleaning up old installs, or used as a move source.
11374     */
11375    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11376            String resourcePath, String[] instructionSets) {
11377        final boolean isInAsec;
11378        if (installOnExternalAsec(installFlags)) {
11379            /* Apps on SD card are always in ASEC containers. */
11380            isInAsec = true;
11381        } else if (installForwardLocked(installFlags)
11382                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11383            /*
11384             * Forward-locked apps are only in ASEC containers if they're the
11385             * new style
11386             */
11387            isInAsec = true;
11388        } else {
11389            isInAsec = false;
11390        }
11391
11392        if (isInAsec) {
11393            return new AsecInstallArgs(codePath, instructionSets,
11394                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11395        } else {
11396            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11397        }
11398    }
11399
11400    static abstract class InstallArgs {
11401        /** @see InstallParams#origin */
11402        final OriginInfo origin;
11403        /** @see InstallParams#move */
11404        final MoveInfo move;
11405
11406        final IPackageInstallObserver2 observer;
11407        // Always refers to PackageManager flags only
11408        final int installFlags;
11409        final String installerPackageName;
11410        final String volumeUuid;
11411        final ManifestDigest manifestDigest;
11412        final UserHandle user;
11413        final String abiOverride;
11414        final String[] installGrantPermissions;
11415        /** If non-null, drop an async trace when the install completes */
11416        final String traceMethod;
11417        final int traceCookie;
11418
11419        // The list of instruction sets supported by this app. This is currently
11420        // only used during the rmdex() phase to clean up resources. We can get rid of this
11421        // if we move dex files under the common app path.
11422        /* nullable */ String[] instructionSets;
11423
11424        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11425                int installFlags, String installerPackageName, String volumeUuid,
11426                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11427                String abiOverride, String[] installGrantPermissions,
11428                String traceMethod, int traceCookie) {
11429            this.origin = origin;
11430            this.move = move;
11431            this.installFlags = installFlags;
11432            this.observer = observer;
11433            this.installerPackageName = installerPackageName;
11434            this.volumeUuid = volumeUuid;
11435            this.manifestDigest = manifestDigest;
11436            this.user = user;
11437            this.instructionSets = instructionSets;
11438            this.abiOverride = abiOverride;
11439            this.installGrantPermissions = installGrantPermissions;
11440            this.traceMethod = traceMethod;
11441            this.traceCookie = traceCookie;
11442        }
11443
11444        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11445        abstract int doPreInstall(int status);
11446
11447        /**
11448         * Rename package into final resting place. All paths on the given
11449         * scanned package should be updated to reflect the rename.
11450         */
11451        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11452        abstract int doPostInstall(int status, int uid);
11453
11454        /** @see PackageSettingBase#codePathString */
11455        abstract String getCodePath();
11456        /** @see PackageSettingBase#resourcePathString */
11457        abstract String getResourcePath();
11458
11459        // Need installer lock especially for dex file removal.
11460        abstract void cleanUpResourcesLI();
11461        abstract boolean doPostDeleteLI(boolean delete);
11462
11463        /**
11464         * Called before the source arguments are copied. This is used mostly
11465         * for MoveParams when it needs to read the source file to put it in the
11466         * destination.
11467         */
11468        int doPreCopy() {
11469            return PackageManager.INSTALL_SUCCEEDED;
11470        }
11471
11472        /**
11473         * Called after the source arguments are copied. This is used mostly for
11474         * MoveParams when it needs to read the source file to put it in the
11475         * destination.
11476         *
11477         * @return
11478         */
11479        int doPostCopy(int uid) {
11480            return PackageManager.INSTALL_SUCCEEDED;
11481        }
11482
11483        protected boolean isFwdLocked() {
11484            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11485        }
11486
11487        protected boolean isExternalAsec() {
11488            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11489        }
11490
11491        protected boolean isEphemeral() {
11492            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11493        }
11494
11495        UserHandle getUser() {
11496            return user;
11497        }
11498    }
11499
11500    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11501        if (!allCodePaths.isEmpty()) {
11502            if (instructionSets == null) {
11503                throw new IllegalStateException("instructionSet == null");
11504            }
11505            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11506            for (String codePath : allCodePaths) {
11507                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11508                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11509                    if (retCode < 0) {
11510                        Slog.w(TAG, "Couldn't remove dex file for package: "
11511                                + " at location " + codePath + ", retcode=" + retCode);
11512                        // we don't consider this to be a failure of the core package deletion
11513                    }
11514                }
11515            }
11516        }
11517    }
11518
11519    /**
11520     * Logic to handle installation of non-ASEC applications, including copying
11521     * and renaming logic.
11522     */
11523    class FileInstallArgs extends InstallArgs {
11524        private File codeFile;
11525        private File resourceFile;
11526
11527        // Example topology:
11528        // /data/app/com.example/base.apk
11529        // /data/app/com.example/split_foo.apk
11530        // /data/app/com.example/lib/arm/libfoo.so
11531        // /data/app/com.example/lib/arm64/libfoo.so
11532        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11533
11534        /** New install */
11535        FileInstallArgs(InstallParams params) {
11536            super(params.origin, params.move, params.observer, params.installFlags,
11537                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11538                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11539                    params.grantedRuntimePermissions,
11540                    params.traceMethod, params.traceCookie);
11541            if (isFwdLocked()) {
11542                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11543            }
11544        }
11545
11546        /** Existing install */
11547        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11548            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11549                    null, null, null, 0);
11550            this.codeFile = (codePath != null) ? new File(codePath) : null;
11551            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11552        }
11553
11554        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11555            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11556            try {
11557                return doCopyApk(imcs, temp);
11558            } finally {
11559                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11560            }
11561        }
11562
11563        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11564            if (origin.staged) {
11565                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11566                codeFile = origin.file;
11567                resourceFile = origin.file;
11568                return PackageManager.INSTALL_SUCCEEDED;
11569            }
11570
11571            try {
11572                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11573                final File tempDir =
11574                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11575                codeFile = tempDir;
11576                resourceFile = tempDir;
11577            } catch (IOException e) {
11578                Slog.w(TAG, "Failed to create copy file: " + e);
11579                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11580            }
11581
11582            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11583                @Override
11584                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11585                    if (!FileUtils.isValidExtFilename(name)) {
11586                        throw new IllegalArgumentException("Invalid filename: " + name);
11587                    }
11588                    try {
11589                        final File file = new File(codeFile, name);
11590                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11591                                O_RDWR | O_CREAT, 0644);
11592                        Os.chmod(file.getAbsolutePath(), 0644);
11593                        return new ParcelFileDescriptor(fd);
11594                    } catch (ErrnoException e) {
11595                        throw new RemoteException("Failed to open: " + e.getMessage());
11596                    }
11597                }
11598            };
11599
11600            int ret = PackageManager.INSTALL_SUCCEEDED;
11601            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11602            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11603                Slog.e(TAG, "Failed to copy package");
11604                return ret;
11605            }
11606
11607            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11608            NativeLibraryHelper.Handle handle = null;
11609            try {
11610                handle = NativeLibraryHelper.Handle.create(codeFile);
11611                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11612                        abiOverride);
11613            } catch (IOException e) {
11614                Slog.e(TAG, "Copying native libraries failed", e);
11615                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11616            } finally {
11617                IoUtils.closeQuietly(handle);
11618            }
11619
11620            return ret;
11621        }
11622
11623        int doPreInstall(int status) {
11624            if (status != PackageManager.INSTALL_SUCCEEDED) {
11625                cleanUp();
11626            }
11627            return status;
11628        }
11629
11630        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11631            if (status != PackageManager.INSTALL_SUCCEEDED) {
11632                cleanUp();
11633                return false;
11634            }
11635
11636            final File targetDir = codeFile.getParentFile();
11637            final File beforeCodeFile = codeFile;
11638            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11639
11640            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11641            try {
11642                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11643            } catch (ErrnoException e) {
11644                Slog.w(TAG, "Failed to rename", e);
11645                return false;
11646            }
11647
11648            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11649                Slog.w(TAG, "Failed to restorecon");
11650                return false;
11651            }
11652
11653            // Reflect the rename internally
11654            codeFile = afterCodeFile;
11655            resourceFile = afterCodeFile;
11656
11657            // Reflect the rename in scanned details
11658            pkg.codePath = afterCodeFile.getAbsolutePath();
11659            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11660                    pkg.baseCodePath);
11661            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11662                    pkg.splitCodePaths);
11663
11664            // Reflect the rename in app info
11665            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11666            pkg.applicationInfo.setCodePath(pkg.codePath);
11667            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11668            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11669            pkg.applicationInfo.setResourcePath(pkg.codePath);
11670            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11671            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11672
11673            return true;
11674        }
11675
11676        int doPostInstall(int status, int uid) {
11677            if (status != PackageManager.INSTALL_SUCCEEDED) {
11678                cleanUp();
11679            }
11680            return status;
11681        }
11682
11683        @Override
11684        String getCodePath() {
11685            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11686        }
11687
11688        @Override
11689        String getResourcePath() {
11690            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11691        }
11692
11693        private boolean cleanUp() {
11694            if (codeFile == null || !codeFile.exists()) {
11695                return false;
11696            }
11697
11698            if (codeFile.isDirectory()) {
11699                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11700            } else {
11701                codeFile.delete();
11702            }
11703
11704            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11705                resourceFile.delete();
11706            }
11707
11708            return true;
11709        }
11710
11711        void cleanUpResourcesLI() {
11712            // Try enumerating all code paths before deleting
11713            List<String> allCodePaths = Collections.EMPTY_LIST;
11714            if (codeFile != null && codeFile.exists()) {
11715                try {
11716                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11717                    allCodePaths = pkg.getAllCodePaths();
11718                } catch (PackageParserException e) {
11719                    // Ignored; we tried our best
11720                }
11721            }
11722
11723            cleanUp();
11724            removeDexFiles(allCodePaths, instructionSets);
11725        }
11726
11727        boolean doPostDeleteLI(boolean delete) {
11728            // XXX err, shouldn't we respect the delete flag?
11729            cleanUpResourcesLI();
11730            return true;
11731        }
11732    }
11733
11734    private boolean isAsecExternal(String cid) {
11735        final String asecPath = PackageHelper.getSdFilesystem(cid);
11736        return !asecPath.startsWith(mAsecInternalPath);
11737    }
11738
11739    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11740            PackageManagerException {
11741        if (copyRet < 0) {
11742            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11743                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11744                throw new PackageManagerException(copyRet, message);
11745            }
11746        }
11747    }
11748
11749    /**
11750     * Extract the MountService "container ID" from the full code path of an
11751     * .apk.
11752     */
11753    static String cidFromCodePath(String fullCodePath) {
11754        int eidx = fullCodePath.lastIndexOf("/");
11755        String subStr1 = fullCodePath.substring(0, eidx);
11756        int sidx = subStr1.lastIndexOf("/");
11757        return subStr1.substring(sidx+1, eidx);
11758    }
11759
11760    /**
11761     * Logic to handle installation of ASEC applications, including copying and
11762     * renaming logic.
11763     */
11764    class AsecInstallArgs extends InstallArgs {
11765        static final String RES_FILE_NAME = "pkg.apk";
11766        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11767
11768        String cid;
11769        String packagePath;
11770        String resourcePath;
11771
11772        /** New install */
11773        AsecInstallArgs(InstallParams params) {
11774            super(params.origin, params.move, params.observer, params.installFlags,
11775                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11776                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11777                    params.grantedRuntimePermissions,
11778                    params.traceMethod, params.traceCookie);
11779        }
11780
11781        /** Existing install */
11782        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11783                        boolean isExternal, boolean isForwardLocked) {
11784            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11785                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11786                    instructionSets, null, null, null, 0);
11787            // Hackily pretend we're still looking at a full code path
11788            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11789                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11790            }
11791
11792            // Extract cid from fullCodePath
11793            int eidx = fullCodePath.lastIndexOf("/");
11794            String subStr1 = fullCodePath.substring(0, eidx);
11795            int sidx = subStr1.lastIndexOf("/");
11796            cid = subStr1.substring(sidx+1, eidx);
11797            setMountPath(subStr1);
11798        }
11799
11800        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11801            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11802                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11803                    instructionSets, null, null, null, 0);
11804            this.cid = cid;
11805            setMountPath(PackageHelper.getSdDir(cid));
11806        }
11807
11808        void createCopyFile() {
11809            cid = mInstallerService.allocateExternalStageCidLegacy();
11810        }
11811
11812        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11813            if (origin.staged && origin.cid != null) {
11814                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11815                cid = origin.cid;
11816                setMountPath(PackageHelper.getSdDir(cid));
11817                return PackageManager.INSTALL_SUCCEEDED;
11818            }
11819
11820            if (temp) {
11821                createCopyFile();
11822            } else {
11823                /*
11824                 * Pre-emptively destroy the container since it's destroyed if
11825                 * copying fails due to it existing anyway.
11826                 */
11827                PackageHelper.destroySdDir(cid);
11828            }
11829
11830            final String newMountPath = imcs.copyPackageToContainer(
11831                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11832                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11833
11834            if (newMountPath != null) {
11835                setMountPath(newMountPath);
11836                return PackageManager.INSTALL_SUCCEEDED;
11837            } else {
11838                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11839            }
11840        }
11841
11842        @Override
11843        String getCodePath() {
11844            return packagePath;
11845        }
11846
11847        @Override
11848        String getResourcePath() {
11849            return resourcePath;
11850        }
11851
11852        int doPreInstall(int status) {
11853            if (status != PackageManager.INSTALL_SUCCEEDED) {
11854                // Destroy container
11855                PackageHelper.destroySdDir(cid);
11856            } else {
11857                boolean mounted = PackageHelper.isContainerMounted(cid);
11858                if (!mounted) {
11859                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11860                            Process.SYSTEM_UID);
11861                    if (newMountPath != null) {
11862                        setMountPath(newMountPath);
11863                    } else {
11864                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11865                    }
11866                }
11867            }
11868            return status;
11869        }
11870
11871        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11872            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11873            String newMountPath = null;
11874            if (PackageHelper.isContainerMounted(cid)) {
11875                // Unmount the container
11876                if (!PackageHelper.unMountSdDir(cid)) {
11877                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11878                    return false;
11879                }
11880            }
11881            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11882                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11883                        " which might be stale. Will try to clean up.");
11884                // Clean up the stale container and proceed to recreate.
11885                if (!PackageHelper.destroySdDir(newCacheId)) {
11886                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11887                    return false;
11888                }
11889                // Successfully cleaned up stale container. Try to rename again.
11890                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11891                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11892                            + " inspite of cleaning it up.");
11893                    return false;
11894                }
11895            }
11896            if (!PackageHelper.isContainerMounted(newCacheId)) {
11897                Slog.w(TAG, "Mounting container " + newCacheId);
11898                newMountPath = PackageHelper.mountSdDir(newCacheId,
11899                        getEncryptKey(), Process.SYSTEM_UID);
11900            } else {
11901                newMountPath = PackageHelper.getSdDir(newCacheId);
11902            }
11903            if (newMountPath == null) {
11904                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11905                return false;
11906            }
11907            Log.i(TAG, "Succesfully renamed " + cid +
11908                    " to " + newCacheId +
11909                    " at new path: " + newMountPath);
11910            cid = newCacheId;
11911
11912            final File beforeCodeFile = new File(packagePath);
11913            setMountPath(newMountPath);
11914            final File afterCodeFile = new File(packagePath);
11915
11916            // Reflect the rename in scanned details
11917            pkg.codePath = afterCodeFile.getAbsolutePath();
11918            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11919                    pkg.baseCodePath);
11920            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11921                    pkg.splitCodePaths);
11922
11923            // Reflect the rename in app info
11924            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11925            pkg.applicationInfo.setCodePath(pkg.codePath);
11926            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11927            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11928            pkg.applicationInfo.setResourcePath(pkg.codePath);
11929            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11930            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11931
11932            return true;
11933        }
11934
11935        private void setMountPath(String mountPath) {
11936            final File mountFile = new File(mountPath);
11937
11938            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11939            if (monolithicFile.exists()) {
11940                packagePath = monolithicFile.getAbsolutePath();
11941                if (isFwdLocked()) {
11942                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11943                } else {
11944                    resourcePath = packagePath;
11945                }
11946            } else {
11947                packagePath = mountFile.getAbsolutePath();
11948                resourcePath = packagePath;
11949            }
11950        }
11951
11952        int doPostInstall(int status, int uid) {
11953            if (status != PackageManager.INSTALL_SUCCEEDED) {
11954                cleanUp();
11955            } else {
11956                final int groupOwner;
11957                final String protectedFile;
11958                if (isFwdLocked()) {
11959                    groupOwner = UserHandle.getSharedAppGid(uid);
11960                    protectedFile = RES_FILE_NAME;
11961                } else {
11962                    groupOwner = -1;
11963                    protectedFile = null;
11964                }
11965
11966                if (uid < Process.FIRST_APPLICATION_UID
11967                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11968                    Slog.e(TAG, "Failed to finalize " + cid);
11969                    PackageHelper.destroySdDir(cid);
11970                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11971                }
11972
11973                boolean mounted = PackageHelper.isContainerMounted(cid);
11974                if (!mounted) {
11975                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11976                }
11977            }
11978            return status;
11979        }
11980
11981        private void cleanUp() {
11982            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11983
11984            // Destroy secure container
11985            PackageHelper.destroySdDir(cid);
11986        }
11987
11988        private List<String> getAllCodePaths() {
11989            final File codeFile = new File(getCodePath());
11990            if (codeFile != null && codeFile.exists()) {
11991                try {
11992                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11993                    return pkg.getAllCodePaths();
11994                } catch (PackageParserException e) {
11995                    // Ignored; we tried our best
11996                }
11997            }
11998            return Collections.EMPTY_LIST;
11999        }
12000
12001        void cleanUpResourcesLI() {
12002            // Enumerate all code paths before deleting
12003            cleanUpResourcesLI(getAllCodePaths());
12004        }
12005
12006        private void cleanUpResourcesLI(List<String> allCodePaths) {
12007            cleanUp();
12008            removeDexFiles(allCodePaths, instructionSets);
12009        }
12010
12011        String getPackageName() {
12012            return getAsecPackageName(cid);
12013        }
12014
12015        boolean doPostDeleteLI(boolean delete) {
12016            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12017            final List<String> allCodePaths = getAllCodePaths();
12018            boolean mounted = PackageHelper.isContainerMounted(cid);
12019            if (mounted) {
12020                // Unmount first
12021                if (PackageHelper.unMountSdDir(cid)) {
12022                    mounted = false;
12023                }
12024            }
12025            if (!mounted && delete) {
12026                cleanUpResourcesLI(allCodePaths);
12027            }
12028            return !mounted;
12029        }
12030
12031        @Override
12032        int doPreCopy() {
12033            if (isFwdLocked()) {
12034                if (!PackageHelper.fixSdPermissions(cid,
12035                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12036                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12037                }
12038            }
12039
12040            return PackageManager.INSTALL_SUCCEEDED;
12041        }
12042
12043        @Override
12044        int doPostCopy(int uid) {
12045            if (isFwdLocked()) {
12046                if (uid < Process.FIRST_APPLICATION_UID
12047                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12048                                RES_FILE_NAME)) {
12049                    Slog.e(TAG, "Failed to finalize " + cid);
12050                    PackageHelper.destroySdDir(cid);
12051                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12052                }
12053            }
12054
12055            return PackageManager.INSTALL_SUCCEEDED;
12056        }
12057    }
12058
12059    /**
12060     * Logic to handle movement of existing installed applications.
12061     */
12062    class MoveInstallArgs extends InstallArgs {
12063        private File codeFile;
12064        private File resourceFile;
12065
12066        /** New install */
12067        MoveInstallArgs(InstallParams params) {
12068            super(params.origin, params.move, params.observer, params.installFlags,
12069                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
12070                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12071                    params.grantedRuntimePermissions,
12072                    params.traceMethod, params.traceCookie);
12073        }
12074
12075        int copyApk(IMediaContainerService imcs, boolean temp) {
12076            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12077                    + move.fromUuid + " to " + move.toUuid);
12078            synchronized (mInstaller) {
12079                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12080                        move.dataAppName, move.appId, move.seinfo) != 0) {
12081                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12082                }
12083            }
12084
12085            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12086            resourceFile = codeFile;
12087            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12088
12089            return PackageManager.INSTALL_SUCCEEDED;
12090        }
12091
12092        int doPreInstall(int status) {
12093            if (status != PackageManager.INSTALL_SUCCEEDED) {
12094                cleanUp(move.toUuid);
12095            }
12096            return status;
12097        }
12098
12099        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12100            if (status != PackageManager.INSTALL_SUCCEEDED) {
12101                cleanUp(move.toUuid);
12102                return false;
12103            }
12104
12105            // Reflect the move in app info
12106            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12107            pkg.applicationInfo.setCodePath(pkg.codePath);
12108            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12109            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12110            pkg.applicationInfo.setResourcePath(pkg.codePath);
12111            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12112            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12113
12114            return true;
12115        }
12116
12117        int doPostInstall(int status, int uid) {
12118            if (status == PackageManager.INSTALL_SUCCEEDED) {
12119                cleanUp(move.fromUuid);
12120            } else {
12121                cleanUp(move.toUuid);
12122            }
12123            return status;
12124        }
12125
12126        @Override
12127        String getCodePath() {
12128            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12129        }
12130
12131        @Override
12132        String getResourcePath() {
12133            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12134        }
12135
12136        private boolean cleanUp(String volumeUuid) {
12137            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12138                    move.dataAppName);
12139            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12140            synchronized (mInstallLock) {
12141                // Clean up both app data and code
12142                removeDataDirsLI(volumeUuid, move.packageName);
12143                if (codeFile.isDirectory()) {
12144                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12145                } else {
12146                    codeFile.delete();
12147                }
12148            }
12149            return true;
12150        }
12151
12152        void cleanUpResourcesLI() {
12153            throw new UnsupportedOperationException();
12154        }
12155
12156        boolean doPostDeleteLI(boolean delete) {
12157            throw new UnsupportedOperationException();
12158        }
12159    }
12160
12161    static String getAsecPackageName(String packageCid) {
12162        int idx = packageCid.lastIndexOf("-");
12163        if (idx == -1) {
12164            return packageCid;
12165        }
12166        return packageCid.substring(0, idx);
12167    }
12168
12169    // Utility method used to create code paths based on package name and available index.
12170    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12171        String idxStr = "";
12172        int idx = 1;
12173        // Fall back to default value of idx=1 if prefix is not
12174        // part of oldCodePath
12175        if (oldCodePath != null) {
12176            String subStr = oldCodePath;
12177            // Drop the suffix right away
12178            if (suffix != null && subStr.endsWith(suffix)) {
12179                subStr = subStr.substring(0, subStr.length() - suffix.length());
12180            }
12181            // If oldCodePath already contains prefix find out the
12182            // ending index to either increment or decrement.
12183            int sidx = subStr.lastIndexOf(prefix);
12184            if (sidx != -1) {
12185                subStr = subStr.substring(sidx + prefix.length());
12186                if (subStr != null) {
12187                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12188                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12189                    }
12190                    try {
12191                        idx = Integer.parseInt(subStr);
12192                        if (idx <= 1) {
12193                            idx++;
12194                        } else {
12195                            idx--;
12196                        }
12197                    } catch(NumberFormatException e) {
12198                    }
12199                }
12200            }
12201        }
12202        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12203        return prefix + idxStr;
12204    }
12205
12206    private File getNextCodePath(File targetDir, String packageName) {
12207        int suffix = 1;
12208        File result;
12209        do {
12210            result = new File(targetDir, packageName + "-" + suffix);
12211            suffix++;
12212        } while (result.exists());
12213        return result;
12214    }
12215
12216    // Utility method that returns the relative package path with respect
12217    // to the installation directory. Like say for /data/data/com.test-1.apk
12218    // string com.test-1 is returned.
12219    static String deriveCodePathName(String codePath) {
12220        if (codePath == null) {
12221            return null;
12222        }
12223        final File codeFile = new File(codePath);
12224        final String name = codeFile.getName();
12225        if (codeFile.isDirectory()) {
12226            return name;
12227        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12228            final int lastDot = name.lastIndexOf('.');
12229            return name.substring(0, lastDot);
12230        } else {
12231            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12232            return null;
12233        }
12234    }
12235
12236    static class PackageInstalledInfo {
12237        String name;
12238        int uid;
12239        // The set of users that originally had this package installed.
12240        int[] origUsers;
12241        // The set of users that now have this package installed.
12242        int[] newUsers;
12243        PackageParser.Package pkg;
12244        int returnCode;
12245        String returnMsg;
12246        PackageRemovedInfo removedInfo;
12247
12248        public void setError(int code, String msg) {
12249            returnCode = code;
12250            returnMsg = msg;
12251            Slog.w(TAG, msg);
12252        }
12253
12254        public void setError(String msg, PackageParserException e) {
12255            returnCode = e.error;
12256            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12257            Slog.w(TAG, msg, e);
12258        }
12259
12260        public void setError(String msg, PackageManagerException e) {
12261            returnCode = e.error;
12262            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12263            Slog.w(TAG, msg, e);
12264        }
12265
12266        // In some error cases we want to convey more info back to the observer
12267        String origPackage;
12268        String origPermission;
12269    }
12270
12271    /*
12272     * Install a non-existing package.
12273     */
12274    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12275            UserHandle user, String installerPackageName, String volumeUuid,
12276            PackageInstalledInfo res) {
12277        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12278
12279        // Remember this for later, in case we need to rollback this install
12280        String pkgName = pkg.packageName;
12281
12282        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12283        // TODO: b/23350563
12284        final boolean dataDirExists = Environment
12285                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12286
12287        synchronized(mPackages) {
12288            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12289                // A package with the same name is already installed, though
12290                // it has been renamed to an older name.  The package we
12291                // are trying to install should be installed as an update to
12292                // the existing one, but that has not been requested, so bail.
12293                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12294                        + " without first uninstalling package running as "
12295                        + mSettings.mRenamedPackages.get(pkgName));
12296                return;
12297            }
12298            if (mPackages.containsKey(pkgName)) {
12299                // Don't allow installation over an existing package with the same name.
12300                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12301                        + " without first uninstalling.");
12302                return;
12303            }
12304        }
12305
12306        try {
12307            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12308                    System.currentTimeMillis(), user);
12309
12310            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12311            // delete the partially installed application. the data directory will have to be
12312            // restored if it was already existing
12313            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12314                // remove package from internal structures.  Note that we want deletePackageX to
12315                // delete the package data and cache directories that it created in
12316                // scanPackageLocked, unless those directories existed before we even tried to
12317                // install.
12318                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12319                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12320                                res.removedInfo, true);
12321            }
12322
12323        } catch (PackageManagerException e) {
12324            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12325        }
12326
12327        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12328    }
12329
12330    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12331        // Can't rotate keys during boot or if sharedUser.
12332        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12333                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12334            return false;
12335        }
12336        // app is using upgradeKeySets; make sure all are valid
12337        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12338        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12339        for (int i = 0; i < upgradeKeySets.length; i++) {
12340            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12341                Slog.wtf(TAG, "Package "
12342                         + (oldPs.name != null ? oldPs.name : "<null>")
12343                         + " contains upgrade-key-set reference to unknown key-set: "
12344                         + upgradeKeySets[i]
12345                         + " reverting to signatures check.");
12346                return false;
12347            }
12348        }
12349        return true;
12350    }
12351
12352    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12353        // Upgrade keysets are being used.  Determine if new package has a superset of the
12354        // required keys.
12355        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12356        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12357        for (int i = 0; i < upgradeKeySets.length; i++) {
12358            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12359            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12360                return true;
12361            }
12362        }
12363        return false;
12364    }
12365
12366    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12367            UserHandle user, String installerPackageName, String volumeUuid,
12368            PackageInstalledInfo res) {
12369        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12370
12371        final PackageParser.Package oldPackage;
12372        final String pkgName = pkg.packageName;
12373        final int[] allUsers;
12374        final boolean[] perUserInstalled;
12375
12376        // First find the old package info and check signatures
12377        synchronized(mPackages) {
12378            oldPackage = mPackages.get(pkgName);
12379            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12380            if (isEphemeral && !oldIsEphemeral) {
12381                // can't downgrade from full to ephemeral
12382                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12383                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12384                return;
12385            }
12386            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12387            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12388            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12389                if(!checkUpgradeKeySetLP(ps, pkg)) {
12390                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12391                            "New package not signed by keys specified by upgrade-keysets: "
12392                            + pkgName);
12393                    return;
12394                }
12395            } else {
12396                // default to original signature matching
12397                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12398                    != PackageManager.SIGNATURE_MATCH) {
12399                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12400                            "New package has a different signature: " + pkgName);
12401                    return;
12402                }
12403            }
12404
12405            // In case of rollback, remember per-user/profile install state
12406            allUsers = sUserManager.getUserIds();
12407            perUserInstalled = new boolean[allUsers.length];
12408            for (int i = 0; i < allUsers.length; i++) {
12409                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12410            }
12411        }
12412
12413        boolean sysPkg = (isSystemApp(oldPackage));
12414        if (sysPkg) {
12415            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12416                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12417        } else {
12418            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12419                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12420        }
12421    }
12422
12423    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12424            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12425            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12426            String volumeUuid, PackageInstalledInfo res) {
12427        String pkgName = deletedPackage.packageName;
12428        boolean deletedPkg = true;
12429        boolean updatedSettings = false;
12430
12431        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12432                + deletedPackage);
12433        long origUpdateTime;
12434        if (pkg.mExtras != null) {
12435            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12436        } else {
12437            origUpdateTime = 0;
12438        }
12439
12440        // First delete the existing package while retaining the data directory
12441        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12442                res.removedInfo, true)) {
12443            // If the existing package wasn't successfully deleted
12444            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12445            deletedPkg = false;
12446        } else {
12447            // Successfully deleted the old package; proceed with replace.
12448
12449            // If deleted package lived in a container, give users a chance to
12450            // relinquish resources before killing.
12451            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12452                if (DEBUG_INSTALL) {
12453                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12454                }
12455                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12456                final ArrayList<String> pkgList = new ArrayList<String>(1);
12457                pkgList.add(deletedPackage.applicationInfo.packageName);
12458                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12459            }
12460
12461            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12462            try {
12463                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12464                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12465                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12466                        perUserInstalled, res, user);
12467                updatedSettings = true;
12468            } catch (PackageManagerException e) {
12469                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12470            }
12471        }
12472
12473        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12474            // remove package from internal structures.  Note that we want deletePackageX to
12475            // delete the package data and cache directories that it created in
12476            // scanPackageLocked, unless those directories existed before we even tried to
12477            // install.
12478            if(updatedSettings) {
12479                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12480                deletePackageLI(
12481                        pkgName, null, true, allUsers, perUserInstalled,
12482                        PackageManager.DELETE_KEEP_DATA,
12483                                res.removedInfo, true);
12484            }
12485            // Since we failed to install the new package we need to restore the old
12486            // package that we deleted.
12487            if (deletedPkg) {
12488                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12489                File restoreFile = new File(deletedPackage.codePath);
12490                // Parse old package
12491                boolean oldExternal = isExternal(deletedPackage);
12492                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12493                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12494                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12495                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12496                try {
12497                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12498                            null);
12499                } catch (PackageManagerException e) {
12500                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12501                            + e.getMessage());
12502                    return;
12503                }
12504                // Restore of old package succeeded. Update permissions.
12505                // writer
12506                synchronized (mPackages) {
12507                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12508                            UPDATE_PERMISSIONS_ALL);
12509                    // can downgrade to reader
12510                    mSettings.writeLPr();
12511                }
12512                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12513            }
12514        }
12515    }
12516
12517    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12518            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12519            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12520            String volumeUuid, PackageInstalledInfo res) {
12521        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12522                + ", old=" + deletedPackage);
12523        boolean disabledSystem = false;
12524        boolean updatedSettings = false;
12525        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12526        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12527                != 0) {
12528            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12529        }
12530        String packageName = deletedPackage.packageName;
12531        if (packageName == null) {
12532            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12533                    "Attempt to delete null packageName.");
12534            return;
12535        }
12536        PackageParser.Package oldPkg;
12537        PackageSetting oldPkgSetting;
12538        // reader
12539        synchronized (mPackages) {
12540            oldPkg = mPackages.get(packageName);
12541            oldPkgSetting = mSettings.mPackages.get(packageName);
12542            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12543                    (oldPkgSetting == null)) {
12544                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12545                        "Couldn't find package:" + packageName + " information");
12546                return;
12547            }
12548        }
12549
12550        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12551
12552        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12553        res.removedInfo.removedPackage = packageName;
12554        // Remove existing system package
12555        removePackageLI(oldPkgSetting, true);
12556        // writer
12557        synchronized (mPackages) {
12558            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12559            if (!disabledSystem && deletedPackage != null) {
12560                // We didn't need to disable the .apk as a current system package,
12561                // which means we are replacing another update that is already
12562                // installed.  We need to make sure to delete the older one's .apk.
12563                res.removedInfo.args = createInstallArgsForExisting(0,
12564                        deletedPackage.applicationInfo.getCodePath(),
12565                        deletedPackage.applicationInfo.getResourcePath(),
12566                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12567            } else {
12568                res.removedInfo.args = null;
12569            }
12570        }
12571
12572        // Successfully disabled the old package. Now proceed with re-installation
12573        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12574
12575        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12576        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12577
12578        PackageParser.Package newPackage = null;
12579        try {
12580            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12581            if (newPackage.mExtras != null) {
12582                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12583                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12584                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12585
12586                // is the update attempting to change shared user? that isn't going to work...
12587                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12588                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12589                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12590                            + " to " + newPkgSetting.sharedUser);
12591                    updatedSettings = true;
12592                }
12593            }
12594
12595            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12596                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12597                        perUserInstalled, res, user);
12598                updatedSettings = true;
12599            }
12600
12601        } catch (PackageManagerException e) {
12602            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12603        }
12604
12605        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12606            // Re installation failed. Restore old information
12607            // Remove new pkg information
12608            if (newPackage != null) {
12609                removeInstalledPackageLI(newPackage, true);
12610            }
12611            // Add back the old system package
12612            try {
12613                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12614            } catch (PackageManagerException e) {
12615                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12616            }
12617            // Restore the old system information in Settings
12618            synchronized (mPackages) {
12619                if (disabledSystem) {
12620                    mSettings.enableSystemPackageLPw(packageName);
12621                }
12622                if (updatedSettings) {
12623                    mSettings.setInstallerPackageName(packageName,
12624                            oldPkgSetting.installerPackageName);
12625                }
12626                mSettings.writeLPr();
12627            }
12628        }
12629    }
12630
12631    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12632        // Collect all used permissions in the UID
12633        ArraySet<String> usedPermissions = new ArraySet<>();
12634        final int packageCount = su.packages.size();
12635        for (int i = 0; i < packageCount; i++) {
12636            PackageSetting ps = su.packages.valueAt(i);
12637            if (ps.pkg == null) {
12638                continue;
12639            }
12640            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12641            for (int j = 0; j < requestedPermCount; j++) {
12642                String permission = ps.pkg.requestedPermissions.get(j);
12643                BasePermission bp = mSettings.mPermissions.get(permission);
12644                if (bp != null) {
12645                    usedPermissions.add(permission);
12646                }
12647            }
12648        }
12649
12650        PermissionsState permissionsState = su.getPermissionsState();
12651        // Prune install permissions
12652        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12653        final int installPermCount = installPermStates.size();
12654        for (int i = installPermCount - 1; i >= 0;  i--) {
12655            PermissionState permissionState = installPermStates.get(i);
12656            if (!usedPermissions.contains(permissionState.getName())) {
12657                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12658                if (bp != null) {
12659                    permissionsState.revokeInstallPermission(bp);
12660                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12661                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12662                }
12663            }
12664        }
12665
12666        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12667
12668        // Prune runtime permissions
12669        for (int userId : allUserIds) {
12670            List<PermissionState> runtimePermStates = permissionsState
12671                    .getRuntimePermissionStates(userId);
12672            final int runtimePermCount = runtimePermStates.size();
12673            for (int i = runtimePermCount - 1; i >= 0; i--) {
12674                PermissionState permissionState = runtimePermStates.get(i);
12675                if (!usedPermissions.contains(permissionState.getName())) {
12676                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12677                    if (bp != null) {
12678                        permissionsState.revokeRuntimePermission(bp, userId);
12679                        permissionsState.updatePermissionFlags(bp, userId,
12680                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12681                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12682                                runtimePermissionChangedUserIds, userId);
12683                    }
12684                }
12685            }
12686        }
12687
12688        return runtimePermissionChangedUserIds;
12689    }
12690
12691    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12692            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12693            UserHandle user) {
12694        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12695
12696        String pkgName = newPackage.packageName;
12697        synchronized (mPackages) {
12698            //write settings. the installStatus will be incomplete at this stage.
12699            //note that the new package setting would have already been
12700            //added to mPackages. It hasn't been persisted yet.
12701            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12702            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12703            mSettings.writeLPr();
12704            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12705        }
12706
12707        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12708        synchronized (mPackages) {
12709            updatePermissionsLPw(newPackage.packageName, newPackage,
12710                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12711                            ? UPDATE_PERMISSIONS_ALL : 0));
12712            // For system-bundled packages, we assume that installing an upgraded version
12713            // of the package implies that the user actually wants to run that new code,
12714            // so we enable the package.
12715            PackageSetting ps = mSettings.mPackages.get(pkgName);
12716            if (ps != null) {
12717                if (isSystemApp(newPackage)) {
12718                    // NB: implicit assumption that system package upgrades apply to all users
12719                    if (DEBUG_INSTALL) {
12720                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12721                    }
12722                    if (res.origUsers != null) {
12723                        for (int userHandle : res.origUsers) {
12724                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12725                                    userHandle, installerPackageName);
12726                        }
12727                    }
12728                    // Also convey the prior install/uninstall state
12729                    if (allUsers != null && perUserInstalled != null) {
12730                        for (int i = 0; i < allUsers.length; i++) {
12731                            if (DEBUG_INSTALL) {
12732                                Slog.d(TAG, "    user " + allUsers[i]
12733                                        + " => " + perUserInstalled[i]);
12734                            }
12735                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12736                        }
12737                        // these install state changes will be persisted in the
12738                        // upcoming call to mSettings.writeLPr().
12739                    }
12740                }
12741                // It's implied that when a user requests installation, they want the app to be
12742                // installed and enabled.
12743                int userId = user.getIdentifier();
12744                if (userId != UserHandle.USER_ALL) {
12745                    ps.setInstalled(true, userId);
12746                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12747                }
12748            }
12749            res.name = pkgName;
12750            res.uid = newPackage.applicationInfo.uid;
12751            res.pkg = newPackage;
12752            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12753            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12754            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12755            //to update install status
12756            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12757            mSettings.writeLPr();
12758            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12759        }
12760
12761        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12762    }
12763
12764    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12765        try {
12766            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12767            installPackageLI(args, res);
12768        } finally {
12769            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12770        }
12771    }
12772
12773    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12774        final int installFlags = args.installFlags;
12775        final String installerPackageName = args.installerPackageName;
12776        final String volumeUuid = args.volumeUuid;
12777        final File tmpPackageFile = new File(args.getCodePath());
12778        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12779        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12780                || (args.volumeUuid != null));
12781        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12782        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12783        boolean replace = false;
12784        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12785        if (args.move != null) {
12786            // moving a complete application; perfom an initial scan on the new install location
12787            scanFlags |= SCAN_INITIAL;
12788        }
12789        // Result object to be returned
12790        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12791
12792        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12793
12794        // Sanity check
12795        if (ephemeral && (forwardLocked || onExternal)) {
12796            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12797                    + " external=" + onExternal);
12798            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12799            return;
12800        }
12801
12802        // Retrieve PackageSettings and parse package
12803        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12804                | PackageParser.PARSE_ENFORCE_CODE
12805                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12806                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12807                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0)
12808                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12809        PackageParser pp = new PackageParser();
12810        pp.setSeparateProcesses(mSeparateProcesses);
12811        pp.setDisplayMetrics(mMetrics);
12812
12813        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12814        final PackageParser.Package pkg;
12815        try {
12816            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12817        } catch (PackageParserException e) {
12818            res.setError("Failed parse during installPackageLI", e);
12819            return;
12820        } finally {
12821            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12822        }
12823
12824        // Mark that we have an install time CPU ABI override.
12825        pkg.cpuAbiOverride = args.abiOverride;
12826
12827        String pkgName = res.name = pkg.packageName;
12828        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12829            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12830                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12831                return;
12832            }
12833        }
12834
12835        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12836        try {
12837            pp.collectCertificates(pkg, parseFlags);
12838        } catch (PackageParserException e) {
12839            res.setError("Failed collect during installPackageLI", e);
12840            return;
12841        } finally {
12842            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12843        }
12844
12845        /* If the installer passed in a manifest digest, compare it now. */
12846        if (args.manifestDigest != null) {
12847            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12848            try {
12849                pp.collectManifestDigest(pkg);
12850            } catch (PackageParserException e) {
12851                res.setError("Failed collect during installPackageLI", e);
12852                return;
12853            } finally {
12854                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12855            }
12856
12857            if (DEBUG_INSTALL) {
12858                final String parsedManifest = pkg.manifestDigest == null ? "null"
12859                        : pkg.manifestDigest.toString();
12860                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12861                        + parsedManifest);
12862            }
12863
12864            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12865                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12866                return;
12867            }
12868        } else if (DEBUG_INSTALL) {
12869            final String parsedManifest = pkg.manifestDigest == null
12870                    ? "null" : pkg.manifestDigest.toString();
12871            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12872        }
12873
12874        // Get rid of all references to package scan path via parser.
12875        pp = null;
12876        String oldCodePath = null;
12877        boolean systemApp = false;
12878        synchronized (mPackages) {
12879            // Check if installing already existing package
12880            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12881                String oldName = mSettings.mRenamedPackages.get(pkgName);
12882                if (pkg.mOriginalPackages != null
12883                        && pkg.mOriginalPackages.contains(oldName)
12884                        && mPackages.containsKey(oldName)) {
12885                    // This package is derived from an original package,
12886                    // and this device has been updating from that original
12887                    // name.  We must continue using the original name, so
12888                    // rename the new package here.
12889                    pkg.setPackageName(oldName);
12890                    pkgName = pkg.packageName;
12891                    replace = true;
12892                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12893                            + oldName + " pkgName=" + pkgName);
12894                } else if (mPackages.containsKey(pkgName)) {
12895                    // This package, under its official name, already exists
12896                    // on the device; we should replace it.
12897                    replace = true;
12898                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12899                }
12900
12901                // Prevent apps opting out from runtime permissions
12902                if (replace) {
12903                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12904                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12905                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12906                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12907                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12908                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12909                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12910                                        + " doesn't support runtime permissions but the old"
12911                                        + " target SDK " + oldTargetSdk + " does.");
12912                        return;
12913                    }
12914                }
12915            }
12916
12917            PackageSetting ps = mSettings.mPackages.get(pkgName);
12918            if (ps != null) {
12919                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12920
12921                // Quick sanity check that we're signed correctly if updating;
12922                // we'll check this again later when scanning, but we want to
12923                // bail early here before tripping over redefined permissions.
12924                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12925                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12926                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12927                                + pkg.packageName + " upgrade keys do not match the "
12928                                + "previously installed version");
12929                        return;
12930                    }
12931                } else {
12932                    try {
12933                        verifySignaturesLP(ps, pkg);
12934                    } catch (PackageManagerException e) {
12935                        res.setError(e.error, e.getMessage());
12936                        return;
12937                    }
12938                }
12939
12940                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12941                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12942                    systemApp = (ps.pkg.applicationInfo.flags &
12943                            ApplicationInfo.FLAG_SYSTEM) != 0;
12944                }
12945                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12946            }
12947
12948            // Check whether the newly-scanned package wants to define an already-defined perm
12949            int N = pkg.permissions.size();
12950            for (int i = N-1; i >= 0; i--) {
12951                PackageParser.Permission perm = pkg.permissions.get(i);
12952                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12953                if (bp != null) {
12954                    // If the defining package is signed with our cert, it's okay.  This
12955                    // also includes the "updating the same package" case, of course.
12956                    // "updating same package" could also involve key-rotation.
12957                    final boolean sigsOk;
12958                    if (bp.sourcePackage.equals(pkg.packageName)
12959                            && (bp.packageSetting instanceof PackageSetting)
12960                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12961                                    scanFlags))) {
12962                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12963                    } else {
12964                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12965                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12966                    }
12967                    if (!sigsOk) {
12968                        // If the owning package is the system itself, we log but allow
12969                        // install to proceed; we fail the install on all other permission
12970                        // redefinitions.
12971                        if (!bp.sourcePackage.equals("android")) {
12972                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12973                                    + pkg.packageName + " attempting to redeclare permission "
12974                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12975                            res.origPermission = perm.info.name;
12976                            res.origPackage = bp.sourcePackage;
12977                            return;
12978                        } else {
12979                            Slog.w(TAG, "Package " + pkg.packageName
12980                                    + " attempting to redeclare system permission "
12981                                    + perm.info.name + "; ignoring new declaration");
12982                            pkg.permissions.remove(i);
12983                        }
12984                    }
12985                }
12986            }
12987
12988        }
12989
12990        if (systemApp) {
12991            if (onExternal) {
12992                // Abort update; system app can't be replaced with app on sdcard
12993                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12994                        "Cannot install updates to system apps on sdcard");
12995                return;
12996            } else if (ephemeral) {
12997                // Abort update; system app can't be replaced with an ephemeral app
12998                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12999                        "Cannot update a system app with an ephemeral app");
13000                return;
13001            }
13002        }
13003
13004        if (args.move != null) {
13005            // We did an in-place move, so dex is ready to roll
13006            scanFlags |= SCAN_NO_DEX;
13007            scanFlags |= SCAN_MOVE;
13008
13009            synchronized (mPackages) {
13010                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13011                if (ps == null) {
13012                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13013                            "Missing settings for moved package " + pkgName);
13014                }
13015
13016                // We moved the entire application as-is, so bring over the
13017                // previously derived ABI information.
13018                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13019                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13020            }
13021
13022        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13023            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13024            scanFlags |= SCAN_NO_DEX;
13025
13026            try {
13027                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13028                        true /* extract libs */);
13029            } catch (PackageManagerException pme) {
13030                Slog.e(TAG, "Error deriving application ABI", pme);
13031                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13032                return;
13033            }
13034        }
13035
13036        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13037            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13038            return;
13039        }
13040
13041        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13042
13043        if (replace) {
13044            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13045                    installerPackageName, volumeUuid, res);
13046        } else {
13047            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13048                    args.user, installerPackageName, volumeUuid, res);
13049        }
13050        synchronized (mPackages) {
13051            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13052            if (ps != null) {
13053                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13054            }
13055        }
13056    }
13057
13058    private void startIntentFilterVerifications(int userId, boolean replacing,
13059            PackageParser.Package pkg) {
13060        if (mIntentFilterVerifierComponent == null) {
13061            Slog.w(TAG, "No IntentFilter verification will not be done as "
13062                    + "there is no IntentFilterVerifier available!");
13063            return;
13064        }
13065
13066        final int verifierUid = getPackageUid(
13067                mIntentFilterVerifierComponent.getPackageName(),
13068                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13069
13070        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13071        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13072        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13073        mHandler.sendMessage(msg);
13074    }
13075
13076    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13077            PackageParser.Package pkg) {
13078        int size = pkg.activities.size();
13079        if (size == 0) {
13080            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13081                    "No activity, so no need to verify any IntentFilter!");
13082            return;
13083        }
13084
13085        final boolean hasDomainURLs = hasDomainURLs(pkg);
13086        if (!hasDomainURLs) {
13087            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13088                    "No domain URLs, so no need to verify any IntentFilter!");
13089            return;
13090        }
13091
13092        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13093                + " if any IntentFilter from the " + size
13094                + " Activities needs verification ...");
13095
13096        int count = 0;
13097        final String packageName = pkg.packageName;
13098
13099        synchronized (mPackages) {
13100            // If this is a new install and we see that we've already run verification for this
13101            // package, we have nothing to do: it means the state was restored from backup.
13102            if (!replacing) {
13103                IntentFilterVerificationInfo ivi =
13104                        mSettings.getIntentFilterVerificationLPr(packageName);
13105                if (ivi != null) {
13106                    if (DEBUG_DOMAIN_VERIFICATION) {
13107                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13108                                + ivi.getStatusString());
13109                    }
13110                    return;
13111                }
13112            }
13113
13114            // If any filters need to be verified, then all need to be.
13115            boolean needToVerify = false;
13116            for (PackageParser.Activity a : pkg.activities) {
13117                for (ActivityIntentInfo filter : a.intents) {
13118                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13119                        if (DEBUG_DOMAIN_VERIFICATION) {
13120                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13121                        }
13122                        needToVerify = true;
13123                        break;
13124                    }
13125                }
13126            }
13127
13128            if (needToVerify) {
13129                final int verificationId = mIntentFilterVerificationToken++;
13130                for (PackageParser.Activity a : pkg.activities) {
13131                    for (ActivityIntentInfo filter : a.intents) {
13132                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13133                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13134                                    "Verification needed for IntentFilter:" + filter.toString());
13135                            mIntentFilterVerifier.addOneIntentFilterVerification(
13136                                    verifierUid, userId, verificationId, filter, packageName);
13137                            count++;
13138                        }
13139                    }
13140                }
13141            }
13142        }
13143
13144        if (count > 0) {
13145            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13146                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13147                    +  " for userId:" + userId);
13148            mIntentFilterVerifier.startVerifications(userId);
13149        } else {
13150            if (DEBUG_DOMAIN_VERIFICATION) {
13151                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13152            }
13153        }
13154    }
13155
13156    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13157        final ComponentName cn  = filter.activity.getComponentName();
13158        final String packageName = cn.getPackageName();
13159
13160        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13161                packageName);
13162        if (ivi == null) {
13163            return true;
13164        }
13165        int status = ivi.getStatus();
13166        switch (status) {
13167            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13168            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13169                return true;
13170
13171            default:
13172                // Nothing to do
13173                return false;
13174        }
13175    }
13176
13177    private static boolean isMultiArch(ApplicationInfo info) {
13178        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13179    }
13180
13181    private static boolean isExternal(PackageParser.Package pkg) {
13182        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13183    }
13184
13185    private static boolean isExternal(PackageSetting ps) {
13186        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13187    }
13188
13189    private static boolean isEphemeral(PackageParser.Package pkg) {
13190        return pkg.applicationInfo.isEphemeralApp();
13191    }
13192
13193    private static boolean isEphemeral(PackageSetting ps) {
13194        return ps.pkg != null && isEphemeral(ps.pkg);
13195    }
13196
13197    private static boolean isSystemApp(PackageParser.Package pkg) {
13198        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13199    }
13200
13201    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13202        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13203    }
13204
13205    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13206        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13207    }
13208
13209    private static boolean isSystemApp(PackageSetting ps) {
13210        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13211    }
13212
13213    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13214        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13215    }
13216
13217    private int packageFlagsToInstallFlags(PackageSetting ps) {
13218        int installFlags = 0;
13219        if (isEphemeral(ps)) {
13220            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13221        }
13222        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13223            // This existing package was an external ASEC install when we have
13224            // the external flag without a UUID
13225            installFlags |= PackageManager.INSTALL_EXTERNAL;
13226        }
13227        if (ps.isForwardLocked()) {
13228            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13229        }
13230        return installFlags;
13231    }
13232
13233    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13234        if (isExternal(pkg)) {
13235            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13236                return StorageManager.UUID_PRIMARY_PHYSICAL;
13237            } else {
13238                return pkg.volumeUuid;
13239            }
13240        } else {
13241            return StorageManager.UUID_PRIVATE_INTERNAL;
13242        }
13243    }
13244
13245    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13246        if (isExternal(pkg)) {
13247            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13248                return mSettings.getExternalVersion();
13249            } else {
13250                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13251            }
13252        } else {
13253            return mSettings.getInternalVersion();
13254        }
13255    }
13256
13257    private void deleteTempPackageFiles() {
13258        final FilenameFilter filter = new FilenameFilter() {
13259            public boolean accept(File dir, String name) {
13260                return name.startsWith("vmdl") && name.endsWith(".tmp");
13261            }
13262        };
13263        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13264            file.delete();
13265        }
13266    }
13267
13268    @Override
13269    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13270            int flags) {
13271        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13272                flags);
13273    }
13274
13275    @Override
13276    public void deletePackage(final String packageName,
13277            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13278        mContext.enforceCallingOrSelfPermission(
13279                android.Manifest.permission.DELETE_PACKAGES, null);
13280        Preconditions.checkNotNull(packageName);
13281        Preconditions.checkNotNull(observer);
13282        final int uid = Binder.getCallingUid();
13283        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13284        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13285        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13286            mContext.enforceCallingOrSelfPermission(
13287                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13288                    "deletePackage for user " + userId);
13289        }
13290
13291        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13292            try {
13293                observer.onPackageDeleted(packageName,
13294                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13295            } catch (RemoteException re) {
13296            }
13297            return;
13298        }
13299
13300        for (int currentUserId : users) {
13301            if (getBlockUninstallForUser(packageName, currentUserId)) {
13302                try {
13303                    observer.onPackageDeleted(packageName,
13304                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13305                } catch (RemoteException re) {
13306                }
13307                return;
13308            }
13309        }
13310
13311        if (DEBUG_REMOVE) {
13312            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13313        }
13314        // Queue up an async operation since the package deletion may take a little while.
13315        mHandler.post(new Runnable() {
13316            public void run() {
13317                mHandler.removeCallbacks(this);
13318                final int returnCode = deletePackageX(packageName, userId, flags);
13319                try {
13320                    observer.onPackageDeleted(packageName, returnCode, null);
13321                } catch (RemoteException e) {
13322                    Log.i(TAG, "Observer no longer exists.");
13323                } //end catch
13324            } //end run
13325        });
13326    }
13327
13328    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13329        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13330                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13331        try {
13332            if (dpm != null) {
13333                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13334                        /* callingUserOnly =*/ false);
13335                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13336                        : deviceOwnerComponentName.getPackageName();
13337                // Does the package contains the device owner?
13338                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13339                // this check is probably not needed, since DO should be registered as a device
13340                // admin on some user too. (Original bug for this: b/17657954)
13341                if (packageName.equals(deviceOwnerPackageName)) {
13342                    return true;
13343                }
13344                // Does it contain a device admin for any user?
13345                int[] users;
13346                if (userId == UserHandle.USER_ALL) {
13347                    users = sUserManager.getUserIds();
13348                } else {
13349                    users = new int[]{userId};
13350                }
13351                for (int i = 0; i < users.length; ++i) {
13352                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13353                        return true;
13354                    }
13355                }
13356            }
13357        } catch (RemoteException e) {
13358        }
13359        return false;
13360    }
13361
13362    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13363        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13364    }
13365
13366    /**
13367     *  This method is an internal method that could be get invoked either
13368     *  to delete an installed package or to clean up a failed installation.
13369     *  After deleting an installed package, a broadcast is sent to notify any
13370     *  listeners that the package has been installed. For cleaning up a failed
13371     *  installation, the broadcast is not necessary since the package's
13372     *  installation wouldn't have sent the initial broadcast either
13373     *  The key steps in deleting a package are
13374     *  deleting the package information in internal structures like mPackages,
13375     *  deleting the packages base directories through installd
13376     *  updating mSettings to reflect current status
13377     *  persisting settings for later use
13378     *  sending a broadcast if necessary
13379     */
13380    private int deletePackageX(String packageName, int userId, int flags) {
13381        final PackageRemovedInfo info = new PackageRemovedInfo();
13382        final boolean res;
13383
13384        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13385                ? UserHandle.ALL : new UserHandle(userId);
13386
13387        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13388            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13389            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13390        }
13391
13392        boolean removedForAllUsers = false;
13393        boolean systemUpdate = false;
13394
13395        PackageParser.Package uninstalledPkg;
13396
13397        // for the uninstall-updates case and restricted profiles, remember the per-
13398        // userhandle installed state
13399        int[] allUsers;
13400        boolean[] perUserInstalled;
13401        synchronized (mPackages) {
13402            uninstalledPkg = mPackages.get(packageName);
13403            PackageSetting ps = mSettings.mPackages.get(packageName);
13404            allUsers = sUserManager.getUserIds();
13405            perUserInstalled = new boolean[allUsers.length];
13406            for (int i = 0; i < allUsers.length; i++) {
13407                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13408            }
13409        }
13410
13411        synchronized (mInstallLock) {
13412            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13413            res = deletePackageLI(packageName, removeForUser,
13414                    true, allUsers, perUserInstalled,
13415                    flags | REMOVE_CHATTY, info, true);
13416            systemUpdate = info.isRemovedPackageSystemUpdate;
13417            synchronized (mPackages) {
13418                if (res) {
13419                    if (!systemUpdate && mPackages.get(packageName) == null) {
13420                        removedForAllUsers = true;
13421                    }
13422                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13423                }
13424            }
13425            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13426                    + " removedForAllUsers=" + removedForAllUsers);
13427        }
13428
13429        if (res) {
13430            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13431
13432            // If the removed package was a system update, the old system package
13433            // was re-enabled; we need to broadcast this information
13434            if (systemUpdate) {
13435                Bundle extras = new Bundle(1);
13436                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13437                        ? info.removedAppId : info.uid);
13438                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13439
13440                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13441                        extras, 0, null, null, null);
13442                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13443                        extras, 0, null, null, null);
13444                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13445                        null, 0, packageName, null, null);
13446            }
13447        }
13448        // Force a gc here.
13449        Runtime.getRuntime().gc();
13450        // Delete the resources here after sending the broadcast to let
13451        // other processes clean up before deleting resources.
13452        if (info.args != null) {
13453            synchronized (mInstallLock) {
13454                info.args.doPostDeleteLI(true);
13455            }
13456        }
13457
13458        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13459    }
13460
13461    class PackageRemovedInfo {
13462        String removedPackage;
13463        int uid = -1;
13464        int removedAppId = -1;
13465        int[] removedUsers = null;
13466        boolean isRemovedPackageSystemUpdate = false;
13467        // Clean up resources deleted packages.
13468        InstallArgs args = null;
13469
13470        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13471            Bundle extras = new Bundle(1);
13472            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13473            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13474            if (replacing) {
13475                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13476            }
13477            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13478            if (removedPackage != null) {
13479                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13480                        extras, 0, null, null, removedUsers);
13481                if (fullRemove && !replacing) {
13482                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13483                            extras, 0, null, null, removedUsers);
13484                }
13485            }
13486            if (removedAppId >= 0) {
13487                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13488                        removedUsers);
13489            }
13490        }
13491    }
13492
13493    /*
13494     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13495     * flag is not set, the data directory is removed as well.
13496     * make sure this flag is set for partially installed apps. If not its meaningless to
13497     * delete a partially installed application.
13498     */
13499    private void removePackageDataLI(PackageSetting ps,
13500            int[] allUserHandles, boolean[] perUserInstalled,
13501            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13502        String packageName = ps.name;
13503        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13504        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13505        // Retrieve object to delete permissions for shared user later on
13506        final PackageSetting deletedPs;
13507        // reader
13508        synchronized (mPackages) {
13509            deletedPs = mSettings.mPackages.get(packageName);
13510            if (outInfo != null) {
13511                outInfo.removedPackage = packageName;
13512                outInfo.removedUsers = deletedPs != null
13513                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13514                        : null;
13515            }
13516        }
13517        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13518            removeDataDirsLI(ps.volumeUuid, packageName);
13519            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13520        }
13521        // writer
13522        synchronized (mPackages) {
13523            if (deletedPs != null) {
13524                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13525                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13526                    clearDefaultBrowserIfNeeded(packageName);
13527                    if (outInfo != null) {
13528                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13529                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13530                    }
13531                    updatePermissionsLPw(deletedPs.name, null, 0);
13532                    if (deletedPs.sharedUser != null) {
13533                        // Remove permissions associated with package. Since runtime
13534                        // permissions are per user we have to kill the removed package
13535                        // or packages running under the shared user of the removed
13536                        // package if revoking the permissions requested only by the removed
13537                        // package is successful and this causes a change in gids.
13538                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13539                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13540                                    userId);
13541                            if (userIdToKill == UserHandle.USER_ALL
13542                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13543                                // If gids changed for this user, kill all affected packages.
13544                                mHandler.post(new Runnable() {
13545                                    @Override
13546                                    public void run() {
13547                                        // This has to happen with no lock held.
13548                                        killApplication(deletedPs.name, deletedPs.appId,
13549                                                KILL_APP_REASON_GIDS_CHANGED);
13550                                    }
13551                                });
13552                                break;
13553                            }
13554                        }
13555                    }
13556                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13557                }
13558                // make sure to preserve per-user disabled state if this removal was just
13559                // a downgrade of a system app to the factory package
13560                if (allUserHandles != null && perUserInstalled != null) {
13561                    if (DEBUG_REMOVE) {
13562                        Slog.d(TAG, "Propagating install state across downgrade");
13563                    }
13564                    for (int i = 0; i < allUserHandles.length; i++) {
13565                        if (DEBUG_REMOVE) {
13566                            Slog.d(TAG, "    user " + allUserHandles[i]
13567                                    + " => " + perUserInstalled[i]);
13568                        }
13569                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13570                    }
13571                }
13572            }
13573            // can downgrade to reader
13574            if (writeSettings) {
13575                // Save settings now
13576                mSettings.writeLPr();
13577            }
13578        }
13579        if (outInfo != null) {
13580            // A user ID was deleted here. Go through all users and remove it
13581            // from KeyStore.
13582            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13583        }
13584    }
13585
13586    static boolean locationIsPrivileged(File path) {
13587        try {
13588            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13589                    .getCanonicalPath();
13590            return path.getCanonicalPath().startsWith(privilegedAppDir);
13591        } catch (IOException e) {
13592            Slog.e(TAG, "Unable to access code path " + path);
13593        }
13594        return false;
13595    }
13596
13597    /*
13598     * Tries to delete system package.
13599     */
13600    private boolean deleteSystemPackageLI(PackageSetting newPs,
13601            int[] allUserHandles, boolean[] perUserInstalled,
13602            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13603        final boolean applyUserRestrictions
13604                = (allUserHandles != null) && (perUserInstalled != null);
13605        PackageSetting disabledPs = null;
13606        // Confirm if the system package has been updated
13607        // An updated system app can be deleted. This will also have to restore
13608        // the system pkg from system partition
13609        // reader
13610        synchronized (mPackages) {
13611            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13612        }
13613        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13614                + " disabledPs=" + disabledPs);
13615        if (disabledPs == null) {
13616            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13617            return false;
13618        } else if (DEBUG_REMOVE) {
13619            Slog.d(TAG, "Deleting system pkg from data partition");
13620        }
13621        if (DEBUG_REMOVE) {
13622            if (applyUserRestrictions) {
13623                Slog.d(TAG, "Remembering install states:");
13624                for (int i = 0; i < allUserHandles.length; i++) {
13625                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13626                }
13627            }
13628        }
13629        // Delete the updated package
13630        outInfo.isRemovedPackageSystemUpdate = true;
13631        if (disabledPs.versionCode < newPs.versionCode) {
13632            // Delete data for downgrades
13633            flags &= ~PackageManager.DELETE_KEEP_DATA;
13634        } else {
13635            // Preserve data by setting flag
13636            flags |= PackageManager.DELETE_KEEP_DATA;
13637        }
13638        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13639                allUserHandles, perUserInstalled, outInfo, writeSettings);
13640        if (!ret) {
13641            return false;
13642        }
13643        // writer
13644        synchronized (mPackages) {
13645            // Reinstate the old system package
13646            mSettings.enableSystemPackageLPw(newPs.name);
13647            // Remove any native libraries from the upgraded package.
13648            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13649        }
13650        // Install the system package
13651        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13652        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13653        if (locationIsPrivileged(disabledPs.codePath)) {
13654            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13655        }
13656
13657        final PackageParser.Package newPkg;
13658        try {
13659            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13660        } catch (PackageManagerException e) {
13661            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13662            return false;
13663        }
13664
13665        // writer
13666        synchronized (mPackages) {
13667            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13668
13669            // Propagate the permissions state as we do not want to drop on the floor
13670            // runtime permissions. The update permissions method below will take
13671            // care of removing obsolete permissions and grant install permissions.
13672            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13673            updatePermissionsLPw(newPkg.packageName, newPkg,
13674                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13675
13676            if (applyUserRestrictions) {
13677                if (DEBUG_REMOVE) {
13678                    Slog.d(TAG, "Propagating install state across reinstall");
13679                }
13680                for (int i = 0; i < allUserHandles.length; i++) {
13681                    if (DEBUG_REMOVE) {
13682                        Slog.d(TAG, "    user " + allUserHandles[i]
13683                                + " => " + perUserInstalled[i]);
13684                    }
13685                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13686
13687                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13688                }
13689                // Regardless of writeSettings we need to ensure that this restriction
13690                // state propagation is persisted
13691                mSettings.writeAllUsersPackageRestrictionsLPr();
13692            }
13693            // can downgrade to reader here
13694            if (writeSettings) {
13695                mSettings.writeLPr();
13696            }
13697        }
13698        return true;
13699    }
13700
13701    private boolean deleteInstalledPackageLI(PackageSetting ps,
13702            boolean deleteCodeAndResources, int flags,
13703            int[] allUserHandles, boolean[] perUserInstalled,
13704            PackageRemovedInfo outInfo, boolean writeSettings) {
13705        if (outInfo != null) {
13706            outInfo.uid = ps.appId;
13707        }
13708
13709        // Delete package data from internal structures and also remove data if flag is set
13710        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13711
13712        // Delete application code and resources
13713        if (deleteCodeAndResources && (outInfo != null)) {
13714            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13715                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13716            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13717        }
13718        return true;
13719    }
13720
13721    @Override
13722    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13723            int userId) {
13724        mContext.enforceCallingOrSelfPermission(
13725                android.Manifest.permission.DELETE_PACKAGES, null);
13726        synchronized (mPackages) {
13727            PackageSetting ps = mSettings.mPackages.get(packageName);
13728            if (ps == null) {
13729                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13730                return false;
13731            }
13732            if (!ps.getInstalled(userId)) {
13733                // Can't block uninstall for an app that is not installed or enabled.
13734                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13735                return false;
13736            }
13737            ps.setBlockUninstall(blockUninstall, userId);
13738            mSettings.writePackageRestrictionsLPr(userId);
13739        }
13740        return true;
13741    }
13742
13743    @Override
13744    public boolean getBlockUninstallForUser(String packageName, int userId) {
13745        synchronized (mPackages) {
13746            PackageSetting ps = mSettings.mPackages.get(packageName);
13747            if (ps == null) {
13748                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13749                return false;
13750            }
13751            return ps.getBlockUninstall(userId);
13752        }
13753    }
13754
13755    /*
13756     * This method handles package deletion in general
13757     */
13758    private boolean deletePackageLI(String packageName, UserHandle user,
13759            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13760            int flags, PackageRemovedInfo outInfo,
13761            boolean writeSettings) {
13762        if (packageName == null) {
13763            Slog.w(TAG, "Attempt to delete null packageName.");
13764            return false;
13765        }
13766        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13767        PackageSetting ps;
13768        boolean dataOnly = false;
13769        int removeUser = -1;
13770        int appId = -1;
13771        synchronized (mPackages) {
13772            ps = mSettings.mPackages.get(packageName);
13773            if (ps == null) {
13774                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13775                return false;
13776            }
13777            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13778                    && user.getIdentifier() != UserHandle.USER_ALL) {
13779                // The caller is asking that the package only be deleted for a single
13780                // user.  To do this, we just mark its uninstalled state and delete
13781                // its data.  If this is a system app, we only allow this to happen if
13782                // they have set the special DELETE_SYSTEM_APP which requests different
13783                // semantics than normal for uninstalling system apps.
13784                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13785                final int userId = user.getIdentifier();
13786                ps.setUserState(userId,
13787                        COMPONENT_ENABLED_STATE_DEFAULT,
13788                        false, //installed
13789                        true,  //stopped
13790                        true,  //notLaunched
13791                        false, //hidden
13792                        null, null, null,
13793                        false, // blockUninstall
13794                        ps.readUserState(userId).domainVerificationStatus, 0);
13795                if (!isSystemApp(ps)) {
13796                    // Do not uninstall the APK if an app should be cached
13797                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13798                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13799                        // Other user still have this package installed, so all
13800                        // we need to do is clear this user's data and save that
13801                        // it is uninstalled.
13802                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13803                        removeUser = user.getIdentifier();
13804                        appId = ps.appId;
13805                        scheduleWritePackageRestrictionsLocked(removeUser);
13806                    } else {
13807                        // We need to set it back to 'installed' so the uninstall
13808                        // broadcasts will be sent correctly.
13809                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13810                        ps.setInstalled(true, user.getIdentifier());
13811                    }
13812                } else {
13813                    // This is a system app, so we assume that the
13814                    // other users still have this package installed, so all
13815                    // we need to do is clear this user's data and save that
13816                    // it is uninstalled.
13817                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13818                    removeUser = user.getIdentifier();
13819                    appId = ps.appId;
13820                    scheduleWritePackageRestrictionsLocked(removeUser);
13821                }
13822            }
13823        }
13824
13825        if (removeUser >= 0) {
13826            // From above, we determined that we are deleting this only
13827            // for a single user.  Continue the work here.
13828            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13829            if (outInfo != null) {
13830                outInfo.removedPackage = packageName;
13831                outInfo.removedAppId = appId;
13832                outInfo.removedUsers = new int[] {removeUser};
13833            }
13834            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13835            removeKeystoreDataIfNeeded(removeUser, appId);
13836            schedulePackageCleaning(packageName, removeUser, false);
13837            synchronized (mPackages) {
13838                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13839                    scheduleWritePackageRestrictionsLocked(removeUser);
13840                }
13841                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13842            }
13843            return true;
13844        }
13845
13846        if (dataOnly) {
13847            // Delete application data first
13848            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13849            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13850            return true;
13851        }
13852
13853        boolean ret = false;
13854        if (isSystemApp(ps)) {
13855            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13856            // When an updated system application is deleted we delete the existing resources as well and
13857            // fall back to existing code in system partition
13858            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13859                    flags, outInfo, writeSettings);
13860        } else {
13861            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13862            // Kill application pre-emptively especially for apps on sd.
13863            killApplication(packageName, ps.appId, "uninstall pkg");
13864            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13865                    allUserHandles, perUserInstalled,
13866                    outInfo, writeSettings);
13867        }
13868
13869        return ret;
13870    }
13871
13872    private final static class ClearStorageConnection implements ServiceConnection {
13873        IMediaContainerService mContainerService;
13874
13875        @Override
13876        public void onServiceConnected(ComponentName name, IBinder service) {
13877            synchronized (this) {
13878                mContainerService = IMediaContainerService.Stub.asInterface(service);
13879                notifyAll();
13880            }
13881        }
13882
13883        @Override
13884        public void onServiceDisconnected(ComponentName name) {
13885        }
13886    }
13887
13888    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13889        final boolean mounted;
13890        if (Environment.isExternalStorageEmulated()) {
13891            mounted = true;
13892        } else {
13893            final String status = Environment.getExternalStorageState();
13894
13895            mounted = status.equals(Environment.MEDIA_MOUNTED)
13896                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13897        }
13898
13899        if (!mounted) {
13900            return;
13901        }
13902
13903        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13904        int[] users;
13905        if (userId == UserHandle.USER_ALL) {
13906            users = sUserManager.getUserIds();
13907        } else {
13908            users = new int[] { userId };
13909        }
13910        final ClearStorageConnection conn = new ClearStorageConnection();
13911        if (mContext.bindServiceAsUser(
13912                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13913            try {
13914                for (int curUser : users) {
13915                    long timeout = SystemClock.uptimeMillis() + 5000;
13916                    synchronized (conn) {
13917                        long now = SystemClock.uptimeMillis();
13918                        while (conn.mContainerService == null && now < timeout) {
13919                            try {
13920                                conn.wait(timeout - now);
13921                            } catch (InterruptedException e) {
13922                            }
13923                        }
13924                    }
13925                    if (conn.mContainerService == null) {
13926                        return;
13927                    }
13928
13929                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13930                    clearDirectory(conn.mContainerService,
13931                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13932                    if (allData) {
13933                        clearDirectory(conn.mContainerService,
13934                                userEnv.buildExternalStorageAppDataDirs(packageName));
13935                        clearDirectory(conn.mContainerService,
13936                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13937                    }
13938                }
13939            } finally {
13940                mContext.unbindService(conn);
13941            }
13942        }
13943    }
13944
13945    @Override
13946    public void clearApplicationUserData(final String packageName,
13947            final IPackageDataObserver observer, final int userId) {
13948        mContext.enforceCallingOrSelfPermission(
13949                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13950        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13951        // Queue up an async operation since the package deletion may take a little while.
13952        mHandler.post(new Runnable() {
13953            public void run() {
13954                mHandler.removeCallbacks(this);
13955                final boolean succeeded;
13956                synchronized (mInstallLock) {
13957                    succeeded = clearApplicationUserDataLI(packageName, userId);
13958                }
13959                clearExternalStorageDataSync(packageName, userId, true);
13960                if (succeeded) {
13961                    // invoke DeviceStorageMonitor's update method to clear any notifications
13962                    DeviceStorageMonitorInternal
13963                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13964                    if (dsm != null) {
13965                        dsm.checkMemory();
13966                    }
13967                }
13968                if(observer != null) {
13969                    try {
13970                        observer.onRemoveCompleted(packageName, succeeded);
13971                    } catch (RemoteException e) {
13972                        Log.i(TAG, "Observer no longer exists.");
13973                    }
13974                } //end if observer
13975            } //end run
13976        });
13977    }
13978
13979    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13980        if (packageName == null) {
13981            Slog.w(TAG, "Attempt to delete null packageName.");
13982            return false;
13983        }
13984
13985        // Try finding details about the requested package
13986        PackageParser.Package pkg;
13987        synchronized (mPackages) {
13988            pkg = mPackages.get(packageName);
13989            if (pkg == null) {
13990                final PackageSetting ps = mSettings.mPackages.get(packageName);
13991                if (ps != null) {
13992                    pkg = ps.pkg;
13993                }
13994            }
13995
13996            if (pkg == null) {
13997                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13998                return false;
13999            }
14000
14001            PackageSetting ps = (PackageSetting) pkg.mExtras;
14002            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14003        }
14004
14005        // Always delete data directories for package, even if we found no other
14006        // record of app. This helps users recover from UID mismatches without
14007        // resorting to a full data wipe.
14008        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14009        if (retCode < 0) {
14010            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
14011            return false;
14012        }
14013
14014        final int appId = pkg.applicationInfo.uid;
14015        removeKeystoreDataIfNeeded(userId, appId);
14016
14017        // Create a native library symlink only if we have native libraries
14018        // and if the native libraries are 32 bit libraries. We do not provide
14019        // this symlink for 64 bit libraries.
14020        if (pkg.applicationInfo.primaryCpuAbi != null &&
14021                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14022            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14023            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14024                    nativeLibPath, userId) < 0) {
14025                Slog.w(TAG, "Failed linking native library dir");
14026                return false;
14027            }
14028        }
14029
14030        return true;
14031    }
14032
14033    /**
14034     * Reverts user permission state changes (permissions and flags) in
14035     * all packages for a given user.
14036     *
14037     * @param userId The device user for which to do a reset.
14038     */
14039    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14040        final int packageCount = mPackages.size();
14041        for (int i = 0; i < packageCount; i++) {
14042            PackageParser.Package pkg = mPackages.valueAt(i);
14043            PackageSetting ps = (PackageSetting) pkg.mExtras;
14044            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14045        }
14046    }
14047
14048    /**
14049     * Reverts user permission state changes (permissions and flags).
14050     *
14051     * @param ps The package for which to reset.
14052     * @param userId The device user for which to do a reset.
14053     */
14054    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14055            final PackageSetting ps, final int userId) {
14056        if (ps.pkg == null) {
14057            return;
14058        }
14059
14060        // These are flags that can change base on user actions.
14061        final int userSettableMask = FLAG_PERMISSION_USER_SET
14062                | FLAG_PERMISSION_USER_FIXED
14063                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14064                | FLAG_PERMISSION_REVIEW_REQUIRED;
14065
14066        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14067                | FLAG_PERMISSION_POLICY_FIXED;
14068
14069        boolean writeInstallPermissions = false;
14070        boolean writeRuntimePermissions = false;
14071
14072        final int permissionCount = ps.pkg.requestedPermissions.size();
14073        for (int i = 0; i < permissionCount; i++) {
14074            String permission = ps.pkg.requestedPermissions.get(i);
14075
14076            BasePermission bp = mSettings.mPermissions.get(permission);
14077            if (bp == null) {
14078                continue;
14079            }
14080
14081            // If shared user we just reset the state to which only this app contributed.
14082            if (ps.sharedUser != null) {
14083                boolean used = false;
14084                final int packageCount = ps.sharedUser.packages.size();
14085                for (int j = 0; j < packageCount; j++) {
14086                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14087                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14088                            && pkg.pkg.requestedPermissions.contains(permission)) {
14089                        used = true;
14090                        break;
14091                    }
14092                }
14093                if (used) {
14094                    continue;
14095                }
14096            }
14097
14098            PermissionsState permissionsState = ps.getPermissionsState();
14099
14100            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14101
14102            // Always clear the user settable flags.
14103            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14104                    bp.name) != null;
14105            // If permission review is enabled and this is a legacy app, mark the
14106            // permission as requiring a review as this is the initial state.
14107            int flags = 0;
14108            if (Build.PERMISSIONS_REVIEW_REQUIRED
14109                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14110                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14111            }
14112            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14113                if (hasInstallState) {
14114                    writeInstallPermissions = true;
14115                } else {
14116                    writeRuntimePermissions = true;
14117                }
14118            }
14119
14120            // Below is only runtime permission handling.
14121            if (!bp.isRuntime()) {
14122                continue;
14123            }
14124
14125            // Never clobber system or policy.
14126            if ((oldFlags & policyOrSystemFlags) != 0) {
14127                continue;
14128            }
14129
14130            // If this permission was granted by default, make sure it is.
14131            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14132                if (permissionsState.grantRuntimePermission(bp, userId)
14133                        != PERMISSION_OPERATION_FAILURE) {
14134                    writeRuntimePermissions = true;
14135                }
14136            // If permission review is enabled the permissions for a legacy apps
14137            // are represented as constantly granted runtime ones, so don't revoke.
14138            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14139                // Otherwise, reset the permission.
14140                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14141                switch (revokeResult) {
14142                    case PERMISSION_OPERATION_SUCCESS: {
14143                        writeRuntimePermissions = true;
14144                    } break;
14145
14146                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14147                        writeRuntimePermissions = true;
14148                        final int appId = ps.appId;
14149                        mHandler.post(new Runnable() {
14150                            @Override
14151                            public void run() {
14152                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14153                            }
14154                        });
14155                    } break;
14156                }
14157            }
14158        }
14159
14160        // Synchronously write as we are taking permissions away.
14161        if (writeRuntimePermissions) {
14162            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14163        }
14164
14165        // Synchronously write as we are taking permissions away.
14166        if (writeInstallPermissions) {
14167            mSettings.writeLPr();
14168        }
14169    }
14170
14171    /**
14172     * Remove entries from the keystore daemon. Will only remove it if the
14173     * {@code appId} is valid.
14174     */
14175    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14176        if (appId < 0) {
14177            return;
14178        }
14179
14180        final KeyStore keyStore = KeyStore.getInstance();
14181        if (keyStore != null) {
14182            if (userId == UserHandle.USER_ALL) {
14183                for (final int individual : sUserManager.getUserIds()) {
14184                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14185                }
14186            } else {
14187                keyStore.clearUid(UserHandle.getUid(userId, appId));
14188            }
14189        } else {
14190            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14191        }
14192    }
14193
14194    @Override
14195    public void deleteApplicationCacheFiles(final String packageName,
14196            final IPackageDataObserver observer) {
14197        mContext.enforceCallingOrSelfPermission(
14198                android.Manifest.permission.DELETE_CACHE_FILES, null);
14199        // Queue up an async operation since the package deletion may take a little while.
14200        final int userId = UserHandle.getCallingUserId();
14201        mHandler.post(new Runnable() {
14202            public void run() {
14203                mHandler.removeCallbacks(this);
14204                final boolean succeded;
14205                synchronized (mInstallLock) {
14206                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14207                }
14208                clearExternalStorageDataSync(packageName, userId, false);
14209                if (observer != null) {
14210                    try {
14211                        observer.onRemoveCompleted(packageName, succeded);
14212                    } catch (RemoteException e) {
14213                        Log.i(TAG, "Observer no longer exists.");
14214                    }
14215                } //end if observer
14216            } //end run
14217        });
14218    }
14219
14220    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14221        if (packageName == null) {
14222            Slog.w(TAG, "Attempt to delete null packageName.");
14223            return false;
14224        }
14225        PackageParser.Package p;
14226        synchronized (mPackages) {
14227            p = mPackages.get(packageName);
14228        }
14229        if (p == null) {
14230            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14231            return false;
14232        }
14233        final ApplicationInfo applicationInfo = p.applicationInfo;
14234        if (applicationInfo == null) {
14235            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14236            return false;
14237        }
14238        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14239        if (retCode < 0) {
14240            Slog.w(TAG, "Couldn't remove cache files for package: "
14241                       + packageName + " u" + userId);
14242            return false;
14243        }
14244        return true;
14245    }
14246
14247    @Override
14248    public void getPackageSizeInfo(final String packageName, int userHandle,
14249            final IPackageStatsObserver observer) {
14250        mContext.enforceCallingOrSelfPermission(
14251                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14252        if (packageName == null) {
14253            throw new IllegalArgumentException("Attempt to get size of null packageName");
14254        }
14255
14256        PackageStats stats = new PackageStats(packageName, userHandle);
14257
14258        /*
14259         * Queue up an async operation since the package measurement may take a
14260         * little while.
14261         */
14262        Message msg = mHandler.obtainMessage(INIT_COPY);
14263        msg.obj = new MeasureParams(stats, observer);
14264        mHandler.sendMessage(msg);
14265    }
14266
14267    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14268            PackageStats pStats) {
14269        if (packageName == null) {
14270            Slog.w(TAG, "Attempt to get size of null packageName.");
14271            return false;
14272        }
14273        PackageParser.Package p;
14274        boolean dataOnly = false;
14275        String libDirRoot = null;
14276        String asecPath = null;
14277        PackageSetting ps = null;
14278        synchronized (mPackages) {
14279            p = mPackages.get(packageName);
14280            ps = mSettings.mPackages.get(packageName);
14281            if(p == null) {
14282                dataOnly = true;
14283                if((ps == null) || (ps.pkg == null)) {
14284                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14285                    return false;
14286                }
14287                p = ps.pkg;
14288            }
14289            if (ps != null) {
14290                libDirRoot = ps.legacyNativeLibraryPathString;
14291            }
14292            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14293                final long token = Binder.clearCallingIdentity();
14294                try {
14295                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14296                    if (secureContainerId != null) {
14297                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14298                    }
14299                } finally {
14300                    Binder.restoreCallingIdentity(token);
14301                }
14302            }
14303        }
14304        String publicSrcDir = null;
14305        if(!dataOnly) {
14306            final ApplicationInfo applicationInfo = p.applicationInfo;
14307            if (applicationInfo == null) {
14308                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14309                return false;
14310            }
14311            if (p.isForwardLocked()) {
14312                publicSrcDir = applicationInfo.getBaseResourcePath();
14313            }
14314        }
14315        // TODO: extend to measure size of split APKs
14316        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14317        // not just the first level.
14318        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14319        // just the primary.
14320        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14321
14322        String apkPath;
14323        File packageDir = new File(p.codePath);
14324
14325        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14326            apkPath = packageDir.getAbsolutePath();
14327            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14328            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14329                libDirRoot = null;
14330            }
14331        } else {
14332            apkPath = p.baseCodePath;
14333        }
14334
14335        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14336                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14337        if (res < 0) {
14338            return false;
14339        }
14340
14341        // Fix-up for forward-locked applications in ASEC containers.
14342        if (!isExternal(p)) {
14343            pStats.codeSize += pStats.externalCodeSize;
14344            pStats.externalCodeSize = 0L;
14345        }
14346
14347        return true;
14348    }
14349
14350
14351    @Override
14352    public void addPackageToPreferred(String packageName) {
14353        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14354    }
14355
14356    @Override
14357    public void removePackageFromPreferred(String packageName) {
14358        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14359    }
14360
14361    @Override
14362    public List<PackageInfo> getPreferredPackages(int flags) {
14363        return new ArrayList<PackageInfo>();
14364    }
14365
14366    private int getUidTargetSdkVersionLockedLPr(int uid) {
14367        Object obj = mSettings.getUserIdLPr(uid);
14368        if (obj instanceof SharedUserSetting) {
14369            final SharedUserSetting sus = (SharedUserSetting) obj;
14370            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14371            final Iterator<PackageSetting> it = sus.packages.iterator();
14372            while (it.hasNext()) {
14373                final PackageSetting ps = it.next();
14374                if (ps.pkg != null) {
14375                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14376                    if (v < vers) vers = v;
14377                }
14378            }
14379            return vers;
14380        } else if (obj instanceof PackageSetting) {
14381            final PackageSetting ps = (PackageSetting) obj;
14382            if (ps.pkg != null) {
14383                return ps.pkg.applicationInfo.targetSdkVersion;
14384            }
14385        }
14386        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14387    }
14388
14389    @Override
14390    public void addPreferredActivity(IntentFilter filter, int match,
14391            ComponentName[] set, ComponentName activity, int userId) {
14392        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14393                "Adding preferred");
14394    }
14395
14396    private void addPreferredActivityInternal(IntentFilter filter, int match,
14397            ComponentName[] set, ComponentName activity, boolean always, int userId,
14398            String opname) {
14399        // writer
14400        int callingUid = Binder.getCallingUid();
14401        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14402        if (filter.countActions() == 0) {
14403            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14404            return;
14405        }
14406        synchronized (mPackages) {
14407            if (mContext.checkCallingOrSelfPermission(
14408                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14409                    != PackageManager.PERMISSION_GRANTED) {
14410                if (getUidTargetSdkVersionLockedLPr(callingUid)
14411                        < Build.VERSION_CODES.FROYO) {
14412                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14413                            + callingUid);
14414                    return;
14415                }
14416                mContext.enforceCallingOrSelfPermission(
14417                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14418            }
14419
14420            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14421            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14422                    + userId + ":");
14423            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14424            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14425            scheduleWritePackageRestrictionsLocked(userId);
14426        }
14427    }
14428
14429    @Override
14430    public void replacePreferredActivity(IntentFilter filter, int match,
14431            ComponentName[] set, ComponentName activity, int userId) {
14432        if (filter.countActions() != 1) {
14433            throw new IllegalArgumentException(
14434                    "replacePreferredActivity expects filter to have only 1 action.");
14435        }
14436        if (filter.countDataAuthorities() != 0
14437                || filter.countDataPaths() != 0
14438                || filter.countDataSchemes() > 1
14439                || filter.countDataTypes() != 0) {
14440            throw new IllegalArgumentException(
14441                    "replacePreferredActivity expects filter to have no data authorities, " +
14442                    "paths, or types; and at most one scheme.");
14443        }
14444
14445        final int callingUid = Binder.getCallingUid();
14446        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14447        synchronized (mPackages) {
14448            if (mContext.checkCallingOrSelfPermission(
14449                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14450                    != PackageManager.PERMISSION_GRANTED) {
14451                if (getUidTargetSdkVersionLockedLPr(callingUid)
14452                        < Build.VERSION_CODES.FROYO) {
14453                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14454                            + Binder.getCallingUid());
14455                    return;
14456                }
14457                mContext.enforceCallingOrSelfPermission(
14458                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14459            }
14460
14461            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14462            if (pir != null) {
14463                // Get all of the existing entries that exactly match this filter.
14464                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14465                if (existing != null && existing.size() == 1) {
14466                    PreferredActivity cur = existing.get(0);
14467                    if (DEBUG_PREFERRED) {
14468                        Slog.i(TAG, "Checking replace of preferred:");
14469                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14470                        if (!cur.mPref.mAlways) {
14471                            Slog.i(TAG, "  -- CUR; not mAlways!");
14472                        } else {
14473                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14474                            Slog.i(TAG, "  -- CUR: mSet="
14475                                    + Arrays.toString(cur.mPref.mSetComponents));
14476                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14477                            Slog.i(TAG, "  -- NEW: mMatch="
14478                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14479                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14480                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14481                        }
14482                    }
14483                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14484                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14485                            && cur.mPref.sameSet(set)) {
14486                        // Setting the preferred activity to what it happens to be already
14487                        if (DEBUG_PREFERRED) {
14488                            Slog.i(TAG, "Replacing with same preferred activity "
14489                                    + cur.mPref.mShortComponent + " for user "
14490                                    + userId + ":");
14491                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14492                        }
14493                        return;
14494                    }
14495                }
14496
14497                if (existing != null) {
14498                    if (DEBUG_PREFERRED) {
14499                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14500                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14501                    }
14502                    for (int i = 0; i < existing.size(); i++) {
14503                        PreferredActivity pa = existing.get(i);
14504                        if (DEBUG_PREFERRED) {
14505                            Slog.i(TAG, "Removing existing preferred activity "
14506                                    + pa.mPref.mComponent + ":");
14507                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14508                        }
14509                        pir.removeFilter(pa);
14510                    }
14511                }
14512            }
14513            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14514                    "Replacing preferred");
14515        }
14516    }
14517
14518    @Override
14519    public void clearPackagePreferredActivities(String packageName) {
14520        final int uid = Binder.getCallingUid();
14521        // writer
14522        synchronized (mPackages) {
14523            PackageParser.Package pkg = mPackages.get(packageName);
14524            if (pkg == null || pkg.applicationInfo.uid != uid) {
14525                if (mContext.checkCallingOrSelfPermission(
14526                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14527                        != PackageManager.PERMISSION_GRANTED) {
14528                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14529                            < Build.VERSION_CODES.FROYO) {
14530                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14531                                + Binder.getCallingUid());
14532                        return;
14533                    }
14534                    mContext.enforceCallingOrSelfPermission(
14535                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14536                }
14537            }
14538
14539            int user = UserHandle.getCallingUserId();
14540            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14541                scheduleWritePackageRestrictionsLocked(user);
14542            }
14543        }
14544    }
14545
14546    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14547    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14548        ArrayList<PreferredActivity> removed = null;
14549        boolean changed = false;
14550        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14551            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14552            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14553            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14554                continue;
14555            }
14556            Iterator<PreferredActivity> it = pir.filterIterator();
14557            while (it.hasNext()) {
14558                PreferredActivity pa = it.next();
14559                // Mark entry for removal only if it matches the package name
14560                // and the entry is of type "always".
14561                if (packageName == null ||
14562                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14563                                && pa.mPref.mAlways)) {
14564                    if (removed == null) {
14565                        removed = new ArrayList<PreferredActivity>();
14566                    }
14567                    removed.add(pa);
14568                }
14569            }
14570            if (removed != null) {
14571                for (int j=0; j<removed.size(); j++) {
14572                    PreferredActivity pa = removed.get(j);
14573                    pir.removeFilter(pa);
14574                }
14575                changed = true;
14576            }
14577        }
14578        return changed;
14579    }
14580
14581    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14582    private void clearIntentFilterVerificationsLPw(int userId) {
14583        final int packageCount = mPackages.size();
14584        for (int i = 0; i < packageCount; i++) {
14585            PackageParser.Package pkg = mPackages.valueAt(i);
14586            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14587        }
14588    }
14589
14590    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14591    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14592        if (userId == UserHandle.USER_ALL) {
14593            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14594                    sUserManager.getUserIds())) {
14595                for (int oneUserId : sUserManager.getUserIds()) {
14596                    scheduleWritePackageRestrictionsLocked(oneUserId);
14597                }
14598            }
14599        } else {
14600            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14601                scheduleWritePackageRestrictionsLocked(userId);
14602            }
14603        }
14604    }
14605
14606    void clearDefaultBrowserIfNeeded(String packageName) {
14607        for (int oneUserId : sUserManager.getUserIds()) {
14608            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14609            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14610            if (packageName.equals(defaultBrowserPackageName)) {
14611                setDefaultBrowserPackageName(null, oneUserId);
14612            }
14613        }
14614    }
14615
14616    @Override
14617    public void resetApplicationPreferences(int userId) {
14618        mContext.enforceCallingOrSelfPermission(
14619                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14620        // writer
14621        synchronized (mPackages) {
14622            final long identity = Binder.clearCallingIdentity();
14623            try {
14624                clearPackagePreferredActivitiesLPw(null, userId);
14625                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14626                // TODO: We have to reset the default SMS and Phone. This requires
14627                // significant refactoring to keep all default apps in the package
14628                // manager (cleaner but more work) or have the services provide
14629                // callbacks to the package manager to request a default app reset.
14630                applyFactoryDefaultBrowserLPw(userId);
14631                clearIntentFilterVerificationsLPw(userId);
14632                primeDomainVerificationsLPw(userId);
14633                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14634                scheduleWritePackageRestrictionsLocked(userId);
14635            } finally {
14636                Binder.restoreCallingIdentity(identity);
14637            }
14638        }
14639    }
14640
14641    @Override
14642    public int getPreferredActivities(List<IntentFilter> outFilters,
14643            List<ComponentName> outActivities, String packageName) {
14644
14645        int num = 0;
14646        final int userId = UserHandle.getCallingUserId();
14647        // reader
14648        synchronized (mPackages) {
14649            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14650            if (pir != null) {
14651                final Iterator<PreferredActivity> it = pir.filterIterator();
14652                while (it.hasNext()) {
14653                    final PreferredActivity pa = it.next();
14654                    if (packageName == null
14655                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14656                                    && pa.mPref.mAlways)) {
14657                        if (outFilters != null) {
14658                            outFilters.add(new IntentFilter(pa));
14659                        }
14660                        if (outActivities != null) {
14661                            outActivities.add(pa.mPref.mComponent);
14662                        }
14663                    }
14664                }
14665            }
14666        }
14667
14668        return num;
14669    }
14670
14671    @Override
14672    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14673            int userId) {
14674        int callingUid = Binder.getCallingUid();
14675        if (callingUid != Process.SYSTEM_UID) {
14676            throw new SecurityException(
14677                    "addPersistentPreferredActivity can only be run by the system");
14678        }
14679        if (filter.countActions() == 0) {
14680            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14681            return;
14682        }
14683        synchronized (mPackages) {
14684            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14685                    " :");
14686            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14687            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14688                    new PersistentPreferredActivity(filter, activity));
14689            scheduleWritePackageRestrictionsLocked(userId);
14690        }
14691    }
14692
14693    @Override
14694    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14695        int callingUid = Binder.getCallingUid();
14696        if (callingUid != Process.SYSTEM_UID) {
14697            throw new SecurityException(
14698                    "clearPackagePersistentPreferredActivities can only be run by the system");
14699        }
14700        ArrayList<PersistentPreferredActivity> removed = null;
14701        boolean changed = false;
14702        synchronized (mPackages) {
14703            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14704                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14705                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14706                        .valueAt(i);
14707                if (userId != thisUserId) {
14708                    continue;
14709                }
14710                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14711                while (it.hasNext()) {
14712                    PersistentPreferredActivity ppa = it.next();
14713                    // Mark entry for removal only if it matches the package name.
14714                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14715                        if (removed == null) {
14716                            removed = new ArrayList<PersistentPreferredActivity>();
14717                        }
14718                        removed.add(ppa);
14719                    }
14720                }
14721                if (removed != null) {
14722                    for (int j=0; j<removed.size(); j++) {
14723                        PersistentPreferredActivity ppa = removed.get(j);
14724                        ppir.removeFilter(ppa);
14725                    }
14726                    changed = true;
14727                }
14728            }
14729
14730            if (changed) {
14731                scheduleWritePackageRestrictionsLocked(userId);
14732            }
14733        }
14734    }
14735
14736    /**
14737     * Common machinery for picking apart a restored XML blob and passing
14738     * it to a caller-supplied functor to be applied to the running system.
14739     */
14740    private void restoreFromXml(XmlPullParser parser, int userId,
14741            String expectedStartTag, BlobXmlRestorer functor)
14742            throws IOException, XmlPullParserException {
14743        int type;
14744        while ((type = parser.next()) != XmlPullParser.START_TAG
14745                && type != XmlPullParser.END_DOCUMENT) {
14746        }
14747        if (type != XmlPullParser.START_TAG) {
14748            // oops didn't find a start tag?!
14749            if (DEBUG_BACKUP) {
14750                Slog.e(TAG, "Didn't find start tag during restore");
14751            }
14752            return;
14753        }
14754
14755        // this is supposed to be TAG_PREFERRED_BACKUP
14756        if (!expectedStartTag.equals(parser.getName())) {
14757            if (DEBUG_BACKUP) {
14758                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14759            }
14760            return;
14761        }
14762
14763        // skip interfering stuff, then we're aligned with the backing implementation
14764        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14765        functor.apply(parser, userId);
14766    }
14767
14768    private interface BlobXmlRestorer {
14769        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14770    }
14771
14772    /**
14773     * Non-Binder method, support for the backup/restore mechanism: write the
14774     * full set of preferred activities in its canonical XML format.  Returns the
14775     * XML output as a byte array, or null if there is none.
14776     */
14777    @Override
14778    public byte[] getPreferredActivityBackup(int userId) {
14779        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14780            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14781        }
14782
14783        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14784        try {
14785            final XmlSerializer serializer = new FastXmlSerializer();
14786            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14787            serializer.startDocument(null, true);
14788            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14789
14790            synchronized (mPackages) {
14791                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14792            }
14793
14794            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14795            serializer.endDocument();
14796            serializer.flush();
14797        } catch (Exception e) {
14798            if (DEBUG_BACKUP) {
14799                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14800            }
14801            return null;
14802        }
14803
14804        return dataStream.toByteArray();
14805    }
14806
14807    @Override
14808    public void restorePreferredActivities(byte[] backup, int userId) {
14809        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14810            throw new SecurityException("Only the system may call restorePreferredActivities()");
14811        }
14812
14813        try {
14814            final XmlPullParser parser = Xml.newPullParser();
14815            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14816            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14817                    new BlobXmlRestorer() {
14818                        @Override
14819                        public void apply(XmlPullParser parser, int userId)
14820                                throws XmlPullParserException, IOException {
14821                            synchronized (mPackages) {
14822                                mSettings.readPreferredActivitiesLPw(parser, userId);
14823                            }
14824                        }
14825                    } );
14826        } catch (Exception e) {
14827            if (DEBUG_BACKUP) {
14828                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14829            }
14830        }
14831    }
14832
14833    /**
14834     * Non-Binder method, support for the backup/restore mechanism: write the
14835     * default browser (etc) settings in its canonical XML format.  Returns the default
14836     * browser XML representation as a byte array, or null if there is none.
14837     */
14838    @Override
14839    public byte[] getDefaultAppsBackup(int userId) {
14840        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14841            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14842        }
14843
14844        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14845        try {
14846            final XmlSerializer serializer = new FastXmlSerializer();
14847            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14848            serializer.startDocument(null, true);
14849            serializer.startTag(null, TAG_DEFAULT_APPS);
14850
14851            synchronized (mPackages) {
14852                mSettings.writeDefaultAppsLPr(serializer, userId);
14853            }
14854
14855            serializer.endTag(null, TAG_DEFAULT_APPS);
14856            serializer.endDocument();
14857            serializer.flush();
14858        } catch (Exception e) {
14859            if (DEBUG_BACKUP) {
14860                Slog.e(TAG, "Unable to write default apps for backup", e);
14861            }
14862            return null;
14863        }
14864
14865        return dataStream.toByteArray();
14866    }
14867
14868    @Override
14869    public void restoreDefaultApps(byte[] backup, int userId) {
14870        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14871            throw new SecurityException("Only the system may call restoreDefaultApps()");
14872        }
14873
14874        try {
14875            final XmlPullParser parser = Xml.newPullParser();
14876            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14877            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14878                    new BlobXmlRestorer() {
14879                        @Override
14880                        public void apply(XmlPullParser parser, int userId)
14881                                throws XmlPullParserException, IOException {
14882                            synchronized (mPackages) {
14883                                mSettings.readDefaultAppsLPw(parser, userId);
14884                            }
14885                        }
14886                    } );
14887        } catch (Exception e) {
14888            if (DEBUG_BACKUP) {
14889                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14890            }
14891        }
14892    }
14893
14894    @Override
14895    public byte[] getIntentFilterVerificationBackup(int userId) {
14896        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14897            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14898        }
14899
14900        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14901        try {
14902            final XmlSerializer serializer = new FastXmlSerializer();
14903            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14904            serializer.startDocument(null, true);
14905            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14906
14907            synchronized (mPackages) {
14908                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14909            }
14910
14911            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14912            serializer.endDocument();
14913            serializer.flush();
14914        } catch (Exception e) {
14915            if (DEBUG_BACKUP) {
14916                Slog.e(TAG, "Unable to write default apps for backup", e);
14917            }
14918            return null;
14919        }
14920
14921        return dataStream.toByteArray();
14922    }
14923
14924    @Override
14925    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14926        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14927            throw new SecurityException("Only the system may call restorePreferredActivities()");
14928        }
14929
14930        try {
14931            final XmlPullParser parser = Xml.newPullParser();
14932            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14933            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14934                    new BlobXmlRestorer() {
14935                        @Override
14936                        public void apply(XmlPullParser parser, int userId)
14937                                throws XmlPullParserException, IOException {
14938                            synchronized (mPackages) {
14939                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14940                                mSettings.writeLPr();
14941                            }
14942                        }
14943                    } );
14944        } catch (Exception e) {
14945            if (DEBUG_BACKUP) {
14946                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14947            }
14948        }
14949    }
14950
14951    @Override
14952    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14953            int sourceUserId, int targetUserId, int flags) {
14954        mContext.enforceCallingOrSelfPermission(
14955                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14956        int callingUid = Binder.getCallingUid();
14957        enforceOwnerRights(ownerPackage, callingUid);
14958        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14959        if (intentFilter.countActions() == 0) {
14960            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14961            return;
14962        }
14963        synchronized (mPackages) {
14964            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14965                    ownerPackage, targetUserId, flags);
14966            CrossProfileIntentResolver resolver =
14967                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14968            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14969            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14970            if (existing != null) {
14971                int size = existing.size();
14972                for (int i = 0; i < size; i++) {
14973                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14974                        return;
14975                    }
14976                }
14977            }
14978            resolver.addFilter(newFilter);
14979            scheduleWritePackageRestrictionsLocked(sourceUserId);
14980        }
14981    }
14982
14983    @Override
14984    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14985        mContext.enforceCallingOrSelfPermission(
14986                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14987        int callingUid = Binder.getCallingUid();
14988        enforceOwnerRights(ownerPackage, callingUid);
14989        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14990        synchronized (mPackages) {
14991            CrossProfileIntentResolver resolver =
14992                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14993            ArraySet<CrossProfileIntentFilter> set =
14994                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14995            for (CrossProfileIntentFilter filter : set) {
14996                if (filter.getOwnerPackage().equals(ownerPackage)) {
14997                    resolver.removeFilter(filter);
14998                }
14999            }
15000            scheduleWritePackageRestrictionsLocked(sourceUserId);
15001        }
15002    }
15003
15004    // Enforcing that callingUid is owning pkg on userId
15005    private void enforceOwnerRights(String pkg, int callingUid) {
15006        // The system owns everything.
15007        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15008            return;
15009        }
15010        int callingUserId = UserHandle.getUserId(callingUid);
15011        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15012        if (pi == null) {
15013            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15014                    + callingUserId);
15015        }
15016        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15017            throw new SecurityException("Calling uid " + callingUid
15018                    + " does not own package " + pkg);
15019        }
15020    }
15021
15022    @Override
15023    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15024        Intent intent = new Intent(Intent.ACTION_MAIN);
15025        intent.addCategory(Intent.CATEGORY_HOME);
15026
15027        final int callingUserId = UserHandle.getCallingUserId();
15028        List<ResolveInfo> list = queryIntentActivities(intent, null,
15029                PackageManager.GET_META_DATA, callingUserId);
15030        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15031                true, false, false, callingUserId);
15032
15033        allHomeCandidates.clear();
15034        if (list != null) {
15035            for (ResolveInfo ri : list) {
15036                allHomeCandidates.add(ri);
15037            }
15038        }
15039        return (preferred == null || preferred.activityInfo == null)
15040                ? null
15041                : new ComponentName(preferred.activityInfo.packageName,
15042                        preferred.activityInfo.name);
15043    }
15044
15045    @Override
15046    public void setApplicationEnabledSetting(String appPackageName,
15047            int newState, int flags, int userId, String callingPackage) {
15048        if (!sUserManager.exists(userId)) return;
15049        if (callingPackage == null) {
15050            callingPackage = Integer.toString(Binder.getCallingUid());
15051        }
15052        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15053    }
15054
15055    @Override
15056    public void setComponentEnabledSetting(ComponentName componentName,
15057            int newState, int flags, int userId) {
15058        if (!sUserManager.exists(userId)) return;
15059        setEnabledSetting(componentName.getPackageName(),
15060                componentName.getClassName(), newState, flags, userId, null);
15061    }
15062
15063    private void setEnabledSetting(final String packageName, String className, int newState,
15064            final int flags, int userId, String callingPackage) {
15065        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15066              || newState == COMPONENT_ENABLED_STATE_ENABLED
15067              || newState == COMPONENT_ENABLED_STATE_DISABLED
15068              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15069              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15070            throw new IllegalArgumentException("Invalid new component state: "
15071                    + newState);
15072        }
15073        PackageSetting pkgSetting;
15074        final int uid = Binder.getCallingUid();
15075        final int permission = mContext.checkCallingOrSelfPermission(
15076                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15077        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15078        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15079        boolean sendNow = false;
15080        boolean isApp = (className == null);
15081        String componentName = isApp ? packageName : className;
15082        int packageUid = -1;
15083        ArrayList<String> components;
15084
15085        // writer
15086        synchronized (mPackages) {
15087            pkgSetting = mSettings.mPackages.get(packageName);
15088            if (pkgSetting == null) {
15089                if (className == null) {
15090                    throw new IllegalArgumentException(
15091                            "Unknown package: " + packageName);
15092                }
15093                throw new IllegalArgumentException(
15094                        "Unknown component: " + packageName
15095                        + "/" + className);
15096            }
15097            // Allow root and verify that userId is not being specified by a different user
15098            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15099                throw new SecurityException(
15100                        "Permission Denial: attempt to change component state from pid="
15101                        + Binder.getCallingPid()
15102                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15103            }
15104            if (className == null) {
15105                // We're dealing with an application/package level state change
15106                if (pkgSetting.getEnabled(userId) == newState) {
15107                    // Nothing to do
15108                    return;
15109                }
15110                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15111                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15112                    // Don't care about who enables an app.
15113                    callingPackage = null;
15114                }
15115                pkgSetting.setEnabled(newState, userId, callingPackage);
15116                // pkgSetting.pkg.mSetEnabled = newState;
15117            } else {
15118                // We're dealing with a component level state change
15119                // First, verify that this is a valid class name.
15120                PackageParser.Package pkg = pkgSetting.pkg;
15121                if (pkg == null || !pkg.hasComponentClassName(className)) {
15122                    if (pkg != null &&
15123                            pkg.applicationInfo.targetSdkVersion >=
15124                                    Build.VERSION_CODES.JELLY_BEAN) {
15125                        throw new IllegalArgumentException("Component class " + className
15126                                + " does not exist in " + packageName);
15127                    } else {
15128                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15129                                + className + " does not exist in " + packageName);
15130                    }
15131                }
15132                switch (newState) {
15133                case COMPONENT_ENABLED_STATE_ENABLED:
15134                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15135                        return;
15136                    }
15137                    break;
15138                case COMPONENT_ENABLED_STATE_DISABLED:
15139                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15140                        return;
15141                    }
15142                    break;
15143                case COMPONENT_ENABLED_STATE_DEFAULT:
15144                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15145                        return;
15146                    }
15147                    break;
15148                default:
15149                    Slog.e(TAG, "Invalid new component state: " + newState);
15150                    return;
15151                }
15152            }
15153            scheduleWritePackageRestrictionsLocked(userId);
15154            components = mPendingBroadcasts.get(userId, packageName);
15155            final boolean newPackage = components == null;
15156            if (newPackage) {
15157                components = new ArrayList<String>();
15158            }
15159            if (!components.contains(componentName)) {
15160                components.add(componentName);
15161            }
15162            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15163                sendNow = true;
15164                // Purge entry from pending broadcast list if another one exists already
15165                // since we are sending one right away.
15166                mPendingBroadcasts.remove(userId, packageName);
15167            } else {
15168                if (newPackage) {
15169                    mPendingBroadcasts.put(userId, packageName, components);
15170                }
15171                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15172                    // Schedule a message
15173                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15174                }
15175            }
15176        }
15177
15178        long callingId = Binder.clearCallingIdentity();
15179        try {
15180            if (sendNow) {
15181                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15182                sendPackageChangedBroadcast(packageName,
15183                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15184            }
15185        } finally {
15186            Binder.restoreCallingIdentity(callingId);
15187        }
15188    }
15189
15190    private void sendPackageChangedBroadcast(String packageName,
15191            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15192        if (DEBUG_INSTALL)
15193            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15194                    + componentNames);
15195        Bundle extras = new Bundle(4);
15196        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15197        String nameList[] = new String[componentNames.size()];
15198        componentNames.toArray(nameList);
15199        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15200        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15201        extras.putInt(Intent.EXTRA_UID, packageUid);
15202        // If this is not reporting a change of the overall package, then only send it
15203        // to registered receivers.  We don't want to launch a swath of apps for every
15204        // little component state change.
15205        final int flags = !componentNames.contains(packageName)
15206                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15207        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15208                new int[] {UserHandle.getUserId(packageUid)});
15209    }
15210
15211    @Override
15212    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15213        if (!sUserManager.exists(userId)) return;
15214        final int uid = Binder.getCallingUid();
15215        final int permission = mContext.checkCallingOrSelfPermission(
15216                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15217        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15218        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15219        // writer
15220        synchronized (mPackages) {
15221            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15222                    allowedByPermission, uid, userId)) {
15223                scheduleWritePackageRestrictionsLocked(userId);
15224            }
15225        }
15226    }
15227
15228    @Override
15229    public String getInstallerPackageName(String packageName) {
15230        // reader
15231        synchronized (mPackages) {
15232            return mSettings.getInstallerPackageNameLPr(packageName);
15233        }
15234    }
15235
15236    @Override
15237    public int getApplicationEnabledSetting(String packageName, int userId) {
15238        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15239        int uid = Binder.getCallingUid();
15240        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15241        // reader
15242        synchronized (mPackages) {
15243            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15244        }
15245    }
15246
15247    @Override
15248    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15249        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15250        int uid = Binder.getCallingUid();
15251        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15252        // reader
15253        synchronized (mPackages) {
15254            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15255        }
15256    }
15257
15258    @Override
15259    public void enterSafeMode() {
15260        enforceSystemOrRoot("Only the system can request entering safe mode");
15261
15262        if (!mSystemReady) {
15263            mSafeMode = true;
15264        }
15265    }
15266
15267    @Override
15268    public void systemReady() {
15269        mSystemReady = true;
15270
15271        // Read the compatibilty setting when the system is ready.
15272        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15273                mContext.getContentResolver(),
15274                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15275        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15276        if (DEBUG_SETTINGS) {
15277            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15278        }
15279
15280        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15281
15282        synchronized (mPackages) {
15283            // Verify that all of the preferred activity components actually
15284            // exist.  It is possible for applications to be updated and at
15285            // that point remove a previously declared activity component that
15286            // had been set as a preferred activity.  We try to clean this up
15287            // the next time we encounter that preferred activity, but it is
15288            // possible for the user flow to never be able to return to that
15289            // situation so here we do a sanity check to make sure we haven't
15290            // left any junk around.
15291            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15292            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15293                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15294                removed.clear();
15295                for (PreferredActivity pa : pir.filterSet()) {
15296                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15297                        removed.add(pa);
15298                    }
15299                }
15300                if (removed.size() > 0) {
15301                    for (int r=0; r<removed.size(); r++) {
15302                        PreferredActivity pa = removed.get(r);
15303                        Slog.w(TAG, "Removing dangling preferred activity: "
15304                                + pa.mPref.mComponent);
15305                        pir.removeFilter(pa);
15306                    }
15307                    mSettings.writePackageRestrictionsLPr(
15308                            mSettings.mPreferredActivities.keyAt(i));
15309                }
15310            }
15311
15312            for (int userId : UserManagerService.getInstance().getUserIds()) {
15313                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15314                    grantPermissionsUserIds = ArrayUtils.appendInt(
15315                            grantPermissionsUserIds, userId);
15316                }
15317            }
15318        }
15319        sUserManager.systemReady();
15320
15321        // If we upgraded grant all default permissions before kicking off.
15322        for (int userId : grantPermissionsUserIds) {
15323            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15324        }
15325
15326        // Kick off any messages waiting for system ready
15327        if (mPostSystemReadyMessages != null) {
15328            for (Message msg : mPostSystemReadyMessages) {
15329                msg.sendToTarget();
15330            }
15331            mPostSystemReadyMessages = null;
15332        }
15333
15334        // Watch for external volumes that come and go over time
15335        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15336        storage.registerListener(mStorageListener);
15337
15338        mInstallerService.systemReady();
15339        mPackageDexOptimizer.systemReady();
15340
15341        MountServiceInternal mountServiceInternal = LocalServices.getService(
15342                MountServiceInternal.class);
15343        mountServiceInternal.addExternalStoragePolicy(
15344                new MountServiceInternal.ExternalStorageMountPolicy() {
15345            @Override
15346            public int getMountMode(int uid, String packageName) {
15347                if (Process.isIsolated(uid)) {
15348                    return Zygote.MOUNT_EXTERNAL_NONE;
15349                }
15350                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15351                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15352                }
15353                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15354                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15355                }
15356                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15357                    return Zygote.MOUNT_EXTERNAL_READ;
15358                }
15359                return Zygote.MOUNT_EXTERNAL_WRITE;
15360            }
15361
15362            @Override
15363            public boolean hasExternalStorage(int uid, String packageName) {
15364                return true;
15365            }
15366        });
15367    }
15368
15369    @Override
15370    public boolean isSafeMode() {
15371        return mSafeMode;
15372    }
15373
15374    @Override
15375    public boolean hasSystemUidErrors() {
15376        return mHasSystemUidErrors;
15377    }
15378
15379    static String arrayToString(int[] array) {
15380        StringBuffer buf = new StringBuffer(128);
15381        buf.append('[');
15382        if (array != null) {
15383            for (int i=0; i<array.length; i++) {
15384                if (i > 0) buf.append(", ");
15385                buf.append(array[i]);
15386            }
15387        }
15388        buf.append(']');
15389        return buf.toString();
15390    }
15391
15392    static class DumpState {
15393        public static final int DUMP_LIBS = 1 << 0;
15394        public static final int DUMP_FEATURES = 1 << 1;
15395        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15396        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15397        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15398        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15399        public static final int DUMP_PERMISSIONS = 1 << 6;
15400        public static final int DUMP_PACKAGES = 1 << 7;
15401        public static final int DUMP_SHARED_USERS = 1 << 8;
15402        public static final int DUMP_MESSAGES = 1 << 9;
15403        public static final int DUMP_PROVIDERS = 1 << 10;
15404        public static final int DUMP_VERIFIERS = 1 << 11;
15405        public static final int DUMP_PREFERRED = 1 << 12;
15406        public static final int DUMP_PREFERRED_XML = 1 << 13;
15407        public static final int DUMP_KEYSETS = 1 << 14;
15408        public static final int DUMP_VERSION = 1 << 15;
15409        public static final int DUMP_INSTALLS = 1 << 16;
15410        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15411        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15412
15413        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15414
15415        private int mTypes;
15416
15417        private int mOptions;
15418
15419        private boolean mTitlePrinted;
15420
15421        private SharedUserSetting mSharedUser;
15422
15423        public boolean isDumping(int type) {
15424            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15425                return true;
15426            }
15427
15428            return (mTypes & type) != 0;
15429        }
15430
15431        public void setDump(int type) {
15432            mTypes |= type;
15433        }
15434
15435        public boolean isOptionEnabled(int option) {
15436            return (mOptions & option) != 0;
15437        }
15438
15439        public void setOptionEnabled(int option) {
15440            mOptions |= option;
15441        }
15442
15443        public boolean onTitlePrinted() {
15444            final boolean printed = mTitlePrinted;
15445            mTitlePrinted = true;
15446            return printed;
15447        }
15448
15449        public boolean getTitlePrinted() {
15450            return mTitlePrinted;
15451        }
15452
15453        public void setTitlePrinted(boolean enabled) {
15454            mTitlePrinted = enabled;
15455        }
15456
15457        public SharedUserSetting getSharedUser() {
15458            return mSharedUser;
15459        }
15460
15461        public void setSharedUser(SharedUserSetting user) {
15462            mSharedUser = user;
15463        }
15464    }
15465
15466    @Override
15467    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15468            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15469        (new PackageManagerShellCommand(this)).exec(
15470                this, in, out, err, args, resultReceiver);
15471    }
15472
15473    @Override
15474    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15475        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15476                != PackageManager.PERMISSION_GRANTED) {
15477            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15478                    + Binder.getCallingPid()
15479                    + ", uid=" + Binder.getCallingUid()
15480                    + " without permission "
15481                    + android.Manifest.permission.DUMP);
15482            return;
15483        }
15484
15485        DumpState dumpState = new DumpState();
15486        boolean fullPreferred = false;
15487        boolean checkin = false;
15488
15489        String packageName = null;
15490        ArraySet<String> permissionNames = null;
15491
15492        int opti = 0;
15493        while (opti < args.length) {
15494            String opt = args[opti];
15495            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15496                break;
15497            }
15498            opti++;
15499
15500            if ("-a".equals(opt)) {
15501                // Right now we only know how to print all.
15502            } else if ("-h".equals(opt)) {
15503                pw.println("Package manager dump options:");
15504                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15505                pw.println("    --checkin: dump for a checkin");
15506                pw.println("    -f: print details of intent filters");
15507                pw.println("    -h: print this help");
15508                pw.println("  cmd may be one of:");
15509                pw.println("    l[ibraries]: list known shared libraries");
15510                pw.println("    f[eatures]: list device features");
15511                pw.println("    k[eysets]: print known keysets");
15512                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15513                pw.println("    perm[issions]: dump permissions");
15514                pw.println("    permission [name ...]: dump declaration and use of given permission");
15515                pw.println("    pref[erred]: print preferred package settings");
15516                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15517                pw.println("    prov[iders]: dump content providers");
15518                pw.println("    p[ackages]: dump installed packages");
15519                pw.println("    s[hared-users]: dump shared user IDs");
15520                pw.println("    m[essages]: print collected runtime messages");
15521                pw.println("    v[erifiers]: print package verifier info");
15522                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15523                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15524                pw.println("    version: print database version info");
15525                pw.println("    write: write current settings now");
15526                pw.println("    installs: details about install sessions");
15527                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15528                pw.println("    <package.name>: info about given package");
15529                return;
15530            } else if ("--checkin".equals(opt)) {
15531                checkin = true;
15532            } else if ("-f".equals(opt)) {
15533                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15534            } else {
15535                pw.println("Unknown argument: " + opt + "; use -h for help");
15536            }
15537        }
15538
15539        // Is the caller requesting to dump a particular piece of data?
15540        if (opti < args.length) {
15541            String cmd = args[opti];
15542            opti++;
15543            // Is this a package name?
15544            if ("android".equals(cmd) || cmd.contains(".")) {
15545                packageName = cmd;
15546                // When dumping a single package, we always dump all of its
15547                // filter information since the amount of data will be reasonable.
15548                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15549            } else if ("check-permission".equals(cmd)) {
15550                if (opti >= args.length) {
15551                    pw.println("Error: check-permission missing permission argument");
15552                    return;
15553                }
15554                String perm = args[opti];
15555                opti++;
15556                if (opti >= args.length) {
15557                    pw.println("Error: check-permission missing package argument");
15558                    return;
15559                }
15560                String pkg = args[opti];
15561                opti++;
15562                int user = UserHandle.getUserId(Binder.getCallingUid());
15563                if (opti < args.length) {
15564                    try {
15565                        user = Integer.parseInt(args[opti]);
15566                    } catch (NumberFormatException e) {
15567                        pw.println("Error: check-permission user argument is not a number: "
15568                                + args[opti]);
15569                        return;
15570                    }
15571                }
15572                pw.println(checkPermission(perm, pkg, user));
15573                return;
15574            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15575                dumpState.setDump(DumpState.DUMP_LIBS);
15576            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15577                dumpState.setDump(DumpState.DUMP_FEATURES);
15578            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15579                if (opti >= args.length) {
15580                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15581                            | DumpState.DUMP_SERVICE_RESOLVERS
15582                            | DumpState.DUMP_RECEIVER_RESOLVERS
15583                            | DumpState.DUMP_CONTENT_RESOLVERS);
15584                } else {
15585                    while (opti < args.length) {
15586                        String name = args[opti];
15587                        if ("a".equals(name) || "activity".equals(name)) {
15588                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15589                        } else if ("s".equals(name) || "service".equals(name)) {
15590                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15591                        } else if ("r".equals(name) || "receiver".equals(name)) {
15592                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15593                        } else if ("c".equals(name) || "content".equals(name)) {
15594                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15595                        } else {
15596                            pw.println("Error: unknown resolver table type: " + name);
15597                            return;
15598                        }
15599                        opti++;
15600                    }
15601                }
15602            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15603                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15604            } else if ("permission".equals(cmd)) {
15605                if (opti >= args.length) {
15606                    pw.println("Error: permission requires permission name");
15607                    return;
15608                }
15609                permissionNames = new ArraySet<>();
15610                while (opti < args.length) {
15611                    permissionNames.add(args[opti]);
15612                    opti++;
15613                }
15614                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15615                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15616            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15617                dumpState.setDump(DumpState.DUMP_PREFERRED);
15618            } else if ("preferred-xml".equals(cmd)) {
15619                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15620                if (opti < args.length && "--full".equals(args[opti])) {
15621                    fullPreferred = true;
15622                    opti++;
15623                }
15624            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15625                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15626            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15627                dumpState.setDump(DumpState.DUMP_PACKAGES);
15628            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15629                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15630            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15631                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15632            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15633                dumpState.setDump(DumpState.DUMP_MESSAGES);
15634            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15635                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15636            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15637                    || "intent-filter-verifiers".equals(cmd)) {
15638                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15639            } else if ("version".equals(cmd)) {
15640                dumpState.setDump(DumpState.DUMP_VERSION);
15641            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15642                dumpState.setDump(DumpState.DUMP_KEYSETS);
15643            } else if ("installs".equals(cmd)) {
15644                dumpState.setDump(DumpState.DUMP_INSTALLS);
15645            } else if ("write".equals(cmd)) {
15646                synchronized (mPackages) {
15647                    mSettings.writeLPr();
15648                    pw.println("Settings written.");
15649                    return;
15650                }
15651            }
15652        }
15653
15654        if (checkin) {
15655            pw.println("vers,1");
15656        }
15657
15658        // reader
15659        synchronized (mPackages) {
15660            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15661                if (!checkin) {
15662                    if (dumpState.onTitlePrinted())
15663                        pw.println();
15664                    pw.println("Database versions:");
15665                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15666                }
15667            }
15668
15669            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15670                if (!checkin) {
15671                    if (dumpState.onTitlePrinted())
15672                        pw.println();
15673                    pw.println("Verifiers:");
15674                    pw.print("  Required: ");
15675                    pw.print(mRequiredVerifierPackage);
15676                    pw.print(" (uid=");
15677                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15678                    pw.println(")");
15679                } else if (mRequiredVerifierPackage != null) {
15680                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15681                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15682                }
15683            }
15684
15685            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15686                    packageName == null) {
15687                if (mIntentFilterVerifierComponent != null) {
15688                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15689                    if (!checkin) {
15690                        if (dumpState.onTitlePrinted())
15691                            pw.println();
15692                        pw.println("Intent Filter Verifier:");
15693                        pw.print("  Using: ");
15694                        pw.print(verifierPackageName);
15695                        pw.print(" (uid=");
15696                        pw.print(getPackageUid(verifierPackageName, 0));
15697                        pw.println(")");
15698                    } else if (verifierPackageName != null) {
15699                        pw.print("ifv,"); pw.print(verifierPackageName);
15700                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15701                    }
15702                } else {
15703                    pw.println();
15704                    pw.println("No Intent Filter Verifier available!");
15705                }
15706            }
15707
15708            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15709                boolean printedHeader = false;
15710                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15711                while (it.hasNext()) {
15712                    String name = it.next();
15713                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15714                    if (!checkin) {
15715                        if (!printedHeader) {
15716                            if (dumpState.onTitlePrinted())
15717                                pw.println();
15718                            pw.println("Libraries:");
15719                            printedHeader = true;
15720                        }
15721                        pw.print("  ");
15722                    } else {
15723                        pw.print("lib,");
15724                    }
15725                    pw.print(name);
15726                    if (!checkin) {
15727                        pw.print(" -> ");
15728                    }
15729                    if (ent.path != null) {
15730                        if (!checkin) {
15731                            pw.print("(jar) ");
15732                            pw.print(ent.path);
15733                        } else {
15734                            pw.print(",jar,");
15735                            pw.print(ent.path);
15736                        }
15737                    } else {
15738                        if (!checkin) {
15739                            pw.print("(apk) ");
15740                            pw.print(ent.apk);
15741                        } else {
15742                            pw.print(",apk,");
15743                            pw.print(ent.apk);
15744                        }
15745                    }
15746                    pw.println();
15747                }
15748            }
15749
15750            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15751                if (dumpState.onTitlePrinted())
15752                    pw.println();
15753                if (!checkin) {
15754                    pw.println("Features:");
15755                }
15756                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15757                while (it.hasNext()) {
15758                    String name = it.next();
15759                    if (!checkin) {
15760                        pw.print("  ");
15761                    } else {
15762                        pw.print("feat,");
15763                    }
15764                    pw.println(name);
15765                }
15766            }
15767
15768            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15769                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15770                        : "Activity Resolver Table:", "  ", packageName,
15771                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15772                    dumpState.setTitlePrinted(true);
15773                }
15774            }
15775            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15776                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15777                        : "Receiver Resolver Table:", "  ", packageName,
15778                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15779                    dumpState.setTitlePrinted(true);
15780                }
15781            }
15782            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15783                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15784                        : "Service Resolver Table:", "  ", packageName,
15785                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15786                    dumpState.setTitlePrinted(true);
15787                }
15788            }
15789            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15790                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15791                        : "Provider Resolver Table:", "  ", packageName,
15792                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15793                    dumpState.setTitlePrinted(true);
15794                }
15795            }
15796
15797            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15798                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15799                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15800                    int user = mSettings.mPreferredActivities.keyAt(i);
15801                    if (pir.dump(pw,
15802                            dumpState.getTitlePrinted()
15803                                ? "\nPreferred Activities User " + user + ":"
15804                                : "Preferred Activities User " + user + ":", "  ",
15805                            packageName, true, false)) {
15806                        dumpState.setTitlePrinted(true);
15807                    }
15808                }
15809            }
15810
15811            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15812                pw.flush();
15813                FileOutputStream fout = new FileOutputStream(fd);
15814                BufferedOutputStream str = new BufferedOutputStream(fout);
15815                XmlSerializer serializer = new FastXmlSerializer();
15816                try {
15817                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15818                    serializer.startDocument(null, true);
15819                    serializer.setFeature(
15820                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15821                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15822                    serializer.endDocument();
15823                    serializer.flush();
15824                } catch (IllegalArgumentException e) {
15825                    pw.println("Failed writing: " + e);
15826                } catch (IllegalStateException e) {
15827                    pw.println("Failed writing: " + e);
15828                } catch (IOException e) {
15829                    pw.println("Failed writing: " + e);
15830                }
15831            }
15832
15833            if (!checkin
15834                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15835                    && packageName == null) {
15836                pw.println();
15837                int count = mSettings.mPackages.size();
15838                if (count == 0) {
15839                    pw.println("No applications!");
15840                    pw.println();
15841                } else {
15842                    final String prefix = "  ";
15843                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15844                    if (allPackageSettings.size() == 0) {
15845                        pw.println("No domain preferred apps!");
15846                        pw.println();
15847                    } else {
15848                        pw.println("App verification status:");
15849                        pw.println();
15850                        count = 0;
15851                        for (PackageSetting ps : allPackageSettings) {
15852                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15853                            if (ivi == null || ivi.getPackageName() == null) continue;
15854                            pw.println(prefix + "Package: " + ivi.getPackageName());
15855                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15856                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15857                            pw.println();
15858                            count++;
15859                        }
15860                        if (count == 0) {
15861                            pw.println(prefix + "No app verification established.");
15862                            pw.println();
15863                        }
15864                        for (int userId : sUserManager.getUserIds()) {
15865                            pw.println("App linkages for user " + userId + ":");
15866                            pw.println();
15867                            count = 0;
15868                            for (PackageSetting ps : allPackageSettings) {
15869                                final long status = ps.getDomainVerificationStatusForUser(userId);
15870                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15871                                    continue;
15872                                }
15873                                pw.println(prefix + "Package: " + ps.name);
15874                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15875                                String statusStr = IntentFilterVerificationInfo.
15876                                        getStatusStringFromValue(status);
15877                                pw.println(prefix + "Status:  " + statusStr);
15878                                pw.println();
15879                                count++;
15880                            }
15881                            if (count == 0) {
15882                                pw.println(prefix + "No configured app linkages.");
15883                                pw.println();
15884                            }
15885                        }
15886                    }
15887                }
15888            }
15889
15890            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15891                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15892                if (packageName == null && permissionNames == null) {
15893                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15894                        if (iperm == 0) {
15895                            if (dumpState.onTitlePrinted())
15896                                pw.println();
15897                            pw.println("AppOp Permissions:");
15898                        }
15899                        pw.print("  AppOp Permission ");
15900                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15901                        pw.println(":");
15902                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15903                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15904                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15905                        }
15906                    }
15907                }
15908            }
15909
15910            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15911                boolean printedSomething = false;
15912                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15913                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15914                        continue;
15915                    }
15916                    if (!printedSomething) {
15917                        if (dumpState.onTitlePrinted())
15918                            pw.println();
15919                        pw.println("Registered ContentProviders:");
15920                        printedSomething = true;
15921                    }
15922                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15923                    pw.print("    "); pw.println(p.toString());
15924                }
15925                printedSomething = false;
15926                for (Map.Entry<String, PackageParser.Provider> entry :
15927                        mProvidersByAuthority.entrySet()) {
15928                    PackageParser.Provider p = entry.getValue();
15929                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15930                        continue;
15931                    }
15932                    if (!printedSomething) {
15933                        if (dumpState.onTitlePrinted())
15934                            pw.println();
15935                        pw.println("ContentProvider Authorities:");
15936                        printedSomething = true;
15937                    }
15938                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15939                    pw.print("    "); pw.println(p.toString());
15940                    if (p.info != null && p.info.applicationInfo != null) {
15941                        final String appInfo = p.info.applicationInfo.toString();
15942                        pw.print("      applicationInfo="); pw.println(appInfo);
15943                    }
15944                }
15945            }
15946
15947            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15948                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15949            }
15950
15951            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15952                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15953            }
15954
15955            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15956                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15957            }
15958
15959            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15960                // XXX should handle packageName != null by dumping only install data that
15961                // the given package is involved with.
15962                if (dumpState.onTitlePrinted()) pw.println();
15963                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15964            }
15965
15966            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15967                if (dumpState.onTitlePrinted()) pw.println();
15968                mSettings.dumpReadMessagesLPr(pw, dumpState);
15969
15970                pw.println();
15971                pw.println("Package warning messages:");
15972                BufferedReader in = null;
15973                String line = null;
15974                try {
15975                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15976                    while ((line = in.readLine()) != null) {
15977                        if (line.contains("ignored: updated version")) continue;
15978                        pw.println(line);
15979                    }
15980                } catch (IOException ignored) {
15981                } finally {
15982                    IoUtils.closeQuietly(in);
15983                }
15984            }
15985
15986            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15987                BufferedReader in = null;
15988                String line = null;
15989                try {
15990                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15991                    while ((line = in.readLine()) != null) {
15992                        if (line.contains("ignored: updated version")) continue;
15993                        pw.print("msg,");
15994                        pw.println(line);
15995                    }
15996                } catch (IOException ignored) {
15997                } finally {
15998                    IoUtils.closeQuietly(in);
15999                }
16000            }
16001        }
16002    }
16003
16004    private String dumpDomainString(String packageName) {
16005        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16006        List<IntentFilter> filters = getAllIntentFilters(packageName);
16007
16008        ArraySet<String> result = new ArraySet<>();
16009        if (iviList.size() > 0) {
16010            for (IntentFilterVerificationInfo ivi : iviList) {
16011                for (String host : ivi.getDomains()) {
16012                    result.add(host);
16013                }
16014            }
16015        }
16016        if (filters != null && filters.size() > 0) {
16017            for (IntentFilter filter : filters) {
16018                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16019                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16020                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16021                    result.addAll(filter.getHostsList());
16022                }
16023            }
16024        }
16025
16026        StringBuilder sb = new StringBuilder(result.size() * 16);
16027        for (String domain : result) {
16028            if (sb.length() > 0) sb.append(" ");
16029            sb.append(domain);
16030        }
16031        return sb.toString();
16032    }
16033
16034    // ------- apps on sdcard specific code -------
16035    static final boolean DEBUG_SD_INSTALL = false;
16036
16037    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16038
16039    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16040
16041    private boolean mMediaMounted = false;
16042
16043    static String getEncryptKey() {
16044        try {
16045            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16046                    SD_ENCRYPTION_KEYSTORE_NAME);
16047            if (sdEncKey == null) {
16048                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16049                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16050                if (sdEncKey == null) {
16051                    Slog.e(TAG, "Failed to create encryption keys");
16052                    return null;
16053                }
16054            }
16055            return sdEncKey;
16056        } catch (NoSuchAlgorithmException nsae) {
16057            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16058            return null;
16059        } catch (IOException ioe) {
16060            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16061            return null;
16062        }
16063    }
16064
16065    /*
16066     * Update media status on PackageManager.
16067     */
16068    @Override
16069    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16070        int callingUid = Binder.getCallingUid();
16071        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16072            throw new SecurityException("Media status can only be updated by the system");
16073        }
16074        // reader; this apparently protects mMediaMounted, but should probably
16075        // be a different lock in that case.
16076        synchronized (mPackages) {
16077            Log.i(TAG, "Updating external media status from "
16078                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16079                    + (mediaStatus ? "mounted" : "unmounted"));
16080            if (DEBUG_SD_INSTALL)
16081                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16082                        + ", mMediaMounted=" + mMediaMounted);
16083            if (mediaStatus == mMediaMounted) {
16084                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16085                        : 0, -1);
16086                mHandler.sendMessage(msg);
16087                return;
16088            }
16089            mMediaMounted = mediaStatus;
16090        }
16091        // Queue up an async operation since the package installation may take a
16092        // little while.
16093        mHandler.post(new Runnable() {
16094            public void run() {
16095                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16096            }
16097        });
16098    }
16099
16100    /**
16101     * Called by MountService when the initial ASECs to scan are available.
16102     * Should block until all the ASEC containers are finished being scanned.
16103     */
16104    public void scanAvailableAsecs() {
16105        updateExternalMediaStatusInner(true, false, false);
16106        if (mShouldRestoreconData) {
16107            SELinuxMMAC.setRestoreconDone();
16108            mShouldRestoreconData = false;
16109        }
16110    }
16111
16112    /*
16113     * Collect information of applications on external media, map them against
16114     * existing containers and update information based on current mount status.
16115     * Please note that we always have to report status if reportStatus has been
16116     * set to true especially when unloading packages.
16117     */
16118    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16119            boolean externalStorage) {
16120        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16121        int[] uidArr = EmptyArray.INT;
16122
16123        final String[] list = PackageHelper.getSecureContainerList();
16124        if (ArrayUtils.isEmpty(list)) {
16125            Log.i(TAG, "No secure containers found");
16126        } else {
16127            // Process list of secure containers and categorize them
16128            // as active or stale based on their package internal state.
16129
16130            // reader
16131            synchronized (mPackages) {
16132                for (String cid : list) {
16133                    // Leave stages untouched for now; installer service owns them
16134                    if (PackageInstallerService.isStageName(cid)) continue;
16135
16136                    if (DEBUG_SD_INSTALL)
16137                        Log.i(TAG, "Processing container " + cid);
16138                    String pkgName = getAsecPackageName(cid);
16139                    if (pkgName == null) {
16140                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16141                        continue;
16142                    }
16143                    if (DEBUG_SD_INSTALL)
16144                        Log.i(TAG, "Looking for pkg : " + pkgName);
16145
16146                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16147                    if (ps == null) {
16148                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16149                        continue;
16150                    }
16151
16152                    /*
16153                     * Skip packages that are not external if we're unmounting
16154                     * external storage.
16155                     */
16156                    if (externalStorage && !isMounted && !isExternal(ps)) {
16157                        continue;
16158                    }
16159
16160                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16161                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16162                    // The package status is changed only if the code path
16163                    // matches between settings and the container id.
16164                    if (ps.codePathString != null
16165                            && ps.codePathString.startsWith(args.getCodePath())) {
16166                        if (DEBUG_SD_INSTALL) {
16167                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16168                                    + " at code path: " + ps.codePathString);
16169                        }
16170
16171                        // We do have a valid package installed on sdcard
16172                        processCids.put(args, ps.codePathString);
16173                        final int uid = ps.appId;
16174                        if (uid != -1) {
16175                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16176                        }
16177                    } else {
16178                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16179                                + ps.codePathString);
16180                    }
16181                }
16182            }
16183
16184            Arrays.sort(uidArr);
16185        }
16186
16187        // Process packages with valid entries.
16188        if (isMounted) {
16189            if (DEBUG_SD_INSTALL)
16190                Log.i(TAG, "Loading packages");
16191            loadMediaPackages(processCids, uidArr, externalStorage);
16192            startCleaningPackages();
16193            mInstallerService.onSecureContainersAvailable();
16194        } else {
16195            if (DEBUG_SD_INSTALL)
16196                Log.i(TAG, "Unloading packages");
16197            unloadMediaPackages(processCids, uidArr, reportStatus);
16198        }
16199    }
16200
16201    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16202            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16203        final int size = infos.size();
16204        final String[] packageNames = new String[size];
16205        final int[] packageUids = new int[size];
16206        for (int i = 0; i < size; i++) {
16207            final ApplicationInfo info = infos.get(i);
16208            packageNames[i] = info.packageName;
16209            packageUids[i] = info.uid;
16210        }
16211        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16212                finishedReceiver);
16213    }
16214
16215    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16216            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16217        sendResourcesChangedBroadcast(mediaStatus, replacing,
16218                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16219    }
16220
16221    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16222            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16223        int size = pkgList.length;
16224        if (size > 0) {
16225            // Send broadcasts here
16226            Bundle extras = new Bundle();
16227            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16228            if (uidArr != null) {
16229                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16230            }
16231            if (replacing) {
16232                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16233            }
16234            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16235                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16236            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16237        }
16238    }
16239
16240   /*
16241     * Look at potentially valid container ids from processCids If package
16242     * information doesn't match the one on record or package scanning fails,
16243     * the cid is added to list of removeCids. We currently don't delete stale
16244     * containers.
16245     */
16246    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16247            boolean externalStorage) {
16248        ArrayList<String> pkgList = new ArrayList<String>();
16249        Set<AsecInstallArgs> keys = processCids.keySet();
16250
16251        for (AsecInstallArgs args : keys) {
16252            String codePath = processCids.get(args);
16253            if (DEBUG_SD_INSTALL)
16254                Log.i(TAG, "Loading container : " + args.cid);
16255            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16256            try {
16257                // Make sure there are no container errors first.
16258                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16259                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16260                            + " when installing from sdcard");
16261                    continue;
16262                }
16263                // Check code path here.
16264                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16265                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16266                            + " does not match one in settings " + codePath);
16267                    continue;
16268                }
16269                // Parse package
16270                int parseFlags = mDefParseFlags;
16271                if (args.isExternalAsec()) {
16272                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16273                }
16274                if (args.isFwdLocked()) {
16275                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16276                }
16277
16278                synchronized (mInstallLock) {
16279                    PackageParser.Package pkg = null;
16280                    try {
16281                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16282                    } catch (PackageManagerException e) {
16283                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16284                    }
16285                    // Scan the package
16286                    if (pkg != null) {
16287                        /*
16288                         * TODO why is the lock being held? doPostInstall is
16289                         * called in other places without the lock. This needs
16290                         * to be straightened out.
16291                         */
16292                        // writer
16293                        synchronized (mPackages) {
16294                            retCode = PackageManager.INSTALL_SUCCEEDED;
16295                            pkgList.add(pkg.packageName);
16296                            // Post process args
16297                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16298                                    pkg.applicationInfo.uid);
16299                        }
16300                    } else {
16301                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16302                    }
16303                }
16304
16305            } finally {
16306                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16307                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16308                }
16309            }
16310        }
16311        // writer
16312        synchronized (mPackages) {
16313            // If the platform SDK has changed since the last time we booted,
16314            // we need to re-grant app permission to catch any new ones that
16315            // appear. This is really a hack, and means that apps can in some
16316            // cases get permissions that the user didn't initially explicitly
16317            // allow... it would be nice to have some better way to handle
16318            // this situation.
16319            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16320                    : mSettings.getInternalVersion();
16321            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16322                    : StorageManager.UUID_PRIVATE_INTERNAL;
16323
16324            int updateFlags = UPDATE_PERMISSIONS_ALL;
16325            if (ver.sdkVersion != mSdkVersion) {
16326                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16327                        + mSdkVersion + "; regranting permissions for external");
16328                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16329            }
16330            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16331
16332            // Yay, everything is now upgraded
16333            ver.forceCurrent();
16334
16335            // can downgrade to reader
16336            // Persist settings
16337            mSettings.writeLPr();
16338        }
16339        // Send a broadcast to let everyone know we are done processing
16340        if (pkgList.size() > 0) {
16341            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16342        }
16343    }
16344
16345   /*
16346     * Utility method to unload a list of specified containers
16347     */
16348    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16349        // Just unmount all valid containers.
16350        for (AsecInstallArgs arg : cidArgs) {
16351            synchronized (mInstallLock) {
16352                arg.doPostDeleteLI(false);
16353           }
16354       }
16355   }
16356
16357    /*
16358     * Unload packages mounted on external media. This involves deleting package
16359     * data from internal structures, sending broadcasts about diabled packages,
16360     * gc'ing to free up references, unmounting all secure containers
16361     * corresponding to packages on external media, and posting a
16362     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16363     * that we always have to post this message if status has been requested no
16364     * matter what.
16365     */
16366    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16367            final boolean reportStatus) {
16368        if (DEBUG_SD_INSTALL)
16369            Log.i(TAG, "unloading media packages");
16370        ArrayList<String> pkgList = new ArrayList<String>();
16371        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16372        final Set<AsecInstallArgs> keys = processCids.keySet();
16373        for (AsecInstallArgs args : keys) {
16374            String pkgName = args.getPackageName();
16375            if (DEBUG_SD_INSTALL)
16376                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16377            // Delete package internally
16378            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16379            synchronized (mInstallLock) {
16380                boolean res = deletePackageLI(pkgName, null, false, null, null,
16381                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16382                if (res) {
16383                    pkgList.add(pkgName);
16384                } else {
16385                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16386                    failedList.add(args);
16387                }
16388            }
16389        }
16390
16391        // reader
16392        synchronized (mPackages) {
16393            // We didn't update the settings after removing each package;
16394            // write them now for all packages.
16395            mSettings.writeLPr();
16396        }
16397
16398        // We have to absolutely send UPDATED_MEDIA_STATUS only
16399        // after confirming that all the receivers processed the ordered
16400        // broadcast when packages get disabled, force a gc to clean things up.
16401        // and unload all the containers.
16402        if (pkgList.size() > 0) {
16403            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16404                    new IIntentReceiver.Stub() {
16405                public void performReceive(Intent intent, int resultCode, String data,
16406                        Bundle extras, boolean ordered, boolean sticky,
16407                        int sendingUser) throws RemoteException {
16408                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16409                            reportStatus ? 1 : 0, 1, keys);
16410                    mHandler.sendMessage(msg);
16411                }
16412            });
16413        } else {
16414            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16415                    keys);
16416            mHandler.sendMessage(msg);
16417        }
16418    }
16419
16420    private void loadPrivatePackages(final VolumeInfo vol) {
16421        mHandler.post(new Runnable() {
16422            @Override
16423            public void run() {
16424                loadPrivatePackagesInner(vol);
16425            }
16426        });
16427    }
16428
16429    private void loadPrivatePackagesInner(VolumeInfo vol) {
16430        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16431        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16432
16433        final VersionInfo ver;
16434        final List<PackageSetting> packages;
16435        synchronized (mPackages) {
16436            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16437            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16438        }
16439
16440        for (PackageSetting ps : packages) {
16441            synchronized (mInstallLock) {
16442                final PackageParser.Package pkg;
16443                try {
16444                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16445                    loaded.add(pkg.applicationInfo);
16446                } catch (PackageManagerException e) {
16447                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16448                }
16449
16450                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16451                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16452                }
16453            }
16454        }
16455
16456        synchronized (mPackages) {
16457            int updateFlags = UPDATE_PERMISSIONS_ALL;
16458            if (ver.sdkVersion != mSdkVersion) {
16459                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16460                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16461                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16462            }
16463            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16464
16465            // Yay, everything is now upgraded
16466            ver.forceCurrent();
16467
16468            mSettings.writeLPr();
16469        }
16470
16471        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16472        sendResourcesChangedBroadcast(true, false, loaded, null);
16473    }
16474
16475    private void unloadPrivatePackages(final VolumeInfo vol) {
16476        mHandler.post(new Runnable() {
16477            @Override
16478            public void run() {
16479                unloadPrivatePackagesInner(vol);
16480            }
16481        });
16482    }
16483
16484    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16485        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16486        synchronized (mInstallLock) {
16487        synchronized (mPackages) {
16488            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16489            for (PackageSetting ps : packages) {
16490                if (ps.pkg == null) continue;
16491
16492                final ApplicationInfo info = ps.pkg.applicationInfo;
16493                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16494                if (deletePackageLI(ps.name, null, false, null, null,
16495                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16496                    unloaded.add(info);
16497                } else {
16498                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16499                }
16500            }
16501
16502            mSettings.writeLPr();
16503        }
16504        }
16505
16506        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16507        sendResourcesChangedBroadcast(false, false, unloaded, null);
16508    }
16509
16510    /**
16511     * Examine all users present on given mounted volume, and destroy data
16512     * belonging to users that are no longer valid, or whose user ID has been
16513     * recycled.
16514     */
16515    private void reconcileUsers(String volumeUuid) {
16516        final File[] files = FileUtils
16517                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16518        for (File file : files) {
16519            if (!file.isDirectory()) continue;
16520
16521            final int userId;
16522            final UserInfo info;
16523            try {
16524                userId = Integer.parseInt(file.getName());
16525                info = sUserManager.getUserInfo(userId);
16526            } catch (NumberFormatException e) {
16527                Slog.w(TAG, "Invalid user directory " + file);
16528                continue;
16529            }
16530
16531            boolean destroyUser = false;
16532            if (info == null) {
16533                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16534                        + " because no matching user was found");
16535                destroyUser = true;
16536            } else {
16537                try {
16538                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16539                } catch (IOException e) {
16540                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16541                            + " because we failed to enforce serial number: " + e);
16542                    destroyUser = true;
16543                }
16544            }
16545
16546            if (destroyUser) {
16547                synchronized (mInstallLock) {
16548                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16549                }
16550            }
16551        }
16552
16553        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16554        final UserManager um = mContext.getSystemService(UserManager.class);
16555        for (UserInfo user : um.getUsers()) {
16556            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16557            if (userDir.exists()) continue;
16558
16559            try {
16560                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16561                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16562            } catch (IOException e) {
16563                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16564            }
16565        }
16566    }
16567
16568    /**
16569     * Examine all apps present on given mounted volume, and destroy apps that
16570     * aren't expected, either due to uninstallation or reinstallation on
16571     * another volume.
16572     */
16573    private void reconcileApps(String volumeUuid) {
16574        final File[] files = FileUtils
16575                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16576        for (File file : files) {
16577            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16578                    && !PackageInstallerService.isStageName(file.getName());
16579            if (!isPackage) {
16580                // Ignore entries which are not packages
16581                continue;
16582            }
16583
16584            boolean destroyApp = false;
16585            String packageName = null;
16586            try {
16587                final PackageLite pkg = PackageParser.parsePackageLite(file,
16588                        PackageParser.PARSE_MUST_BE_APK);
16589                packageName = pkg.packageName;
16590
16591                synchronized (mPackages) {
16592                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16593                    if (ps == null) {
16594                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16595                                + volumeUuid + " because we found no install record");
16596                        destroyApp = true;
16597                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16598                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16599                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16600                        destroyApp = true;
16601                    }
16602                }
16603
16604            } catch (PackageParserException e) {
16605                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16606                destroyApp = true;
16607            }
16608
16609            if (destroyApp) {
16610                synchronized (mInstallLock) {
16611                    if (packageName != null) {
16612                        removeDataDirsLI(volumeUuid, packageName);
16613                    }
16614                    if (file.isDirectory()) {
16615                        mInstaller.rmPackageDir(file.getAbsolutePath());
16616                    } else {
16617                        file.delete();
16618                    }
16619                }
16620            }
16621        }
16622    }
16623
16624    private void unfreezePackage(String packageName) {
16625        synchronized (mPackages) {
16626            final PackageSetting ps = mSettings.mPackages.get(packageName);
16627            if (ps != null) {
16628                ps.frozen = false;
16629            }
16630        }
16631    }
16632
16633    @Override
16634    public int movePackage(final String packageName, final String volumeUuid) {
16635        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16636
16637        final int moveId = mNextMoveId.getAndIncrement();
16638        mHandler.post(new Runnable() {
16639            @Override
16640            public void run() {
16641                try {
16642                    movePackageInternal(packageName, volumeUuid, moveId);
16643                } catch (PackageManagerException e) {
16644                    Slog.w(TAG, "Failed to move " + packageName, e);
16645                    mMoveCallbacks.notifyStatusChanged(moveId,
16646                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16647                }
16648            }
16649        });
16650        return moveId;
16651    }
16652
16653    private void movePackageInternal(final String packageName, final String volumeUuid,
16654            final int moveId) throws PackageManagerException {
16655        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16656        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16657        final PackageManager pm = mContext.getPackageManager();
16658
16659        final boolean currentAsec;
16660        final String currentVolumeUuid;
16661        final File codeFile;
16662        final String installerPackageName;
16663        final String packageAbiOverride;
16664        final int appId;
16665        final String seinfo;
16666        final String label;
16667
16668        // reader
16669        synchronized (mPackages) {
16670            final PackageParser.Package pkg = mPackages.get(packageName);
16671            final PackageSetting ps = mSettings.mPackages.get(packageName);
16672            if (pkg == null || ps == null) {
16673                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16674            }
16675
16676            if (pkg.applicationInfo.isSystemApp()) {
16677                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16678                        "Cannot move system application");
16679            }
16680
16681            if (pkg.applicationInfo.isExternalAsec()) {
16682                currentAsec = true;
16683                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16684            } else if (pkg.applicationInfo.isForwardLocked()) {
16685                currentAsec = true;
16686                currentVolumeUuid = "forward_locked";
16687            } else {
16688                currentAsec = false;
16689                currentVolumeUuid = ps.volumeUuid;
16690
16691                final File probe = new File(pkg.codePath);
16692                final File probeOat = new File(probe, "oat");
16693                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16694                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16695                            "Move only supported for modern cluster style installs");
16696                }
16697            }
16698
16699            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16700                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16701                        "Package already moved to " + volumeUuid);
16702            }
16703
16704            if (ps.frozen) {
16705                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16706                        "Failed to move already frozen package");
16707            }
16708            ps.frozen = true;
16709
16710            codeFile = new File(pkg.codePath);
16711            installerPackageName = ps.installerPackageName;
16712            packageAbiOverride = ps.cpuAbiOverrideString;
16713            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16714            seinfo = pkg.applicationInfo.seinfo;
16715            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16716        }
16717
16718        // Now that we're guarded by frozen state, kill app during move
16719        final long token = Binder.clearCallingIdentity();
16720        try {
16721            killApplication(packageName, appId, "move pkg");
16722        } finally {
16723            Binder.restoreCallingIdentity(token);
16724        }
16725
16726        final Bundle extras = new Bundle();
16727        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16728        extras.putString(Intent.EXTRA_TITLE, label);
16729        mMoveCallbacks.notifyCreated(moveId, extras);
16730
16731        int installFlags;
16732        final boolean moveCompleteApp;
16733        final File measurePath;
16734
16735        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16736            installFlags = INSTALL_INTERNAL;
16737            moveCompleteApp = !currentAsec;
16738            measurePath = Environment.getDataAppDirectory(volumeUuid);
16739        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16740            installFlags = INSTALL_EXTERNAL;
16741            moveCompleteApp = false;
16742            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16743        } else {
16744            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16745            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16746                    || !volume.isMountedWritable()) {
16747                unfreezePackage(packageName);
16748                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16749                        "Move location not mounted private volume");
16750            }
16751
16752            Preconditions.checkState(!currentAsec);
16753
16754            installFlags = INSTALL_INTERNAL;
16755            moveCompleteApp = true;
16756            measurePath = Environment.getDataAppDirectory(volumeUuid);
16757        }
16758
16759        final PackageStats stats = new PackageStats(null, -1);
16760        synchronized (mInstaller) {
16761            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16762                unfreezePackage(packageName);
16763                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16764                        "Failed to measure package size");
16765            }
16766        }
16767
16768        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16769                + stats.dataSize);
16770
16771        final long startFreeBytes = measurePath.getFreeSpace();
16772        final long sizeBytes;
16773        if (moveCompleteApp) {
16774            sizeBytes = stats.codeSize + stats.dataSize;
16775        } else {
16776            sizeBytes = stats.codeSize;
16777        }
16778
16779        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16780            unfreezePackage(packageName);
16781            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16782                    "Not enough free space to move");
16783        }
16784
16785        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16786
16787        final CountDownLatch installedLatch = new CountDownLatch(1);
16788        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16789            @Override
16790            public void onUserActionRequired(Intent intent) throws RemoteException {
16791                throw new IllegalStateException();
16792            }
16793
16794            @Override
16795            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16796                    Bundle extras) throws RemoteException {
16797                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16798                        + PackageManager.installStatusToString(returnCode, msg));
16799
16800                installedLatch.countDown();
16801
16802                // Regardless of success or failure of the move operation,
16803                // always unfreeze the package
16804                unfreezePackage(packageName);
16805
16806                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16807                switch (status) {
16808                    case PackageInstaller.STATUS_SUCCESS:
16809                        mMoveCallbacks.notifyStatusChanged(moveId,
16810                                PackageManager.MOVE_SUCCEEDED);
16811                        break;
16812                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16813                        mMoveCallbacks.notifyStatusChanged(moveId,
16814                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16815                        break;
16816                    default:
16817                        mMoveCallbacks.notifyStatusChanged(moveId,
16818                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16819                        break;
16820                }
16821            }
16822        };
16823
16824        final MoveInfo move;
16825        if (moveCompleteApp) {
16826            // Kick off a thread to report progress estimates
16827            new Thread() {
16828                @Override
16829                public void run() {
16830                    while (true) {
16831                        try {
16832                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16833                                break;
16834                            }
16835                        } catch (InterruptedException ignored) {
16836                        }
16837
16838                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16839                        final int progress = 10 + (int) MathUtils.constrain(
16840                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16841                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16842                    }
16843                }
16844            }.start();
16845
16846            final String dataAppName = codeFile.getName();
16847            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16848                    dataAppName, appId, seinfo);
16849        } else {
16850            move = null;
16851        }
16852
16853        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16854
16855        final Message msg = mHandler.obtainMessage(INIT_COPY);
16856        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16857        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16858                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16859        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16860        msg.obj = params;
16861
16862        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16863                System.identityHashCode(msg.obj));
16864        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16865                System.identityHashCode(msg.obj));
16866
16867        mHandler.sendMessage(msg);
16868    }
16869
16870    @Override
16871    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16872        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16873
16874        final int realMoveId = mNextMoveId.getAndIncrement();
16875        final Bundle extras = new Bundle();
16876        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16877        mMoveCallbacks.notifyCreated(realMoveId, extras);
16878
16879        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16880            @Override
16881            public void onCreated(int moveId, Bundle extras) {
16882                // Ignored
16883            }
16884
16885            @Override
16886            public void onStatusChanged(int moveId, int status, long estMillis) {
16887                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16888            }
16889        };
16890
16891        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16892        storage.setPrimaryStorageUuid(volumeUuid, callback);
16893        return realMoveId;
16894    }
16895
16896    @Override
16897    public int getMoveStatus(int moveId) {
16898        mContext.enforceCallingOrSelfPermission(
16899                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16900        return mMoveCallbacks.mLastStatus.get(moveId);
16901    }
16902
16903    @Override
16904    public void registerMoveCallback(IPackageMoveObserver callback) {
16905        mContext.enforceCallingOrSelfPermission(
16906                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16907        mMoveCallbacks.register(callback);
16908    }
16909
16910    @Override
16911    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16912        mContext.enforceCallingOrSelfPermission(
16913                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16914        mMoveCallbacks.unregister(callback);
16915    }
16916
16917    @Override
16918    public boolean setInstallLocation(int loc) {
16919        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16920                null);
16921        if (getInstallLocation() == loc) {
16922            return true;
16923        }
16924        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16925                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16926            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16927                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16928            return true;
16929        }
16930        return false;
16931   }
16932
16933    @Override
16934    public int getInstallLocation() {
16935        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16936                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16937                PackageHelper.APP_INSTALL_AUTO);
16938    }
16939
16940    /** Called by UserManagerService */
16941    void cleanUpUser(UserManagerService userManager, int userHandle) {
16942        synchronized (mPackages) {
16943            mDirtyUsers.remove(userHandle);
16944            mUserNeedsBadging.delete(userHandle);
16945            mSettings.removeUserLPw(userHandle);
16946            mPendingBroadcasts.remove(userHandle);
16947            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16948        }
16949        synchronized (mInstallLock) {
16950            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16951            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16952                final String volumeUuid = vol.getFsUuid();
16953                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16954                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16955            }
16956            synchronized (mPackages) {
16957                removeUnusedPackagesLILPw(userManager, userHandle);
16958            }
16959        }
16960    }
16961
16962    /**
16963     * We're removing userHandle and would like to remove any downloaded packages
16964     * that are no longer in use by any other user.
16965     * @param userHandle the user being removed
16966     */
16967    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16968        final boolean DEBUG_CLEAN_APKS = false;
16969        int [] users = userManager.getUserIds();
16970        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16971        while (psit.hasNext()) {
16972            PackageSetting ps = psit.next();
16973            if (ps.pkg == null) {
16974                continue;
16975            }
16976            final String packageName = ps.pkg.packageName;
16977            // Skip over if system app
16978            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16979                continue;
16980            }
16981            if (DEBUG_CLEAN_APKS) {
16982                Slog.i(TAG, "Checking package " + packageName);
16983            }
16984            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16985            if (keep) {
16986                if (DEBUG_CLEAN_APKS) {
16987                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16988                }
16989            } else {
16990                for (int i = 0; i < users.length; i++) {
16991                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16992                        keep = true;
16993                        if (DEBUG_CLEAN_APKS) {
16994                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
16995                                    + users[i]);
16996                        }
16997                        break;
16998                    }
16999                }
17000            }
17001            if (!keep) {
17002                if (DEBUG_CLEAN_APKS) {
17003                    Slog.i(TAG, "  Removing package " + packageName);
17004                }
17005                mHandler.post(new Runnable() {
17006                    public void run() {
17007                        deletePackageX(packageName, userHandle, 0);
17008                    } //end run
17009                });
17010            }
17011        }
17012    }
17013
17014    /** Called by UserManagerService */
17015    void createNewUser(int userHandle) {
17016        synchronized (mInstallLock) {
17017            mInstaller.createUserConfig(userHandle);
17018            mSettings.createNewUserLI(this, mInstaller, userHandle);
17019        }
17020        synchronized (mPackages) {
17021            applyFactoryDefaultBrowserLPw(userHandle);
17022            primeDomainVerificationsLPw(userHandle);
17023        }
17024    }
17025
17026    void newUserCreated(final int userHandle) {
17027        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17028        // If permission review for legacy apps is required, we represent
17029        // dagerous permissions for such apps as always granted runtime
17030        // permissions to keep per user flag state whether review is needed.
17031        // Hence, if a new user is added we have to propagate dangerous
17032        // permission grants for these legacy apps.
17033        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17034            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17035                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17036        }
17037    }
17038
17039    @Override
17040    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17041        mContext.enforceCallingOrSelfPermission(
17042                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17043                "Only package verification agents can read the verifier device identity");
17044
17045        synchronized (mPackages) {
17046            return mSettings.getVerifierDeviceIdentityLPw();
17047        }
17048    }
17049
17050    @Override
17051    public void setPermissionEnforced(String permission, boolean enforced) {
17052        // TODO: Now that we no longer change GID for storage, this should to away.
17053        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17054                "setPermissionEnforced");
17055        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17056            synchronized (mPackages) {
17057                if (mSettings.mReadExternalStorageEnforced == null
17058                        || mSettings.mReadExternalStorageEnforced != enforced) {
17059                    mSettings.mReadExternalStorageEnforced = enforced;
17060                    mSettings.writeLPr();
17061                }
17062            }
17063            // kill any non-foreground processes so we restart them and
17064            // grant/revoke the GID.
17065            final IActivityManager am = ActivityManagerNative.getDefault();
17066            if (am != null) {
17067                final long token = Binder.clearCallingIdentity();
17068                try {
17069                    am.killProcessesBelowForeground("setPermissionEnforcement");
17070                } catch (RemoteException e) {
17071                } finally {
17072                    Binder.restoreCallingIdentity(token);
17073                }
17074            }
17075        } else {
17076            throw new IllegalArgumentException("No selective enforcement for " + permission);
17077        }
17078    }
17079
17080    @Override
17081    @Deprecated
17082    public boolean isPermissionEnforced(String permission) {
17083        return true;
17084    }
17085
17086    @Override
17087    public boolean isStorageLow() {
17088        final long token = Binder.clearCallingIdentity();
17089        try {
17090            final DeviceStorageMonitorInternal
17091                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17092            if (dsm != null) {
17093                return dsm.isMemoryLow();
17094            } else {
17095                return false;
17096            }
17097        } finally {
17098            Binder.restoreCallingIdentity(token);
17099        }
17100    }
17101
17102    @Override
17103    public IPackageInstaller getPackageInstaller() {
17104        return mInstallerService;
17105    }
17106
17107    private boolean userNeedsBadging(int userId) {
17108        int index = mUserNeedsBadging.indexOfKey(userId);
17109        if (index < 0) {
17110            final UserInfo userInfo;
17111            final long token = Binder.clearCallingIdentity();
17112            try {
17113                userInfo = sUserManager.getUserInfo(userId);
17114            } finally {
17115                Binder.restoreCallingIdentity(token);
17116            }
17117            final boolean b;
17118            if (userInfo != null && userInfo.isManagedProfile()) {
17119                b = true;
17120            } else {
17121                b = false;
17122            }
17123            mUserNeedsBadging.put(userId, b);
17124            return b;
17125        }
17126        return mUserNeedsBadging.valueAt(index);
17127    }
17128
17129    @Override
17130    public KeySet getKeySetByAlias(String packageName, String alias) {
17131        if (packageName == null || alias == null) {
17132            return null;
17133        }
17134        synchronized(mPackages) {
17135            final PackageParser.Package pkg = mPackages.get(packageName);
17136            if (pkg == null) {
17137                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17138                throw new IllegalArgumentException("Unknown package: " + packageName);
17139            }
17140            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17141            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17142        }
17143    }
17144
17145    @Override
17146    public KeySet getSigningKeySet(String packageName) {
17147        if (packageName == null) {
17148            return null;
17149        }
17150        synchronized(mPackages) {
17151            final PackageParser.Package pkg = mPackages.get(packageName);
17152            if (pkg == null) {
17153                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17154                throw new IllegalArgumentException("Unknown package: " + packageName);
17155            }
17156            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17157                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17158                throw new SecurityException("May not access signing KeySet of other apps.");
17159            }
17160            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17161            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17162        }
17163    }
17164
17165    @Override
17166    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17167        if (packageName == null || ks == null) {
17168            return false;
17169        }
17170        synchronized(mPackages) {
17171            final PackageParser.Package pkg = mPackages.get(packageName);
17172            if (pkg == null) {
17173                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17174                throw new IllegalArgumentException("Unknown package: " + packageName);
17175            }
17176            IBinder ksh = ks.getToken();
17177            if (ksh instanceof KeySetHandle) {
17178                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17179                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17180            }
17181            return false;
17182        }
17183    }
17184
17185    @Override
17186    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17187        if (packageName == null || ks == null) {
17188            return false;
17189        }
17190        synchronized(mPackages) {
17191            final PackageParser.Package pkg = mPackages.get(packageName);
17192            if (pkg == null) {
17193                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17194                throw new IllegalArgumentException("Unknown package: " + packageName);
17195            }
17196            IBinder ksh = ks.getToken();
17197            if (ksh instanceof KeySetHandle) {
17198                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17199                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17200            }
17201            return false;
17202        }
17203    }
17204
17205    private void deletePackageIfUnusedLPr(final String packageName) {
17206        PackageSetting ps = mSettings.mPackages.get(packageName);
17207        if (ps == null) {
17208            return;
17209        }
17210        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17211            // TODO Implement atomic delete if package is unused
17212            // It is currently possible that the package will be deleted even if it is installed
17213            // after this method returns.
17214            mHandler.post(new Runnable() {
17215                public void run() {
17216                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17217                }
17218            });
17219        }
17220    }
17221
17222    /**
17223     * Check and throw if the given before/after packages would be considered a
17224     * downgrade.
17225     */
17226    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17227            throws PackageManagerException {
17228        if (after.versionCode < before.mVersionCode) {
17229            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17230                    "Update version code " + after.versionCode + " is older than current "
17231                    + before.mVersionCode);
17232        } else if (after.versionCode == before.mVersionCode) {
17233            if (after.baseRevisionCode < before.baseRevisionCode) {
17234                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17235                        "Update base revision code " + after.baseRevisionCode
17236                        + " is older than current " + before.baseRevisionCode);
17237            }
17238
17239            if (!ArrayUtils.isEmpty(after.splitNames)) {
17240                for (int i = 0; i < after.splitNames.length; i++) {
17241                    final String splitName = after.splitNames[i];
17242                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17243                    if (j != -1) {
17244                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17245                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17246                                    "Update split " + splitName + " revision code "
17247                                    + after.splitRevisionCodes[i] + " is older than current "
17248                                    + before.splitRevisionCodes[j]);
17249                        }
17250                    }
17251                }
17252            }
17253        }
17254    }
17255
17256    private static class MoveCallbacks extends Handler {
17257        private static final int MSG_CREATED = 1;
17258        private static final int MSG_STATUS_CHANGED = 2;
17259
17260        private final RemoteCallbackList<IPackageMoveObserver>
17261                mCallbacks = new RemoteCallbackList<>();
17262
17263        private final SparseIntArray mLastStatus = new SparseIntArray();
17264
17265        public MoveCallbacks(Looper looper) {
17266            super(looper);
17267        }
17268
17269        public void register(IPackageMoveObserver callback) {
17270            mCallbacks.register(callback);
17271        }
17272
17273        public void unregister(IPackageMoveObserver callback) {
17274            mCallbacks.unregister(callback);
17275        }
17276
17277        @Override
17278        public void handleMessage(Message msg) {
17279            final SomeArgs args = (SomeArgs) msg.obj;
17280            final int n = mCallbacks.beginBroadcast();
17281            for (int i = 0; i < n; i++) {
17282                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17283                try {
17284                    invokeCallback(callback, msg.what, args);
17285                } catch (RemoteException ignored) {
17286                }
17287            }
17288            mCallbacks.finishBroadcast();
17289            args.recycle();
17290        }
17291
17292        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17293                throws RemoteException {
17294            switch (what) {
17295                case MSG_CREATED: {
17296                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17297                    break;
17298                }
17299                case MSG_STATUS_CHANGED: {
17300                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17301                    break;
17302                }
17303            }
17304        }
17305
17306        private void notifyCreated(int moveId, Bundle extras) {
17307            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17308
17309            final SomeArgs args = SomeArgs.obtain();
17310            args.argi1 = moveId;
17311            args.arg2 = extras;
17312            obtainMessage(MSG_CREATED, args).sendToTarget();
17313        }
17314
17315        private void notifyStatusChanged(int moveId, int status) {
17316            notifyStatusChanged(moveId, status, -1);
17317        }
17318
17319        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17320            Slog.v(TAG, "Move " + moveId + " status " + status);
17321
17322            final SomeArgs args = SomeArgs.obtain();
17323            args.argi1 = moveId;
17324            args.argi2 = status;
17325            args.arg3 = estMillis;
17326            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17327
17328            synchronized (mLastStatus) {
17329                mLastStatus.put(moveId, status);
17330            }
17331        }
17332    }
17333
17334    private final static class OnPermissionChangeListeners extends Handler {
17335        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17336
17337        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17338                new RemoteCallbackList<>();
17339
17340        public OnPermissionChangeListeners(Looper looper) {
17341            super(looper);
17342        }
17343
17344        @Override
17345        public void handleMessage(Message msg) {
17346            switch (msg.what) {
17347                case MSG_ON_PERMISSIONS_CHANGED: {
17348                    final int uid = msg.arg1;
17349                    handleOnPermissionsChanged(uid);
17350                } break;
17351            }
17352        }
17353
17354        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17355            mPermissionListeners.register(listener);
17356
17357        }
17358
17359        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17360            mPermissionListeners.unregister(listener);
17361        }
17362
17363        public void onPermissionsChanged(int uid) {
17364            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17365                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17366            }
17367        }
17368
17369        private void handleOnPermissionsChanged(int uid) {
17370            final int count = mPermissionListeners.beginBroadcast();
17371            try {
17372                for (int i = 0; i < count; i++) {
17373                    IOnPermissionsChangeListener callback = mPermissionListeners
17374                            .getBroadcastItem(i);
17375                    try {
17376                        callback.onPermissionsChanged(uid);
17377                    } catch (RemoteException e) {
17378                        Log.e(TAG, "Permission listener is dead", e);
17379                    }
17380                }
17381            } finally {
17382                mPermissionListeners.finishBroadcast();
17383            }
17384        }
17385    }
17386
17387    private class PackageManagerInternalImpl extends PackageManagerInternal {
17388        @Override
17389        public void setLocationPackagesProvider(PackagesProvider provider) {
17390            synchronized (mPackages) {
17391                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17392            }
17393        }
17394
17395        @Override
17396        public void setImePackagesProvider(PackagesProvider provider) {
17397            synchronized (mPackages) {
17398                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17399            }
17400        }
17401
17402        @Override
17403        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17404            synchronized (mPackages) {
17405                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17406            }
17407        }
17408
17409        @Override
17410        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17411            synchronized (mPackages) {
17412                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17413            }
17414        }
17415
17416        @Override
17417        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17418            synchronized (mPackages) {
17419                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17420            }
17421        }
17422
17423        @Override
17424        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17425            synchronized (mPackages) {
17426                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17427            }
17428        }
17429
17430        @Override
17431        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17432            synchronized (mPackages) {
17433                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17434            }
17435        }
17436
17437        @Override
17438        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17439            synchronized (mPackages) {
17440                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17441                        packageName, userId);
17442            }
17443        }
17444
17445        @Override
17446        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17447            synchronized (mPackages) {
17448                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17449                        packageName, userId);
17450            }
17451        }
17452
17453        @Override
17454        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17455            synchronized (mPackages) {
17456                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17457                        packageName, userId);
17458            }
17459        }
17460
17461        @Override
17462        public void setKeepUninstalledPackages(final List<String> packageList) {
17463            Preconditions.checkNotNull(packageList);
17464            List<String> removedFromList = null;
17465            synchronized (mPackages) {
17466                if (mKeepUninstalledPackages != null) {
17467                    final int packagesCount = mKeepUninstalledPackages.size();
17468                    for (int i = 0; i < packagesCount; i++) {
17469                        String oldPackage = mKeepUninstalledPackages.get(i);
17470                        if (packageList != null && packageList.contains(oldPackage)) {
17471                            continue;
17472                        }
17473                        if (removedFromList == null) {
17474                            removedFromList = new ArrayList<>();
17475                        }
17476                        removedFromList.add(oldPackage);
17477                    }
17478                }
17479                mKeepUninstalledPackages = new ArrayList<>(packageList);
17480                if (removedFromList != null) {
17481                    final int removedCount = removedFromList.size();
17482                    for (int i = 0; i < removedCount; i++) {
17483                        deletePackageIfUnusedLPr(removedFromList.get(i));
17484                    }
17485                }
17486            }
17487        }
17488
17489        @Override
17490        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17491            synchronized (mPackages) {
17492                // If we do not support permission review, done.
17493                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17494                    return false;
17495                }
17496
17497                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17498                if (packageSetting == null) {
17499                    return false;
17500                }
17501
17502                // Permission review applies only to apps not supporting the new permission model.
17503                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17504                    return false;
17505                }
17506
17507                // Legacy apps have the permission and get user consent on launch.
17508                PermissionsState permissionsState = packageSetting.getPermissionsState();
17509                return permissionsState.isPermissionReviewRequired(userId);
17510            }
17511        }
17512    }
17513
17514    @Override
17515    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17516        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17517        synchronized (mPackages) {
17518            final long identity = Binder.clearCallingIdentity();
17519            try {
17520                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17521                        packageNames, userId);
17522            } finally {
17523                Binder.restoreCallingIdentity(identity);
17524            }
17525        }
17526    }
17527
17528    private static void enforceSystemOrPhoneCaller(String tag) {
17529        int callingUid = Binder.getCallingUid();
17530        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17531            throw new SecurityException(
17532                    "Cannot call " + tag + " from UID " + callingUid);
17533        }
17534    }
17535}
17536