PackageManagerService.java revision bdbc9692c7cb365d9d3f239baa2377724a6f7bc8
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
63import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
64import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
65import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
66import static android.content.pm.PackageManager.PERMISSION_DENIED;
67import static android.content.pm.PackageManager.PERMISSION_GRANTED;
68import static android.content.pm.PackageParser.isApkFile;
69import static android.os.Process.PACKAGE_INFO_GID;
70import static android.os.Process.SYSTEM_UID;
71import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
72import static android.system.OsConstants.O_CREAT;
73import static android.system.OsConstants.O_RDWR;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
76import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
77import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
78import static com.android.internal.util.ArrayUtils.appendInt;
79import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
80import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
83import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
84import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
88
89import android.Manifest;
90import android.app.ActivityManager;
91import android.app.ActivityManagerNative;
92import android.app.AppGlobals;
93import android.app.IActivityManager;
94import android.app.admin.IDevicePolicyManager;
95import android.app.backup.IBackupManager;
96import android.content.BroadcastReceiver;
97import android.content.ComponentName;
98import android.content.Context;
99import android.content.IIntentReceiver;
100import android.content.Intent;
101import android.content.IntentFilter;
102import android.content.IntentSender;
103import android.content.IntentSender.SendIntentException;
104import android.content.ServiceConnection;
105import android.content.pm.ActivityInfo;
106import android.content.pm.ApplicationInfo;
107import android.content.pm.AppsQueryHelper;
108import android.content.pm.EphemeralResolveInfo;
109import android.content.pm.EphemeralApplicationInfo;
110import android.content.pm.FeatureInfo;
111import android.content.pm.IOnPermissionsChangeListener;
112import android.content.pm.IPackageDataObserver;
113import android.content.pm.IPackageDeleteObserver;
114import android.content.pm.IPackageDeleteObserver2;
115import android.content.pm.IPackageInstallObserver2;
116import android.content.pm.IPackageInstaller;
117import android.content.pm.IPackageManager;
118import android.content.pm.IPackageMoveObserver;
119import android.content.pm.IPackageStatsObserver;
120import android.content.pm.InstrumentationInfo;
121import android.content.pm.IntentFilterVerificationInfo;
122import android.content.pm.KeySet;
123import android.content.pm.ManifestDigest;
124import android.content.pm.PackageCleanItem;
125import android.content.pm.PackageInfo;
126import android.content.pm.PackageInfoLite;
127import android.content.pm.PackageInstaller;
128import android.content.pm.PackageManager;
129import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
130import android.content.pm.PackageManagerInternal;
131import android.content.pm.PackageParser;
132import android.content.pm.PackageParser.ActivityIntentInfo;
133import android.content.pm.PackageParser.PackageLite;
134import android.content.pm.PackageParser.PackageParserException;
135import android.content.pm.PackageStats;
136import android.content.pm.PackageUserState;
137import android.content.pm.ParceledListSlice;
138import android.content.pm.PermissionGroupInfo;
139import android.content.pm.PermissionInfo;
140import android.content.pm.ProviderInfo;
141import android.content.pm.ResolveInfo;
142import android.content.pm.ServiceInfo;
143import android.content.pm.Signature;
144import android.content.pm.UserInfo;
145import android.content.pm.VerificationParams;
146import android.content.pm.VerifierDeviceIdentity;
147import android.content.pm.VerifierInfo;
148import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
149import android.content.res.Resources;
150import android.graphics.Bitmap;
151import android.hardware.display.DisplayManager;
152import android.net.Uri;
153import android.os.Debug;
154import android.os.Binder;
155import android.os.Build;
156import android.os.Bundle;
157import android.os.Environment;
158import android.os.Environment.UserEnvironment;
159import android.os.FileUtils;
160import android.os.Handler;
161import android.os.IBinder;
162import android.os.Looper;
163import android.os.Message;
164import android.os.Parcel;
165import android.os.ParcelFileDescriptor;
166import android.os.Process;
167import android.os.RemoteCallbackList;
168import android.os.RemoteException;
169import android.os.ResultReceiver;
170import android.os.SELinux;
171import android.os.ServiceManager;
172import android.os.SystemClock;
173import android.os.SystemProperties;
174import android.os.Trace;
175import android.os.UserHandle;
176import android.os.UserManager;
177import android.os.storage.IMountService;
178import android.os.storage.MountServiceInternal;
179import android.os.storage.StorageEventListener;
180import android.os.storage.StorageManager;
181import android.os.storage.VolumeInfo;
182import android.os.storage.VolumeRecord;
183import android.security.KeyStore;
184import android.security.SystemKeyStore;
185import android.system.ErrnoException;
186import android.system.Os;
187import android.system.StructStat;
188import android.text.TextUtils;
189import android.text.format.DateUtils;
190import android.util.ArrayMap;
191import android.util.ArraySet;
192import android.util.AtomicFile;
193import android.util.DisplayMetrics;
194import android.util.EventLog;
195import android.util.ExceptionUtils;
196import android.util.Log;
197import android.util.LogPrinter;
198import android.util.MathUtils;
199import android.util.PrintStreamPrinter;
200import android.util.Slog;
201import android.util.SparseArray;
202import android.util.SparseBooleanArray;
203import android.util.SparseIntArray;
204import android.util.Xml;
205import android.view.Display;
206
207import com.android.internal.annotations.GuardedBy;
208import dalvik.system.DexFile;
209import dalvik.system.VMRuntime;
210
211import libcore.io.IoUtils;
212import libcore.util.EmptyArray;
213
214import com.android.internal.R;
215import com.android.internal.annotations.GuardedBy;
216import com.android.internal.app.IMediaContainerService;
217import com.android.internal.app.ResolverActivity;
218import com.android.internal.content.NativeLibraryHelper;
219import com.android.internal.content.PackageHelper;
220import com.android.internal.os.IParcelFileDescriptorFactory;
221import com.android.internal.os.SomeArgs;
222import com.android.internal.os.Zygote;
223import com.android.internal.util.ArrayUtils;
224import com.android.internal.util.FastPrintWriter;
225import com.android.internal.util.FastXmlSerializer;
226import com.android.internal.util.IndentingPrintWriter;
227import com.android.internal.util.Preconditions;
228import com.android.server.EventLogTags;
229import com.android.server.FgThread;
230import com.android.server.IntentResolver;
231import com.android.server.LocalServices;
232import com.android.server.ServiceThread;
233import com.android.server.SystemConfig;
234import com.android.server.Watchdog;
235import com.android.server.pm.PermissionsState.PermissionState;
236import com.android.server.pm.Settings.DatabaseVersion;
237import com.android.server.pm.Settings.VersionInfo;
238import com.android.server.storage.DeviceStorageMonitorInternal;
239
240import org.xmlpull.v1.XmlPullParser;
241import org.xmlpull.v1.XmlPullParserException;
242import org.xmlpull.v1.XmlSerializer;
243
244import java.io.BufferedInputStream;
245import java.io.BufferedOutputStream;
246import java.io.BufferedReader;
247import java.io.ByteArrayInputStream;
248import java.io.ByteArrayOutputStream;
249import java.io.File;
250import java.io.FileDescriptor;
251import java.io.FileNotFoundException;
252import java.io.FileOutputStream;
253import java.io.FileReader;
254import java.io.FilenameFilter;
255import java.io.IOException;
256import java.io.InputStream;
257import java.io.PrintWriter;
258import java.nio.charset.StandardCharsets;
259import java.security.MessageDigest;
260import java.security.NoSuchAlgorithmException;
261import java.security.PublicKey;
262import java.security.cert.CertificateEncodingException;
263import java.security.cert.CertificateException;
264import java.text.SimpleDateFormat;
265import java.util.ArrayList;
266import java.util.Arrays;
267import java.util.Collection;
268import java.util.Collections;
269import java.util.Comparator;
270import java.util.Date;
271import java.util.Iterator;
272import java.util.List;
273import java.util.Map;
274import java.util.Objects;
275import java.util.Set;
276import java.util.concurrent.CountDownLatch;
277import java.util.concurrent.TimeUnit;
278import java.util.concurrent.atomic.AtomicBoolean;
279import java.util.concurrent.atomic.AtomicInteger;
280import java.util.concurrent.atomic.AtomicLong;
281
282/**
283 * Keep track of all those .apks everywhere.
284 *
285 * This is very central to the platform's security; please run the unit
286 * tests whenever making modifications here:
287 *
288runtest -c android.content.pm.PackageManagerTests frameworks-core
289 *
290 * {@hide}
291 */
292public class PackageManagerService extends IPackageManager.Stub {
293    static final String TAG = "PackageManager";
294    static final boolean DEBUG_SETTINGS = false;
295    static final boolean DEBUG_PREFERRED = false;
296    static final boolean DEBUG_UPGRADE = false;
297    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
298    private static final boolean DEBUG_BACKUP = false;
299    private static final boolean DEBUG_INSTALL = false;
300    private static final boolean DEBUG_REMOVE = false;
301    private static final boolean DEBUG_BROADCASTS = false;
302    private static final boolean DEBUG_SHOW_INFO = false;
303    private static final boolean DEBUG_PACKAGE_INFO = false;
304    private static final boolean DEBUG_INTENT_MATCHING = false;
305    private static final boolean DEBUG_PACKAGE_SCANNING = false;
306    private static final boolean DEBUG_VERIFY = false;
307    private static final boolean DEBUG_DEXOPT = false;
308    private static final boolean DEBUG_ABI_SELECTION = false;
309    private static final boolean DEBUG_EPHEMERAL = false;
310
311    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
312
313    private static final int RADIO_UID = Process.PHONE_UID;
314    private static final int LOG_UID = Process.LOG_UID;
315    private static final int NFC_UID = Process.NFC_UID;
316    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
317    private static final int SHELL_UID = Process.SHELL_UID;
318
319    // Cap the size of permission trees that 3rd party apps can define
320    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
321
322    // Suffix used during package installation when copying/moving
323    // package apks to install directory.
324    private static final String INSTALL_PACKAGE_SUFFIX = "-";
325
326    static final int SCAN_NO_DEX = 1<<1;
327    static final int SCAN_FORCE_DEX = 1<<2;
328    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
329    static final int SCAN_NEW_INSTALL = 1<<4;
330    static final int SCAN_NO_PATHS = 1<<5;
331    static final int SCAN_UPDATE_TIME = 1<<6;
332    static final int SCAN_DEFER_DEX = 1<<7;
333    static final int SCAN_BOOTING = 1<<8;
334    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
335    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
336    static final int SCAN_REPLACING = 1<<11;
337    static final int SCAN_REQUIRE_KNOWN = 1<<12;
338    static final int SCAN_MOVE = 1<<13;
339    static final int SCAN_INITIAL = 1<<14;
340
341    static final int REMOVE_CHATTY = 1<<16;
342
343    private static final int[] EMPTY_INT_ARRAY = new int[0];
344
345    /**
346     * Timeout (in milliseconds) after which the watchdog should declare that
347     * our handler thread is wedged.  The usual default for such things is one
348     * minute but we sometimes do very lengthy I/O operations on this thread,
349     * such as installing multi-gigabyte applications, so ours needs to be longer.
350     */
351    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
352
353    /**
354     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
355     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
356     * settings entry if available, otherwise we use the hardcoded default.  If it's been
357     * more than this long since the last fstrim, we force one during the boot sequence.
358     *
359     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
360     * one gets run at the next available charging+idle time.  This final mandatory
361     * no-fstrim check kicks in only of the other scheduling criteria is never met.
362     */
363    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
364
365    /**
366     * Whether verification is enabled by default.
367     */
368    private static final boolean DEFAULT_VERIFY_ENABLE = true;
369
370    /**
371     * The default maximum time to wait for the verification agent to return in
372     * milliseconds.
373     */
374    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
375
376    /**
377     * The default response for package verification timeout.
378     *
379     * This can be either PackageManager.VERIFICATION_ALLOW or
380     * PackageManager.VERIFICATION_REJECT.
381     */
382    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
383
384    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
385
386    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
387            DEFAULT_CONTAINER_PACKAGE,
388            "com.android.defcontainer.DefaultContainerService");
389
390    private static final String KILL_APP_REASON_GIDS_CHANGED =
391            "permission grant or revoke changed gids";
392
393    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
394            "permissions revoked";
395
396    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
397
398    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
399
400    /** Permission grant: not grant the permission. */
401    private static final int GRANT_DENIED = 1;
402
403    /** Permission grant: grant the permission as an install permission. */
404    private static final int GRANT_INSTALL = 2;
405
406    /** Permission grant: grant the permission as a runtime one. */
407    private static final int GRANT_RUNTIME = 3;
408
409    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
410    private static final int GRANT_UPGRADE = 4;
411
412    /** Canonical intent used to identify what counts as a "web browser" app */
413    private static final Intent sBrowserIntent;
414    static {
415        sBrowserIntent = new Intent();
416        sBrowserIntent.setAction(Intent.ACTION_VIEW);
417        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
418        sBrowserIntent.setData(Uri.parse("http:"));
419    }
420
421    final ServiceThread mHandlerThread;
422
423    final PackageHandler mHandler;
424
425    /**
426     * Messages for {@link #mHandler} that need to wait for system ready before
427     * being dispatched.
428     */
429    private ArrayList<Message> mPostSystemReadyMessages;
430
431    final int mSdkVersion = Build.VERSION.SDK_INT;
432
433    final Context mContext;
434    final boolean mFactoryTest;
435    final boolean mOnlyCore;
436    final DisplayMetrics mMetrics;
437    final int mDefParseFlags;
438    final String[] mSeparateProcesses;
439    final boolean mIsUpgrade;
440
441    /** The location for ASEC container files on internal storage. */
442    final String mAsecInternalPath;
443
444    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
445    // LOCK HELD.  Can be called with mInstallLock held.
446    @GuardedBy("mInstallLock")
447    final Installer mInstaller;
448
449    /** Directory where installed third-party apps stored */
450    final File mAppInstallDir;
451    final File mEphemeralInstallDir;
452
453    /**
454     * Directory to which applications installed internally have their
455     * 32 bit native libraries copied.
456     */
457    private File mAppLib32InstallDir;
458
459    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
460    // apps.
461    final File mDrmAppPrivateInstallDir;
462
463    // ----------------------------------------------------------------
464
465    // Lock for state used when installing and doing other long running
466    // operations.  Methods that must be called with this lock held have
467    // the suffix "LI".
468    final Object mInstallLock = new Object();
469
470    // ----------------------------------------------------------------
471
472    // Keys are String (package name), values are Package.  This also serves
473    // as the lock for the global state.  Methods that must be called with
474    // this lock held have the prefix "LP".
475    @GuardedBy("mPackages")
476    final ArrayMap<String, PackageParser.Package> mPackages =
477            new ArrayMap<String, PackageParser.Package>();
478
479    // Tracks available target package names -> overlay package paths.
480    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
481        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
482
483    /**
484     * Tracks new system packages [received in an OTA] that we expect to
485     * find updated user-installed versions. Keys are package name, values
486     * are package location.
487     */
488    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
489
490    /**
491     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
492     */
493    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
494    /**
495     * Whether or not system app permissions should be promoted from install to runtime.
496     */
497    boolean mPromoteSystemApps;
498
499    final Settings mSettings;
500    boolean mRestoredSettings;
501
502    // System configuration read by SystemConfig.
503    final int[] mGlobalGids;
504    final SparseArray<ArraySet<String>> mSystemPermissions;
505    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
506
507    // If mac_permissions.xml was found for seinfo labeling.
508    boolean mFoundPolicyFile;
509
510    // If a recursive restorecon of /data/data/<pkg> is needed.
511    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
512
513    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
514
515    public static final class SharedLibraryEntry {
516        public final String path;
517        public final String apk;
518
519        SharedLibraryEntry(String _path, String _apk) {
520            path = _path;
521            apk = _apk;
522        }
523    }
524
525    // Currently known shared libraries.
526    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
527            new ArrayMap<String, SharedLibraryEntry>();
528
529    // All available activities, for your resolving pleasure.
530    final ActivityIntentResolver mActivities =
531            new ActivityIntentResolver();
532
533    // All available receivers, for your resolving pleasure.
534    final ActivityIntentResolver mReceivers =
535            new ActivityIntentResolver();
536
537    // All available services, for your resolving pleasure.
538    final ServiceIntentResolver mServices = new ServiceIntentResolver();
539
540    // All available providers, for your resolving pleasure.
541    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
542
543    // Mapping from provider base names (first directory in content URI codePath)
544    // to the provider information.
545    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
546            new ArrayMap<String, PackageParser.Provider>();
547
548    // Mapping from instrumentation class names to info about them.
549    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
550            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
551
552    // Mapping from permission names to info about them.
553    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
554            new ArrayMap<String, PackageParser.PermissionGroup>();
555
556    // Packages whose data we have transfered into another package, thus
557    // should no longer exist.
558    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
559
560    // Broadcast actions that are only available to the system.
561    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
562
563    /** List of packages waiting for verification. */
564    final SparseArray<PackageVerificationState> mPendingVerification
565            = new SparseArray<PackageVerificationState>();
566
567    /** Set of packages associated with each app op permission. */
568    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
569
570    final PackageInstallerService mInstallerService;
571
572    private final PackageDexOptimizer mPackageDexOptimizer;
573
574    private AtomicInteger mNextMoveId = new AtomicInteger();
575    private final MoveCallbacks mMoveCallbacks;
576
577    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
578
579    // Cache of users who need badging.
580    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
581
582    /** Token for keys in mPendingVerification. */
583    private int mPendingVerificationToken = 0;
584
585    volatile boolean mSystemReady;
586    volatile boolean mSafeMode;
587    volatile boolean mHasSystemUidErrors;
588
589    ApplicationInfo mAndroidApplication;
590    final ActivityInfo mResolveActivity = new ActivityInfo();
591    final ResolveInfo mResolveInfo = new ResolveInfo();
592    ComponentName mResolveComponentName;
593    PackageParser.Package mPlatformPackage;
594    ComponentName mCustomResolverComponentName;
595
596    boolean mResolverReplaced = false;
597
598    private final ComponentName mIntentFilterVerifierComponent;
599    private int mIntentFilterVerificationToken = 0;
600
601    /** Component that knows whether or not an ephemeral application exists */
602    final ComponentName mEphemeralResolverComponent;
603    /** The service connection to the ephemeral resolver */
604    final EphemeralResolverConnection mEphemeralResolverConnection;
605
606    /** Component used to install ephemeral applications */
607    final ComponentName mEphemeralInstallerComponent;
608    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
609    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
610
611    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
612            = new SparseArray<IntentFilterVerificationState>();
613
614    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
615            new DefaultPermissionGrantPolicy(this);
616
617    // List of packages names to keep cached, even if they are uninstalled for all users
618    private List<String> mKeepUninstalledPackages;
619
620    private static class IFVerificationParams {
621        PackageParser.Package pkg;
622        boolean replacing;
623        int userId;
624        int verifierUid;
625
626        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
627                int _userId, int _verifierUid) {
628            pkg = _pkg;
629            replacing = _replacing;
630            userId = _userId;
631            replacing = _replacing;
632            verifierUid = _verifierUid;
633        }
634    }
635
636    private interface IntentFilterVerifier<T extends IntentFilter> {
637        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
638                                               T filter, String packageName);
639        void startVerifications(int userId);
640        void receiveVerificationResponse(int verificationId);
641    }
642
643    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
644        private Context mContext;
645        private ComponentName mIntentFilterVerifierComponent;
646        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
647
648        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
649            mContext = context;
650            mIntentFilterVerifierComponent = verifierComponent;
651        }
652
653        private String getDefaultScheme() {
654            return IntentFilter.SCHEME_HTTPS;
655        }
656
657        @Override
658        public void startVerifications(int userId) {
659            // Launch verifications requests
660            int count = mCurrentIntentFilterVerifications.size();
661            for (int n=0; n<count; n++) {
662                int verificationId = mCurrentIntentFilterVerifications.get(n);
663                final IntentFilterVerificationState ivs =
664                        mIntentFilterVerificationStates.get(verificationId);
665
666                String packageName = ivs.getPackageName();
667
668                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
669                final int filterCount = filters.size();
670                ArraySet<String> domainsSet = new ArraySet<>();
671                for (int m=0; m<filterCount; m++) {
672                    PackageParser.ActivityIntentInfo filter = filters.get(m);
673                    domainsSet.addAll(filter.getHostsList());
674                }
675                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
676                synchronized (mPackages) {
677                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
678                            packageName, domainsList) != null) {
679                        scheduleWriteSettingsLocked();
680                    }
681                }
682                sendVerificationRequest(userId, verificationId, ivs);
683            }
684            mCurrentIntentFilterVerifications.clear();
685        }
686
687        private void sendVerificationRequest(int userId, int verificationId,
688                IntentFilterVerificationState ivs) {
689
690            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
691            verificationIntent.putExtra(
692                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
693                    verificationId);
694            verificationIntent.putExtra(
695                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
696                    getDefaultScheme());
697            verificationIntent.putExtra(
698                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
699                    ivs.getHostsString());
700            verificationIntent.putExtra(
701                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
702                    ivs.getPackageName());
703            verificationIntent.setComponent(mIntentFilterVerifierComponent);
704            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
705
706            UserHandle user = new UserHandle(userId);
707            mContext.sendBroadcastAsUser(verificationIntent, user);
708            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
709                    "Sending IntentFilter verification broadcast");
710        }
711
712        public void receiveVerificationResponse(int verificationId) {
713            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
714
715            final boolean verified = ivs.isVerified();
716
717            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
718            final int count = filters.size();
719            if (DEBUG_DOMAIN_VERIFICATION) {
720                Slog.i(TAG, "Received verification response " + verificationId
721                        + " for " + count + " filters, verified=" + verified);
722            }
723            for (int n=0; n<count; n++) {
724                PackageParser.ActivityIntentInfo filter = filters.get(n);
725                filter.setVerified(verified);
726
727                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
728                        + " verified with result:" + verified + " and hosts:"
729                        + ivs.getHostsString());
730            }
731
732            mIntentFilterVerificationStates.remove(verificationId);
733
734            final String packageName = ivs.getPackageName();
735            IntentFilterVerificationInfo ivi = null;
736
737            synchronized (mPackages) {
738                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
739            }
740            if (ivi == null) {
741                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
742                        + verificationId + " packageName:" + packageName);
743                return;
744            }
745            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
746                    "Updating IntentFilterVerificationInfo for package " + packageName
747                            +" verificationId:" + verificationId);
748
749            synchronized (mPackages) {
750                if (verified) {
751                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
752                } else {
753                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
754                }
755                scheduleWriteSettingsLocked();
756
757                final int userId = ivs.getUserId();
758                if (userId != UserHandle.USER_ALL) {
759                    final int userStatus =
760                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
761
762                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
763                    boolean needUpdate = false;
764
765                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
766                    // already been set by the User thru the Disambiguation dialog
767                    switch (userStatus) {
768                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
769                            if (verified) {
770                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
771                            } else {
772                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
773                            }
774                            needUpdate = true;
775                            break;
776
777                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
778                            if (verified) {
779                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
780                                needUpdate = true;
781                            }
782                            break;
783
784                        default:
785                            // Nothing to do
786                    }
787
788                    if (needUpdate) {
789                        mSettings.updateIntentFilterVerificationStatusLPw(
790                                packageName, updatedStatus, userId);
791                        scheduleWritePackageRestrictionsLocked(userId);
792                    }
793                }
794            }
795        }
796
797        @Override
798        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
799                    ActivityIntentInfo filter, String packageName) {
800            if (!hasValidDomains(filter)) {
801                return false;
802            }
803            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
804            if (ivs == null) {
805                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
806                        packageName);
807            }
808            if (DEBUG_DOMAIN_VERIFICATION) {
809                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
810            }
811            ivs.addFilter(filter);
812            return true;
813        }
814
815        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
816                int userId, int verificationId, String packageName) {
817            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
818                    verifierUid, userId, packageName);
819            ivs.setPendingState();
820            synchronized (mPackages) {
821                mIntentFilterVerificationStates.append(verificationId, ivs);
822                mCurrentIntentFilterVerifications.add(verificationId);
823            }
824            return ivs;
825        }
826    }
827
828    private static boolean hasValidDomains(ActivityIntentInfo filter) {
829        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
830                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
831                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
832    }
833
834    private IntentFilterVerifier mIntentFilterVerifier;
835
836    // Set of pending broadcasts for aggregating enable/disable of components.
837    static class PendingPackageBroadcasts {
838        // for each user id, a map of <package name -> components within that package>
839        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
840
841        public PendingPackageBroadcasts() {
842            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
843        }
844
845        public ArrayList<String> get(int userId, String packageName) {
846            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
847            return packages.get(packageName);
848        }
849
850        public void put(int userId, String packageName, ArrayList<String> components) {
851            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
852            packages.put(packageName, components);
853        }
854
855        public void remove(int userId, String packageName) {
856            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
857            if (packages != null) {
858                packages.remove(packageName);
859            }
860        }
861
862        public void remove(int userId) {
863            mUidMap.remove(userId);
864        }
865
866        public int userIdCount() {
867            return mUidMap.size();
868        }
869
870        public int userIdAt(int n) {
871            return mUidMap.keyAt(n);
872        }
873
874        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
875            return mUidMap.get(userId);
876        }
877
878        public int size() {
879            // total number of pending broadcast entries across all userIds
880            int num = 0;
881            for (int i = 0; i< mUidMap.size(); i++) {
882                num += mUidMap.valueAt(i).size();
883            }
884            return num;
885        }
886
887        public void clear() {
888            mUidMap.clear();
889        }
890
891        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
892            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
893            if (map == null) {
894                map = new ArrayMap<String, ArrayList<String>>();
895                mUidMap.put(userId, map);
896            }
897            return map;
898        }
899    }
900    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
901
902    // Service Connection to remote media container service to copy
903    // package uri's from external media onto secure containers
904    // or internal storage.
905    private IMediaContainerService mContainerService = null;
906
907    static final int SEND_PENDING_BROADCAST = 1;
908    static final int MCS_BOUND = 3;
909    static final int END_COPY = 4;
910    static final int INIT_COPY = 5;
911    static final int MCS_UNBIND = 6;
912    static final int START_CLEANING_PACKAGE = 7;
913    static final int FIND_INSTALL_LOC = 8;
914    static final int POST_INSTALL = 9;
915    static final int MCS_RECONNECT = 10;
916    static final int MCS_GIVE_UP = 11;
917    static final int UPDATED_MEDIA_STATUS = 12;
918    static final int WRITE_SETTINGS = 13;
919    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
920    static final int PACKAGE_VERIFIED = 15;
921    static final int CHECK_PENDING_VERIFICATION = 16;
922    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
923    static final int INTENT_FILTER_VERIFIED = 18;
924
925    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
926
927    // Delay time in millisecs
928    static final int BROADCAST_DELAY = 10 * 1000;
929
930    static UserManagerService sUserManager;
931
932    // Stores a list of users whose package restrictions file needs to be updated
933    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
934
935    final private DefaultContainerConnection mDefContainerConn =
936            new DefaultContainerConnection();
937    class DefaultContainerConnection implements ServiceConnection {
938        public void onServiceConnected(ComponentName name, IBinder service) {
939            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
940            IMediaContainerService imcs =
941                IMediaContainerService.Stub.asInterface(service);
942            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
943        }
944
945        public void onServiceDisconnected(ComponentName name) {
946            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
947        }
948    }
949
950    // Recordkeeping of restore-after-install operations that are currently in flight
951    // between the Package Manager and the Backup Manager
952    static class PostInstallData {
953        public InstallArgs args;
954        public PackageInstalledInfo res;
955
956        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
957            args = _a;
958            res = _r;
959        }
960    }
961
962    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
963    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
964
965    // XML tags for backup/restore of various bits of state
966    private static final String TAG_PREFERRED_BACKUP = "pa";
967    private static final String TAG_DEFAULT_APPS = "da";
968    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
969
970    final String mRequiredVerifierPackage;
971    final String mRequiredInstallerPackage;
972
973    private final PackageUsage mPackageUsage = new PackageUsage();
974
975    private class PackageUsage {
976        private static final int WRITE_INTERVAL
977            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
978
979        private final Object mFileLock = new Object();
980        private final AtomicLong mLastWritten = new AtomicLong(0);
981        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
982
983        private boolean mIsHistoricalPackageUsageAvailable = true;
984
985        boolean isHistoricalPackageUsageAvailable() {
986            return mIsHistoricalPackageUsageAvailable;
987        }
988
989        void write(boolean force) {
990            if (force) {
991                writeInternal();
992                return;
993            }
994            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
995                && !DEBUG_DEXOPT) {
996                return;
997            }
998            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
999                new Thread("PackageUsage_DiskWriter") {
1000                    @Override
1001                    public void run() {
1002                        try {
1003                            writeInternal();
1004                        } finally {
1005                            mBackgroundWriteRunning.set(false);
1006                        }
1007                    }
1008                }.start();
1009            }
1010        }
1011
1012        private void writeInternal() {
1013            synchronized (mPackages) {
1014                synchronized (mFileLock) {
1015                    AtomicFile file = getFile();
1016                    FileOutputStream f = null;
1017                    try {
1018                        f = file.startWrite();
1019                        BufferedOutputStream out = new BufferedOutputStream(f);
1020                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1021                        StringBuilder sb = new StringBuilder();
1022                        for (PackageParser.Package pkg : mPackages.values()) {
1023                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1024                                continue;
1025                            }
1026                            sb.setLength(0);
1027                            sb.append(pkg.packageName);
1028                            sb.append(' ');
1029                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1030                            sb.append('\n');
1031                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1032                        }
1033                        out.flush();
1034                        file.finishWrite(f);
1035                    } catch (IOException e) {
1036                        if (f != null) {
1037                            file.failWrite(f);
1038                        }
1039                        Log.e(TAG, "Failed to write package usage times", e);
1040                    }
1041                }
1042            }
1043            mLastWritten.set(SystemClock.elapsedRealtime());
1044        }
1045
1046        void readLP() {
1047            synchronized (mFileLock) {
1048                AtomicFile file = getFile();
1049                BufferedInputStream in = null;
1050                try {
1051                    in = new BufferedInputStream(file.openRead());
1052                    StringBuffer sb = new StringBuffer();
1053                    while (true) {
1054                        String packageName = readToken(in, sb, ' ');
1055                        if (packageName == null) {
1056                            break;
1057                        }
1058                        String timeInMillisString = readToken(in, sb, '\n');
1059                        if (timeInMillisString == null) {
1060                            throw new IOException("Failed to find last usage time for package "
1061                                                  + packageName);
1062                        }
1063                        PackageParser.Package pkg = mPackages.get(packageName);
1064                        if (pkg == null) {
1065                            continue;
1066                        }
1067                        long timeInMillis;
1068                        try {
1069                            timeInMillis = Long.parseLong(timeInMillisString);
1070                        } catch (NumberFormatException e) {
1071                            throw new IOException("Failed to parse " + timeInMillisString
1072                                                  + " as a long.", e);
1073                        }
1074                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1075                    }
1076                } catch (FileNotFoundException expected) {
1077                    mIsHistoricalPackageUsageAvailable = false;
1078                } catch (IOException e) {
1079                    Log.w(TAG, "Failed to read package usage times", e);
1080                } finally {
1081                    IoUtils.closeQuietly(in);
1082                }
1083            }
1084            mLastWritten.set(SystemClock.elapsedRealtime());
1085        }
1086
1087        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1088                throws IOException {
1089            sb.setLength(0);
1090            while (true) {
1091                int ch = in.read();
1092                if (ch == -1) {
1093                    if (sb.length() == 0) {
1094                        return null;
1095                    }
1096                    throw new IOException("Unexpected EOF");
1097                }
1098                if (ch == endOfToken) {
1099                    return sb.toString();
1100                }
1101                sb.append((char)ch);
1102            }
1103        }
1104
1105        private AtomicFile getFile() {
1106            File dataDir = Environment.getDataDirectory();
1107            File systemDir = new File(dataDir, "system");
1108            File fname = new File(systemDir, "package-usage.list");
1109            return new AtomicFile(fname);
1110        }
1111    }
1112
1113    class PackageHandler extends Handler {
1114        private boolean mBound = false;
1115        final ArrayList<HandlerParams> mPendingInstalls =
1116            new ArrayList<HandlerParams>();
1117
1118        private boolean connectToService() {
1119            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1120                    " DefaultContainerService");
1121            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1122            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1123            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1124                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1125                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126                mBound = true;
1127                return true;
1128            }
1129            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1130            return false;
1131        }
1132
1133        private void disconnectService() {
1134            mContainerService = null;
1135            mBound = false;
1136            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1137            mContext.unbindService(mDefContainerConn);
1138            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1139        }
1140
1141        PackageHandler(Looper looper) {
1142            super(looper);
1143        }
1144
1145        public void handleMessage(Message msg) {
1146            try {
1147                doHandleMessage(msg);
1148            } finally {
1149                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1150            }
1151        }
1152
1153        void doHandleMessage(Message msg) {
1154            switch (msg.what) {
1155                case INIT_COPY: {
1156                    HandlerParams params = (HandlerParams) msg.obj;
1157                    int idx = mPendingInstalls.size();
1158                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1159                    // If a bind was already initiated we dont really
1160                    // need to do anything. The pending install
1161                    // will be processed later on.
1162                    if (!mBound) {
1163                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1164                                System.identityHashCode(mHandler));
1165                        // If this is the only one pending we might
1166                        // have to bind to the service again.
1167                        if (!connectToService()) {
1168                            Slog.e(TAG, "Failed to bind to media container service");
1169                            params.serviceError();
1170                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1171                                    System.identityHashCode(mHandler));
1172                            if (params.traceMethod != null) {
1173                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1174                                        params.traceCookie);
1175                            }
1176                            return;
1177                        } else {
1178                            // Once we bind to the service, the first
1179                            // pending request will be processed.
1180                            mPendingInstalls.add(idx, params);
1181                        }
1182                    } else {
1183                        mPendingInstalls.add(idx, params);
1184                        // Already bound to the service. Just make
1185                        // sure we trigger off processing the first request.
1186                        if (idx == 0) {
1187                            mHandler.sendEmptyMessage(MCS_BOUND);
1188                        }
1189                    }
1190                    break;
1191                }
1192                case MCS_BOUND: {
1193                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1194                    if (msg.obj != null) {
1195                        mContainerService = (IMediaContainerService) msg.obj;
1196                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1197                                System.identityHashCode(mHandler));
1198                    }
1199                    if (mContainerService == null) {
1200                        if (!mBound) {
1201                            // Something seriously wrong since we are not bound and we are not
1202                            // waiting for connection. Bail out.
1203                            Slog.e(TAG, "Cannot bind to media container service");
1204                            for (HandlerParams params : mPendingInstalls) {
1205                                // Indicate service bind error
1206                                params.serviceError();
1207                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1208                                        System.identityHashCode(params));
1209                                if (params.traceMethod != null) {
1210                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1211                                            params.traceMethod, params.traceCookie);
1212                                }
1213                                return;
1214                            }
1215                            mPendingInstalls.clear();
1216                        } else {
1217                            Slog.w(TAG, "Waiting to connect to media container service");
1218                        }
1219                    } else if (mPendingInstalls.size() > 0) {
1220                        HandlerParams params = mPendingInstalls.get(0);
1221                        if (params != null) {
1222                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1223                                    System.identityHashCode(params));
1224                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1225                            if (params.startCopy()) {
1226                                // We are done...  look for more work or to
1227                                // go idle.
1228                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1229                                        "Checking for more work or unbind...");
1230                                // Delete pending install
1231                                if (mPendingInstalls.size() > 0) {
1232                                    mPendingInstalls.remove(0);
1233                                }
1234                                if (mPendingInstalls.size() == 0) {
1235                                    if (mBound) {
1236                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1237                                                "Posting delayed MCS_UNBIND");
1238                                        removeMessages(MCS_UNBIND);
1239                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1240                                        // Unbind after a little delay, to avoid
1241                                        // continual thrashing.
1242                                        sendMessageDelayed(ubmsg, 10000);
1243                                    }
1244                                } else {
1245                                    // There are more pending requests in queue.
1246                                    // Just post MCS_BOUND message to trigger processing
1247                                    // of next pending install.
1248                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1249                                            "Posting MCS_BOUND for next work");
1250                                    mHandler.sendEmptyMessage(MCS_BOUND);
1251                                }
1252                            }
1253                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1254                        }
1255                    } else {
1256                        // Should never happen ideally.
1257                        Slog.w(TAG, "Empty queue");
1258                    }
1259                    break;
1260                }
1261                case MCS_RECONNECT: {
1262                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1263                    if (mPendingInstalls.size() > 0) {
1264                        if (mBound) {
1265                            disconnectService();
1266                        }
1267                        if (!connectToService()) {
1268                            Slog.e(TAG, "Failed to bind to media container service");
1269                            for (HandlerParams params : mPendingInstalls) {
1270                                // Indicate service bind error
1271                                params.serviceError();
1272                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1273                                        System.identityHashCode(params));
1274                            }
1275                            mPendingInstalls.clear();
1276                        }
1277                    }
1278                    break;
1279                }
1280                case MCS_UNBIND: {
1281                    // If there is no actual work left, then time to unbind.
1282                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1283
1284                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1285                        if (mBound) {
1286                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1287
1288                            disconnectService();
1289                        }
1290                    } else if (mPendingInstalls.size() > 0) {
1291                        // There are more pending requests in queue.
1292                        // Just post MCS_BOUND message to trigger processing
1293                        // of next pending install.
1294                        mHandler.sendEmptyMessage(MCS_BOUND);
1295                    }
1296
1297                    break;
1298                }
1299                case MCS_GIVE_UP: {
1300                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1301                    HandlerParams params = mPendingInstalls.remove(0);
1302                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1303                            System.identityHashCode(params));
1304                    break;
1305                }
1306                case SEND_PENDING_BROADCAST: {
1307                    String packages[];
1308                    ArrayList<String> components[];
1309                    int size = 0;
1310                    int uids[];
1311                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1312                    synchronized (mPackages) {
1313                        if (mPendingBroadcasts == null) {
1314                            return;
1315                        }
1316                        size = mPendingBroadcasts.size();
1317                        if (size <= 0) {
1318                            // Nothing to be done. Just return
1319                            return;
1320                        }
1321                        packages = new String[size];
1322                        components = new ArrayList[size];
1323                        uids = new int[size];
1324                        int i = 0;  // filling out the above arrays
1325
1326                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1327                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1328                            Iterator<Map.Entry<String, ArrayList<String>>> it
1329                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1330                                            .entrySet().iterator();
1331                            while (it.hasNext() && i < size) {
1332                                Map.Entry<String, ArrayList<String>> ent = it.next();
1333                                packages[i] = ent.getKey();
1334                                components[i] = ent.getValue();
1335                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1336                                uids[i] = (ps != null)
1337                                        ? UserHandle.getUid(packageUserId, ps.appId)
1338                                        : -1;
1339                                i++;
1340                            }
1341                        }
1342                        size = i;
1343                        mPendingBroadcasts.clear();
1344                    }
1345                    // Send broadcasts
1346                    for (int i = 0; i < size; i++) {
1347                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1348                    }
1349                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1350                    break;
1351                }
1352                case START_CLEANING_PACKAGE: {
1353                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1354                    final String packageName = (String)msg.obj;
1355                    final int userId = msg.arg1;
1356                    final boolean andCode = msg.arg2 != 0;
1357                    synchronized (mPackages) {
1358                        if (userId == UserHandle.USER_ALL) {
1359                            int[] users = sUserManager.getUserIds();
1360                            for (int user : users) {
1361                                mSettings.addPackageToCleanLPw(
1362                                        new PackageCleanItem(user, packageName, andCode));
1363                            }
1364                        } else {
1365                            mSettings.addPackageToCleanLPw(
1366                                    new PackageCleanItem(userId, packageName, andCode));
1367                        }
1368                    }
1369                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1370                    startCleaningPackages();
1371                } break;
1372                case POST_INSTALL: {
1373                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1374
1375                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1376                    mRunningInstalls.delete(msg.arg1);
1377                    boolean deleteOld = false;
1378
1379                    if (data != null) {
1380                        InstallArgs args = data.args;
1381                        PackageInstalledInfo res = data.res;
1382
1383                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1384                            final String packageName = res.pkg.applicationInfo.packageName;
1385                            res.removedInfo.sendBroadcast(false, true, false);
1386                            Bundle extras = new Bundle(1);
1387                            extras.putInt(Intent.EXTRA_UID, res.uid);
1388
1389                            // Now that we successfully installed the package, grant runtime
1390                            // permissions if requested before broadcasting the install.
1391                            if ((args.installFlags
1392                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1393                                    && res.pkg.applicationInfo.targetSdkVersion
1394                                            >= Build.VERSION_CODES.M) {
1395                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1396                                        args.installGrantPermissions);
1397                            }
1398
1399                            synchronized (mPackages) {
1400                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1401                            }
1402
1403                            // Determine the set of users who are adding this
1404                            // package for the first time vs. those who are seeing
1405                            // an update.
1406                            int[] firstUsers;
1407                            int[] updateUsers = new int[0];
1408                            if (res.origUsers == null || res.origUsers.length == 0) {
1409                                firstUsers = res.newUsers;
1410                            } else {
1411                                firstUsers = new int[0];
1412                                for (int i=0; i<res.newUsers.length; i++) {
1413                                    int user = res.newUsers[i];
1414                                    boolean isNew = true;
1415                                    for (int j=0; j<res.origUsers.length; j++) {
1416                                        if (res.origUsers[j] == user) {
1417                                            isNew = false;
1418                                            break;
1419                                        }
1420                                    }
1421                                    if (isNew) {
1422                                        int[] newFirst = new int[firstUsers.length+1];
1423                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1424                                                firstUsers.length);
1425                                        newFirst[firstUsers.length] = user;
1426                                        firstUsers = newFirst;
1427                                    } else {
1428                                        int[] newUpdate = new int[updateUsers.length+1];
1429                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1430                                                updateUsers.length);
1431                                        newUpdate[updateUsers.length] = user;
1432                                        updateUsers = newUpdate;
1433                                    }
1434                                }
1435                            }
1436                            // don't broadcast for ephemeral installs/updates
1437                            final boolean isEphemeral = isEphemeral(res.pkg);
1438                            if (!isEphemeral) {
1439                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1440                                        extras, 0 /*flags*/, null /*targetPackage*/,
1441                                        null /*finishedReceiver*/, firstUsers);
1442                            }
1443                            final boolean update = res.removedInfo.removedPackage != null;
1444                            if (update) {
1445                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1446                            }
1447                            if (!isEphemeral) {
1448                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1449                                        extras, 0 /*flags*/, null /*targetPackage*/,
1450                                        null /*finishedReceiver*/, updateUsers);
1451                            }
1452                            if (update) {
1453                                if (!isEphemeral) {
1454                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1455                                            packageName, extras, 0 /*flags*/,
1456                                            null /*targetPackage*/, null /*finishedReceiver*/,
1457                                            updateUsers);
1458                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1459                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1460                                            packageName /*targetPackage*/,
1461                                            null /*finishedReceiver*/, updateUsers);
1462                                }
1463
1464                                // treat asec-hosted packages like removable media on upgrade
1465                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1466                                    if (DEBUG_INSTALL) {
1467                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1468                                                + " is ASEC-hosted -> AVAILABLE");
1469                                    }
1470                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1471                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1472                                    pkgList.add(packageName);
1473                                    sendResourcesChangedBroadcast(true, true,
1474                                            pkgList,uidArray, null);
1475                                }
1476                            }
1477                            if (res.removedInfo.args != null) {
1478                                // Remove the replaced package's older resources safely now
1479                                deleteOld = true;
1480                            }
1481
1482                            // If this app is a browser and it's newly-installed for some
1483                            // users, clear any default-browser state in those users
1484                            if (firstUsers.length > 0) {
1485                                // the app's nature doesn't depend on the user, so we can just
1486                                // check its browser nature in any user and generalize.
1487                                if (packageIsBrowser(packageName, firstUsers[0])) {
1488                                    synchronized (mPackages) {
1489                                        for (int userId : firstUsers) {
1490                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1491                                        }
1492                                    }
1493                                }
1494                            }
1495                            // Log current value of "unknown sources" setting
1496                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1497                                getUnknownSourcesSettings());
1498                        }
1499                        // Force a gc to clear up things
1500                        Runtime.getRuntime().gc();
1501                        // We delete after a gc for applications  on sdcard.
1502                        if (deleteOld) {
1503                            synchronized (mInstallLock) {
1504                                res.removedInfo.args.doPostDeleteLI(true);
1505                            }
1506                        }
1507                        if (args.observer != null) {
1508                            try {
1509                                Bundle extras = extrasForInstallResult(res);
1510                                args.observer.onPackageInstalled(res.name, res.returnCode,
1511                                        res.returnMsg, extras);
1512                            } catch (RemoteException e) {
1513                                Slog.i(TAG, "Observer no longer exists.");
1514                            }
1515                        }
1516                        if (args.traceMethod != null) {
1517                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1518                                    args.traceCookie);
1519                        }
1520                        return;
1521                    } else {
1522                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1523                    }
1524
1525                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1526                } break;
1527                case UPDATED_MEDIA_STATUS: {
1528                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1529                    boolean reportStatus = msg.arg1 == 1;
1530                    boolean doGc = msg.arg2 == 1;
1531                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1532                    if (doGc) {
1533                        // Force a gc to clear up stale containers.
1534                        Runtime.getRuntime().gc();
1535                    }
1536                    if (msg.obj != null) {
1537                        @SuppressWarnings("unchecked")
1538                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1539                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1540                        // Unload containers
1541                        unloadAllContainers(args);
1542                    }
1543                    if (reportStatus) {
1544                        try {
1545                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1546                            PackageHelper.getMountService().finishMediaUpdate();
1547                        } catch (RemoteException e) {
1548                            Log.e(TAG, "MountService not running?");
1549                        }
1550                    }
1551                } break;
1552                case WRITE_SETTINGS: {
1553                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1554                    synchronized (mPackages) {
1555                        removeMessages(WRITE_SETTINGS);
1556                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1557                        mSettings.writeLPr();
1558                        mDirtyUsers.clear();
1559                    }
1560                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1561                } break;
1562                case WRITE_PACKAGE_RESTRICTIONS: {
1563                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1564                    synchronized (mPackages) {
1565                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1566                        for (int userId : mDirtyUsers) {
1567                            mSettings.writePackageRestrictionsLPr(userId);
1568                        }
1569                        mDirtyUsers.clear();
1570                    }
1571                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1572                } break;
1573                case CHECK_PENDING_VERIFICATION: {
1574                    final int verificationId = msg.arg1;
1575                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1576
1577                    if ((state != null) && !state.timeoutExtended()) {
1578                        final InstallArgs args = state.getInstallArgs();
1579                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1580
1581                        Slog.i(TAG, "Verification timed out for " + originUri);
1582                        mPendingVerification.remove(verificationId);
1583
1584                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1585
1586                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1587                            Slog.i(TAG, "Continuing with installation of " + originUri);
1588                            state.setVerifierResponse(Binder.getCallingUid(),
1589                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1590                            broadcastPackageVerified(verificationId, originUri,
1591                                    PackageManager.VERIFICATION_ALLOW,
1592                                    state.getInstallArgs().getUser());
1593                            try {
1594                                ret = args.copyApk(mContainerService, true);
1595                            } catch (RemoteException e) {
1596                                Slog.e(TAG, "Could not contact the ContainerService");
1597                            }
1598                        } else {
1599                            broadcastPackageVerified(verificationId, originUri,
1600                                    PackageManager.VERIFICATION_REJECT,
1601                                    state.getInstallArgs().getUser());
1602                        }
1603
1604                        Trace.asyncTraceEnd(
1605                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1606
1607                        processPendingInstall(args, ret);
1608                        mHandler.sendEmptyMessage(MCS_UNBIND);
1609                    }
1610                    break;
1611                }
1612                case PACKAGE_VERIFIED: {
1613                    final int verificationId = msg.arg1;
1614
1615                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1616                    if (state == null) {
1617                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1618                        break;
1619                    }
1620
1621                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1622
1623                    state.setVerifierResponse(response.callerUid, response.code);
1624
1625                    if (state.isVerificationComplete()) {
1626                        mPendingVerification.remove(verificationId);
1627
1628                        final InstallArgs args = state.getInstallArgs();
1629                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1630
1631                        int ret;
1632                        if (state.isInstallAllowed()) {
1633                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1634                            broadcastPackageVerified(verificationId, originUri,
1635                                    response.code, state.getInstallArgs().getUser());
1636                            try {
1637                                ret = args.copyApk(mContainerService, true);
1638                            } catch (RemoteException e) {
1639                                Slog.e(TAG, "Could not contact the ContainerService");
1640                            }
1641                        } else {
1642                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1643                        }
1644
1645                        Trace.asyncTraceEnd(
1646                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1647
1648                        processPendingInstall(args, ret);
1649                        mHandler.sendEmptyMessage(MCS_UNBIND);
1650                    }
1651
1652                    break;
1653                }
1654                case START_INTENT_FILTER_VERIFICATIONS: {
1655                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1656                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1657                            params.replacing, params.pkg);
1658                    break;
1659                }
1660                case INTENT_FILTER_VERIFIED: {
1661                    final int verificationId = msg.arg1;
1662
1663                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1664                            verificationId);
1665                    if (state == null) {
1666                        Slog.w(TAG, "Invalid IntentFilter verification token "
1667                                + verificationId + " received");
1668                        break;
1669                    }
1670
1671                    final int userId = state.getUserId();
1672
1673                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1674                            "Processing IntentFilter verification with token:"
1675                            + verificationId + " and userId:" + userId);
1676
1677                    final IntentFilterVerificationResponse response =
1678                            (IntentFilterVerificationResponse) msg.obj;
1679
1680                    state.setVerifierResponse(response.callerUid, response.code);
1681
1682                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1683                            "IntentFilter verification with token:" + verificationId
1684                            + " and userId:" + userId
1685                            + " is settings verifier response with response code:"
1686                            + response.code);
1687
1688                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1689                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1690                                + response.getFailedDomainsString());
1691                    }
1692
1693                    if (state.isVerificationComplete()) {
1694                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1695                    } else {
1696                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1697                                "IntentFilter verification with token:" + verificationId
1698                                + " was not said to be complete");
1699                    }
1700
1701                    break;
1702                }
1703            }
1704        }
1705    }
1706
1707    private StorageEventListener mStorageListener = new StorageEventListener() {
1708        @Override
1709        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1710            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1711                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1712                    final String volumeUuid = vol.getFsUuid();
1713
1714                    // Clean up any users or apps that were removed or recreated
1715                    // while this volume was missing
1716                    reconcileUsers(volumeUuid);
1717                    reconcileApps(volumeUuid);
1718
1719                    // Clean up any install sessions that expired or were
1720                    // cancelled while this volume was missing
1721                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1722
1723                    loadPrivatePackages(vol);
1724
1725                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1726                    unloadPrivatePackages(vol);
1727                }
1728            }
1729
1730            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1731                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1732                    updateExternalMediaStatus(true, false);
1733                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1734                    updateExternalMediaStatus(false, false);
1735                }
1736            }
1737        }
1738
1739        @Override
1740        public void onVolumeForgotten(String fsUuid) {
1741            if (TextUtils.isEmpty(fsUuid)) {
1742                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1743                return;
1744            }
1745
1746            // Remove any apps installed on the forgotten volume
1747            synchronized (mPackages) {
1748                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1749                for (PackageSetting ps : packages) {
1750                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1751                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1752                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1753                }
1754
1755                mSettings.onVolumeForgotten(fsUuid);
1756                mSettings.writeLPr();
1757            }
1758        }
1759    };
1760
1761    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1762            String[] grantedPermissions) {
1763        if (userId >= UserHandle.USER_SYSTEM) {
1764            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1765        } else if (userId == UserHandle.USER_ALL) {
1766            final int[] userIds;
1767            synchronized (mPackages) {
1768                userIds = UserManagerService.getInstance().getUserIds();
1769            }
1770            for (int someUserId : userIds) {
1771                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1772            }
1773        }
1774
1775        // We could have touched GID membership, so flush out packages.list
1776        synchronized (mPackages) {
1777            mSettings.writePackageListLPr();
1778        }
1779    }
1780
1781    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1782            String[] grantedPermissions) {
1783        SettingBase sb = (SettingBase) pkg.mExtras;
1784        if (sb == null) {
1785            return;
1786        }
1787
1788        PermissionsState permissionsState = sb.getPermissionsState();
1789
1790        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1791                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1792
1793        synchronized (mPackages) {
1794            for (String permission : pkg.requestedPermissions) {
1795                BasePermission bp = mSettings.mPermissions.get(permission);
1796                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1797                        && (grantedPermissions == null
1798                               || ArrayUtils.contains(grantedPermissions, permission))) {
1799                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1800                    // Installer cannot change immutable permissions.
1801                    if ((flags & immutableFlags) == 0) {
1802                        grantRuntimePermission(pkg.packageName, permission, userId);
1803                    }
1804                }
1805            }
1806        }
1807    }
1808
1809    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1810        Bundle extras = null;
1811        switch (res.returnCode) {
1812            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1813                extras = new Bundle();
1814                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1815                        res.origPermission);
1816                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1817                        res.origPackage);
1818                break;
1819            }
1820            case PackageManager.INSTALL_SUCCEEDED: {
1821                extras = new Bundle();
1822                extras.putBoolean(Intent.EXTRA_REPLACING,
1823                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1824                break;
1825            }
1826        }
1827        return extras;
1828    }
1829
1830    void scheduleWriteSettingsLocked() {
1831        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1832            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1833        }
1834    }
1835
1836    void scheduleWritePackageRestrictionsLocked(int userId) {
1837        if (!sUserManager.exists(userId)) return;
1838        mDirtyUsers.add(userId);
1839        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1840            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1841        }
1842    }
1843
1844    public static PackageManagerService main(Context context, Installer installer,
1845            boolean factoryTest, boolean onlyCore) {
1846        PackageManagerService m = new PackageManagerService(context, installer,
1847                factoryTest, onlyCore);
1848        m.enableSystemUserPackages();
1849        ServiceManager.addService("package", m);
1850        return m;
1851    }
1852
1853    private void enableSystemUserPackages() {
1854        if (!UserManager.isSplitSystemUser()) {
1855            return;
1856        }
1857        // For system user, enable apps based on the following conditions:
1858        // - app is whitelisted or belong to one of these groups:
1859        //   -- system app which has no launcher icons
1860        //   -- system app which has INTERACT_ACROSS_USERS permission
1861        //   -- system IME app
1862        // - app is not in the blacklist
1863        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1864        Set<String> enableApps = new ArraySet<>();
1865        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1866                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1867                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1868        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1869        enableApps.addAll(wlApps);
1870        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1871                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1872        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1873        enableApps.removeAll(blApps);
1874        Log.i(TAG, "Applications installed for system user: " + enableApps);
1875        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1876                UserHandle.SYSTEM);
1877        final int allAppsSize = allAps.size();
1878        synchronized (mPackages) {
1879            for (int i = 0; i < allAppsSize; i++) {
1880                String pName = allAps.get(i);
1881                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1882                // Should not happen, but we shouldn't be failing if it does
1883                if (pkgSetting == null) {
1884                    continue;
1885                }
1886                boolean install = enableApps.contains(pName);
1887                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1888                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1889                            + " for system user");
1890                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1891                }
1892            }
1893        }
1894    }
1895
1896    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1897        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1898                Context.DISPLAY_SERVICE);
1899        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1900    }
1901
1902    public PackageManagerService(Context context, Installer installer,
1903            boolean factoryTest, boolean onlyCore) {
1904        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1905                SystemClock.uptimeMillis());
1906
1907        if (mSdkVersion <= 0) {
1908            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1909        }
1910
1911        mContext = context;
1912        mFactoryTest = factoryTest;
1913        mOnlyCore = onlyCore;
1914        mMetrics = new DisplayMetrics();
1915        mSettings = new Settings(mPackages);
1916        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1917                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1918        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1919                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1920        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1921                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1922        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1923                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1924        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1925                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1926        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1927                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1928
1929        String separateProcesses = SystemProperties.get("debug.separate_processes");
1930        if (separateProcesses != null && separateProcesses.length() > 0) {
1931            if ("*".equals(separateProcesses)) {
1932                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1933                mSeparateProcesses = null;
1934                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1935            } else {
1936                mDefParseFlags = 0;
1937                mSeparateProcesses = separateProcesses.split(",");
1938                Slog.w(TAG, "Running with debug.separate_processes: "
1939                        + separateProcesses);
1940            }
1941        } else {
1942            mDefParseFlags = 0;
1943            mSeparateProcesses = null;
1944        }
1945
1946        mInstaller = installer;
1947        mPackageDexOptimizer = new PackageDexOptimizer(this);
1948        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1949
1950        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1951                FgThread.get().getLooper());
1952
1953        getDefaultDisplayMetrics(context, mMetrics);
1954
1955        SystemConfig systemConfig = SystemConfig.getInstance();
1956        mGlobalGids = systemConfig.getGlobalGids();
1957        mSystemPermissions = systemConfig.getSystemPermissions();
1958        mAvailableFeatures = systemConfig.getAvailableFeatures();
1959
1960        synchronized (mInstallLock) {
1961        // writer
1962        synchronized (mPackages) {
1963            mHandlerThread = new ServiceThread(TAG,
1964                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1965            mHandlerThread.start();
1966            mHandler = new PackageHandler(mHandlerThread.getLooper());
1967            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1968
1969            File dataDir = Environment.getDataDirectory();
1970            mAppInstallDir = new File(dataDir, "app");
1971            mAppLib32InstallDir = new File(dataDir, "app-lib");
1972            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1973            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1974            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1975
1976            sUserManager = new UserManagerService(context, this, mPackages);
1977
1978            // Propagate permission configuration in to package manager.
1979            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1980                    = systemConfig.getPermissions();
1981            for (int i=0; i<permConfig.size(); i++) {
1982                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1983                BasePermission bp = mSettings.mPermissions.get(perm.name);
1984                if (bp == null) {
1985                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1986                    mSettings.mPermissions.put(perm.name, bp);
1987                }
1988                if (perm.gids != null) {
1989                    bp.setGids(perm.gids, perm.perUser);
1990                }
1991            }
1992
1993            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1994            for (int i=0; i<libConfig.size(); i++) {
1995                mSharedLibraries.put(libConfig.keyAt(i),
1996                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1997            }
1998
1999            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2000
2001            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2002
2003            String customResolverActivity = Resources.getSystem().getString(
2004                    R.string.config_customResolverActivity);
2005            if (TextUtils.isEmpty(customResolverActivity)) {
2006                customResolverActivity = null;
2007            } else {
2008                mCustomResolverComponentName = ComponentName.unflattenFromString(
2009                        customResolverActivity);
2010            }
2011
2012            long startTime = SystemClock.uptimeMillis();
2013
2014            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2015                    startTime);
2016
2017            // Set flag to monitor and not change apk file paths when
2018            // scanning install directories.
2019            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2020
2021            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2022            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2023
2024            if (bootClassPath == null) {
2025                Slog.w(TAG, "No BOOTCLASSPATH found!");
2026            }
2027
2028            if (systemServerClassPath == null) {
2029                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2030            }
2031
2032            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2033            final String[] dexCodeInstructionSets =
2034                    getDexCodeInstructionSets(
2035                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2036
2037            /**
2038             * Ensure all external libraries have had dexopt run on them.
2039             */
2040            if (mSharedLibraries.size() > 0) {
2041                // NOTE: For now, we're compiling these system "shared libraries"
2042                // (and framework jars) into all available architectures. It's possible
2043                // to compile them only when we come across an app that uses them (there's
2044                // already logic for that in scanPackageLI) but that adds some complexity.
2045                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2046                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2047                        final String lib = libEntry.path;
2048                        if (lib == null) {
2049                            continue;
2050                        }
2051
2052                        try {
2053                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2054                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2055                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2056                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2057                            }
2058                        } catch (FileNotFoundException e) {
2059                            Slog.w(TAG, "Library not found: " + lib);
2060                        } catch (IOException e) {
2061                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2062                                    + e.getMessage());
2063                        }
2064                    }
2065                }
2066            }
2067
2068            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2069
2070            final VersionInfo ver = mSettings.getInternalVersion();
2071            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2072            // when upgrading from pre-M, promote system app permissions from install to runtime
2073            mPromoteSystemApps =
2074                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2075
2076            // save off the names of pre-existing system packages prior to scanning; we don't
2077            // want to automatically grant runtime permissions for new system apps
2078            if (mPromoteSystemApps) {
2079                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2080                while (pkgSettingIter.hasNext()) {
2081                    PackageSetting ps = pkgSettingIter.next();
2082                    if (isSystemApp(ps)) {
2083                        mExistingSystemPackages.add(ps.name);
2084                    }
2085                }
2086            }
2087
2088            // Collect vendor overlay packages.
2089            // (Do this before scanning any apps.)
2090            // For security and version matching reason, only consider
2091            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2092            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2093            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2094                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2095
2096            // Find base frameworks (resource packages without code).
2097            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2098                    | PackageParser.PARSE_IS_SYSTEM_DIR
2099                    | PackageParser.PARSE_IS_PRIVILEGED,
2100                    scanFlags | SCAN_NO_DEX, 0);
2101
2102            // Collected privileged system packages.
2103            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2104            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2105                    | PackageParser.PARSE_IS_SYSTEM_DIR
2106                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2107
2108            // Collect ordinary system packages.
2109            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2110            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2111                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2112
2113            // Collect all vendor packages.
2114            File vendorAppDir = new File("/vendor/app");
2115            try {
2116                vendorAppDir = vendorAppDir.getCanonicalFile();
2117            } catch (IOException e) {
2118                // failed to look up canonical path, continue with original one
2119            }
2120            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2121                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2122
2123            // Collect all OEM packages.
2124            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2125            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2126                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2127
2128            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2129            mInstaller.moveFiles();
2130
2131            // Prune any system packages that no longer exist.
2132            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2133            if (!mOnlyCore) {
2134                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2135                while (psit.hasNext()) {
2136                    PackageSetting ps = psit.next();
2137
2138                    /*
2139                     * If this is not a system app, it can't be a
2140                     * disable system app.
2141                     */
2142                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2143                        continue;
2144                    }
2145
2146                    /*
2147                     * If the package is scanned, it's not erased.
2148                     */
2149                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2150                    if (scannedPkg != null) {
2151                        /*
2152                         * If the system app is both scanned and in the
2153                         * disabled packages list, then it must have been
2154                         * added via OTA. Remove it from the currently
2155                         * scanned package so the previously user-installed
2156                         * application can be scanned.
2157                         */
2158                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2159                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2160                                    + ps.name + "; removing system app.  Last known codePath="
2161                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2162                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2163                                    + scannedPkg.mVersionCode);
2164                            removePackageLI(ps, true);
2165                            mExpectingBetter.put(ps.name, ps.codePath);
2166                        }
2167
2168                        continue;
2169                    }
2170
2171                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2172                        psit.remove();
2173                        logCriticalInfo(Log.WARN, "System package " + ps.name
2174                                + " no longer exists; wiping its data");
2175                        removeDataDirsLI(null, ps.name);
2176                    } else {
2177                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2178                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2179                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2180                        }
2181                    }
2182                }
2183            }
2184
2185            //look for any incomplete package installations
2186            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2187            //clean up list
2188            for(int i = 0; i < deletePkgsList.size(); i++) {
2189                //clean up here
2190                cleanupInstallFailedPackage(deletePkgsList.get(i));
2191            }
2192            //delete tmp files
2193            deleteTempPackageFiles();
2194
2195            // Remove any shared userIDs that have no associated packages
2196            mSettings.pruneSharedUsersLPw();
2197
2198            if (!mOnlyCore) {
2199                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2200                        SystemClock.uptimeMillis());
2201                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2202
2203                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2204                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2205
2206                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2207                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2208
2209                /**
2210                 * Remove disable package settings for any updated system
2211                 * apps that were removed via an OTA. If they're not a
2212                 * previously-updated app, remove them completely.
2213                 * Otherwise, just revoke their system-level permissions.
2214                 */
2215                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2216                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2217                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2218
2219                    String msg;
2220                    if (deletedPkg == null) {
2221                        msg = "Updated system package " + deletedAppName
2222                                + " no longer exists; wiping its data";
2223                        removeDataDirsLI(null, deletedAppName);
2224                    } else {
2225                        msg = "Updated system app + " + deletedAppName
2226                                + " no longer present; removing system privileges for "
2227                                + deletedAppName;
2228
2229                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2230
2231                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2232                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2233                    }
2234                    logCriticalInfo(Log.WARN, msg);
2235                }
2236
2237                /**
2238                 * Make sure all system apps that we expected to appear on
2239                 * the userdata partition actually showed up. If they never
2240                 * appeared, crawl back and revive the system version.
2241                 */
2242                for (int i = 0; i < mExpectingBetter.size(); i++) {
2243                    final String packageName = mExpectingBetter.keyAt(i);
2244                    if (!mPackages.containsKey(packageName)) {
2245                        final File scanFile = mExpectingBetter.valueAt(i);
2246
2247                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2248                                + " but never showed up; reverting to system");
2249
2250                        final int reparseFlags;
2251                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2252                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2253                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2254                                    | PackageParser.PARSE_IS_PRIVILEGED;
2255                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2256                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2257                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2258                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2259                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2260                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2261                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2262                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2263                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2264                        } else {
2265                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2266                            continue;
2267                        }
2268
2269                        mSettings.enableSystemPackageLPw(packageName);
2270
2271                        try {
2272                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2273                        } catch (PackageManagerException e) {
2274                            Slog.e(TAG, "Failed to parse original system package: "
2275                                    + e.getMessage());
2276                        }
2277                    }
2278                }
2279            }
2280            mExpectingBetter.clear();
2281
2282            // Now that we know all of the shared libraries, update all clients to have
2283            // the correct library paths.
2284            updateAllSharedLibrariesLPw();
2285
2286            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2287                // NOTE: We ignore potential failures here during a system scan (like
2288                // the rest of the commands above) because there's precious little we
2289                // can do about it. A settings error is reported, though.
2290                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2291                        false /* boot complete */);
2292            }
2293
2294            // Now that we know all the packages we are keeping,
2295            // read and update their last usage times.
2296            mPackageUsage.readLP();
2297
2298            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2299                    SystemClock.uptimeMillis());
2300            Slog.i(TAG, "Time to scan packages: "
2301                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2302                    + " seconds");
2303
2304            // If the platform SDK has changed since the last time we booted,
2305            // we need to re-grant app permission to catch any new ones that
2306            // appear.  This is really a hack, and means that apps can in some
2307            // cases get permissions that the user didn't initially explicitly
2308            // allow...  it would be nice to have some better way to handle
2309            // this situation.
2310            int updateFlags = UPDATE_PERMISSIONS_ALL;
2311            if (ver.sdkVersion != mSdkVersion) {
2312                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2313                        + mSdkVersion + "; regranting permissions for internal storage");
2314                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2315            }
2316            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2317            ver.sdkVersion = mSdkVersion;
2318
2319            // If this is the first boot or an update from pre-M, and it is a normal
2320            // boot, then we need to initialize the default preferred apps across
2321            // all defined users.
2322            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2323                for (UserInfo user : sUserManager.getUsers(true)) {
2324                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2325                    applyFactoryDefaultBrowserLPw(user.id);
2326                    primeDomainVerificationsLPw(user.id);
2327                }
2328            }
2329
2330            // If this is first boot after an OTA, and a normal boot, then
2331            // we need to clear code cache directories.
2332            if (mIsUpgrade && !onlyCore) {
2333                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2334                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2335                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2336                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2337                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2338                    }
2339                }
2340                ver.fingerprint = Build.FINGERPRINT;
2341            }
2342
2343            checkDefaultBrowser();
2344
2345            // clear only after permissions and other defaults have been updated
2346            mExistingSystemPackages.clear();
2347            mPromoteSystemApps = false;
2348
2349            // All the changes are done during package scanning.
2350            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2351
2352            // can downgrade to reader
2353            mSettings.writeLPr();
2354
2355            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2356                    SystemClock.uptimeMillis());
2357
2358            mRequiredVerifierPackage = getRequiredVerifierLPr();
2359            mRequiredInstallerPackage = getRequiredInstallerLPr();
2360
2361            mInstallerService = new PackageInstallerService(context, this);
2362
2363            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2364            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2365                    mIntentFilterVerifierComponent);
2366
2367            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2368            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2369            // both the installer and resolver must be present to enable ephemeral
2370            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2371                if (DEBUG_EPHEMERAL) {
2372                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2373                            + " installer:" + ephemeralInstallerComponent);
2374                }
2375                mEphemeralResolverComponent = ephemeralResolverComponent;
2376                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2377                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2378                mEphemeralResolverConnection =
2379                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2380            } else {
2381                if (DEBUG_EPHEMERAL) {
2382                    final String missingComponent =
2383                            (ephemeralResolverComponent == null)
2384                            ? (ephemeralInstallerComponent == null)
2385                                    ? "resolver and installer"
2386                                    : "resolver"
2387                            : "installer";
2388                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2389                }
2390                mEphemeralResolverComponent = null;
2391                mEphemeralInstallerComponent = null;
2392                mEphemeralResolverConnection = null;
2393            }
2394
2395            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2396        } // synchronized (mPackages)
2397        } // synchronized (mInstallLock)
2398
2399        // Now after opening every single application zip, make sure they
2400        // are all flushed.  Not really needed, but keeps things nice and
2401        // tidy.
2402        Runtime.getRuntime().gc();
2403
2404        // The initial scanning above does many calls into installd while
2405        // holding the mPackages lock, but we're mostly interested in yelling
2406        // once we have a booted system.
2407        mInstaller.setWarnIfHeld(mPackages);
2408
2409        // Expose private service for system components to use.
2410        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2411    }
2412
2413    @Override
2414    public boolean isFirstBoot() {
2415        return !mRestoredSettings;
2416    }
2417
2418    @Override
2419    public boolean isOnlyCoreApps() {
2420        return mOnlyCore;
2421    }
2422
2423    @Override
2424    public boolean isUpgrade() {
2425        return mIsUpgrade;
2426    }
2427
2428    private String getRequiredVerifierLPr() {
2429        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2430        // We only care about verifier that's installed under system user.
2431        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2432                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2433
2434        String requiredVerifier = null;
2435
2436        final int N = receivers.size();
2437        for (int i = 0; i < N; i++) {
2438            final ResolveInfo info = receivers.get(i);
2439
2440            if (info.activityInfo == null) {
2441                continue;
2442            }
2443
2444            final String packageName = info.activityInfo.packageName;
2445
2446            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2447                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2448                continue;
2449            }
2450
2451            if (requiredVerifier != null) {
2452                throw new RuntimeException("There can be only one required verifier");
2453            }
2454
2455            requiredVerifier = packageName;
2456        }
2457
2458        return requiredVerifier;
2459    }
2460
2461    private String getRequiredInstallerLPr() {
2462        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2463        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2464        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2465
2466        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2467                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2468
2469        String requiredInstaller = null;
2470
2471        final int N = installers.size();
2472        for (int i = 0; i < N; i++) {
2473            final ResolveInfo info = installers.get(i);
2474            final String packageName = info.activityInfo.packageName;
2475
2476            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2477                continue;
2478            }
2479
2480            if (requiredInstaller != null) {
2481                throw new RuntimeException("There must be one required installer");
2482            }
2483
2484            requiredInstaller = packageName;
2485        }
2486
2487        if (requiredInstaller == null) {
2488            throw new RuntimeException("There must be one required installer");
2489        }
2490
2491        return requiredInstaller;
2492    }
2493
2494    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2495        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2496        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2497                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2498
2499        ComponentName verifierComponentName = null;
2500
2501        int priority = -1000;
2502        final int N = receivers.size();
2503        for (int i = 0; i < N; i++) {
2504            final ResolveInfo info = receivers.get(i);
2505
2506            if (info.activityInfo == null) {
2507                continue;
2508            }
2509
2510            final String packageName = info.activityInfo.packageName;
2511
2512            final PackageSetting ps = mSettings.mPackages.get(packageName);
2513            if (ps == null) {
2514                continue;
2515            }
2516
2517            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2518                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2519                continue;
2520            }
2521
2522            // Select the IntentFilterVerifier with the highest priority
2523            if (priority < info.priority) {
2524                priority = info.priority;
2525                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2526                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2527                        + verifierComponentName + " with priority: " + info.priority);
2528            }
2529        }
2530
2531        return verifierComponentName;
2532    }
2533
2534    private ComponentName getEphemeralResolverLPr() {
2535        final String[] packageArray =
2536                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2537        if (packageArray.length == 0) {
2538            if (DEBUG_EPHEMERAL) {
2539                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2540            }
2541            return null;
2542        }
2543
2544        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2545        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2546                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2547
2548        final int N = resolvers.size();
2549        if (N == 0) {
2550            if (DEBUG_EPHEMERAL) {
2551                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2552            }
2553            return null;
2554        }
2555
2556        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2557        for (int i = 0; i < N; i++) {
2558            final ResolveInfo info = resolvers.get(i);
2559
2560            if (info.serviceInfo == null) {
2561                continue;
2562            }
2563
2564            final String packageName = info.serviceInfo.packageName;
2565            if (!possiblePackages.contains(packageName)) {
2566                if (DEBUG_EPHEMERAL) {
2567                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2568                            + " pkg: " + packageName + ", info:" + info);
2569                }
2570                continue;
2571            }
2572
2573            if (DEBUG_EPHEMERAL) {
2574                Slog.v(TAG, "Ephemeral resolver found;"
2575                        + " pkg: " + packageName + ", info:" + info);
2576            }
2577            return new ComponentName(packageName, info.serviceInfo.name);
2578        }
2579        if (DEBUG_EPHEMERAL) {
2580            Slog.v(TAG, "Ephemeral resolver NOT found");
2581        }
2582        return null;
2583    }
2584
2585    private ComponentName getEphemeralInstallerLPr() {
2586        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2587        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2588        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2589        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2590                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2591
2592        ComponentName ephemeralInstaller = null;
2593
2594        final int N = installers.size();
2595        for (int i = 0; i < N; i++) {
2596            final ResolveInfo info = installers.get(i);
2597            final String packageName = info.activityInfo.packageName;
2598
2599            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2600                if (DEBUG_EPHEMERAL) {
2601                    Slog.d(TAG, "Ephemeral installer is not system app;"
2602                            + " pkg: " + packageName + ", info:" + info);
2603                }
2604                continue;
2605            }
2606
2607            if (ephemeralInstaller != null) {
2608                throw new RuntimeException("There must only be one ephemeral installer");
2609            }
2610
2611            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2612        }
2613
2614        return ephemeralInstaller;
2615    }
2616
2617    private void primeDomainVerificationsLPw(int userId) {
2618        if (DEBUG_DOMAIN_VERIFICATION) {
2619            Slog.d(TAG, "Priming domain verifications in user " + userId);
2620        }
2621
2622        SystemConfig systemConfig = SystemConfig.getInstance();
2623        ArraySet<String> packages = systemConfig.getLinkedApps();
2624        ArraySet<String> domains = new ArraySet<String>();
2625
2626        for (String packageName : packages) {
2627            PackageParser.Package pkg = mPackages.get(packageName);
2628            if (pkg != null) {
2629                if (!pkg.isSystemApp()) {
2630                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2631                    continue;
2632                }
2633
2634                domains.clear();
2635                for (PackageParser.Activity a : pkg.activities) {
2636                    for (ActivityIntentInfo filter : a.intents) {
2637                        if (hasValidDomains(filter)) {
2638                            domains.addAll(filter.getHostsList());
2639                        }
2640                    }
2641                }
2642
2643                if (domains.size() > 0) {
2644                    if (DEBUG_DOMAIN_VERIFICATION) {
2645                        Slog.v(TAG, "      + " + packageName);
2646                    }
2647                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2648                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2649                    // and then 'always' in the per-user state actually used for intent resolution.
2650                    final IntentFilterVerificationInfo ivi;
2651                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2652                            new ArrayList<String>(domains));
2653                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2654                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2655                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2656                } else {
2657                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2658                            + "' does not handle web links");
2659                }
2660            } else {
2661                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2662            }
2663        }
2664
2665        scheduleWritePackageRestrictionsLocked(userId);
2666        scheduleWriteSettingsLocked();
2667    }
2668
2669    private void applyFactoryDefaultBrowserLPw(int userId) {
2670        // The default browser app's package name is stored in a string resource,
2671        // with a product-specific overlay used for vendor customization.
2672        String browserPkg = mContext.getResources().getString(
2673                com.android.internal.R.string.default_browser);
2674        if (!TextUtils.isEmpty(browserPkg)) {
2675            // non-empty string => required to be a known package
2676            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2677            if (ps == null) {
2678                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2679                browserPkg = null;
2680            } else {
2681                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2682            }
2683        }
2684
2685        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2686        // default.  If there's more than one, just leave everything alone.
2687        if (browserPkg == null) {
2688            calculateDefaultBrowserLPw(userId);
2689        }
2690    }
2691
2692    private void calculateDefaultBrowserLPw(int userId) {
2693        List<String> allBrowsers = resolveAllBrowserApps(userId);
2694        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2695        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2696    }
2697
2698    private List<String> resolveAllBrowserApps(int userId) {
2699        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2700        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2701                PackageManager.MATCH_ALL, userId);
2702
2703        final int count = list.size();
2704        List<String> result = new ArrayList<String>(count);
2705        for (int i=0; i<count; i++) {
2706            ResolveInfo info = list.get(i);
2707            if (info.activityInfo == null
2708                    || !info.handleAllWebDataURI
2709                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2710                    || result.contains(info.activityInfo.packageName)) {
2711                continue;
2712            }
2713            result.add(info.activityInfo.packageName);
2714        }
2715
2716        return result;
2717    }
2718
2719    private boolean packageIsBrowser(String packageName, int userId) {
2720        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2721                PackageManager.MATCH_ALL, userId);
2722        final int N = list.size();
2723        for (int i = 0; i < N; i++) {
2724            ResolveInfo info = list.get(i);
2725            if (packageName.equals(info.activityInfo.packageName)) {
2726                return true;
2727            }
2728        }
2729        return false;
2730    }
2731
2732    private void checkDefaultBrowser() {
2733        final int myUserId = UserHandle.myUserId();
2734        final String packageName = getDefaultBrowserPackageName(myUserId);
2735        if (packageName != null) {
2736            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2737            if (info == null) {
2738                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2739                synchronized (mPackages) {
2740                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2741                }
2742            }
2743        }
2744    }
2745
2746    @Override
2747    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2748            throws RemoteException {
2749        try {
2750            return super.onTransact(code, data, reply, flags);
2751        } catch (RuntimeException e) {
2752            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2753                Slog.wtf(TAG, "Package Manager Crash", e);
2754            }
2755            throw e;
2756        }
2757    }
2758
2759    void cleanupInstallFailedPackage(PackageSetting ps) {
2760        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2761
2762        removeDataDirsLI(ps.volumeUuid, ps.name);
2763        if (ps.codePath != null) {
2764            if (ps.codePath.isDirectory()) {
2765                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2766            } else {
2767                ps.codePath.delete();
2768            }
2769        }
2770        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2771            if (ps.resourcePath.isDirectory()) {
2772                FileUtils.deleteContents(ps.resourcePath);
2773            }
2774            ps.resourcePath.delete();
2775        }
2776        mSettings.removePackageLPw(ps.name);
2777    }
2778
2779    static int[] appendInts(int[] cur, int[] add) {
2780        if (add == null) return cur;
2781        if (cur == null) return add;
2782        final int N = add.length;
2783        for (int i=0; i<N; i++) {
2784            cur = appendInt(cur, add[i]);
2785        }
2786        return cur;
2787    }
2788
2789    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2790        if (!sUserManager.exists(userId)) return null;
2791        final PackageSetting ps = (PackageSetting) p.mExtras;
2792        if (ps == null) {
2793            return null;
2794        }
2795
2796        final PermissionsState permissionsState = ps.getPermissionsState();
2797
2798        final int[] gids = permissionsState.computeGids(userId);
2799        final Set<String> permissions = permissionsState.getPermissions(userId);
2800        final PackageUserState state = ps.readUserState(userId);
2801
2802        return PackageParser.generatePackageInfo(p, gids, flags,
2803                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2804    }
2805
2806    @Override
2807    public void checkPackageStartable(String packageName, int userId) {
2808        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2809
2810        synchronized (mPackages) {
2811            final PackageSetting ps = mSettings.mPackages.get(packageName);
2812            if (ps == null) {
2813                throw new SecurityException("Package " + packageName + " was not found!");
2814            }
2815
2816            if (ps.frozen) {
2817                throw new SecurityException("Package " + packageName + " is currently frozen!");
2818            }
2819
2820            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2821                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2822                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2823            }
2824        }
2825    }
2826
2827    @Override
2828    public boolean isPackageAvailable(String packageName, int userId) {
2829        if (!sUserManager.exists(userId)) return false;
2830        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2831        synchronized (mPackages) {
2832            PackageParser.Package p = mPackages.get(packageName);
2833            if (p != null) {
2834                final PackageSetting ps = (PackageSetting) p.mExtras;
2835                if (ps != null) {
2836                    final PackageUserState state = ps.readUserState(userId);
2837                    if (state != null) {
2838                        return PackageParser.isAvailable(state);
2839                    }
2840                }
2841            }
2842        }
2843        return false;
2844    }
2845
2846    @Override
2847    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2848        if (!sUserManager.exists(userId)) return null;
2849        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2850        // reader
2851        synchronized (mPackages) {
2852            PackageParser.Package p = mPackages.get(packageName);
2853            if (DEBUG_PACKAGE_INFO)
2854                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2855            if (p != null) {
2856                return generatePackageInfo(p, flags, userId);
2857            }
2858            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2859                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2860            }
2861        }
2862        return null;
2863    }
2864
2865    @Override
2866    public String[] currentToCanonicalPackageNames(String[] names) {
2867        String[] out = new String[names.length];
2868        // reader
2869        synchronized (mPackages) {
2870            for (int i=names.length-1; i>=0; i--) {
2871                PackageSetting ps = mSettings.mPackages.get(names[i]);
2872                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2873            }
2874        }
2875        return out;
2876    }
2877
2878    @Override
2879    public String[] canonicalToCurrentPackageNames(String[] names) {
2880        String[] out = new String[names.length];
2881        // reader
2882        synchronized (mPackages) {
2883            for (int i=names.length-1; i>=0; i--) {
2884                String cur = mSettings.mRenamedPackages.get(names[i]);
2885                out[i] = cur != null ? cur : names[i];
2886            }
2887        }
2888        return out;
2889    }
2890
2891    @Override
2892    public int getPackageUid(String packageName, int userId) {
2893        return getPackageUidEtc(packageName, 0, userId);
2894    }
2895
2896    @Override
2897    public int getPackageUidEtc(String packageName, int flags, int userId) {
2898        if (!sUserManager.exists(userId)) return -1;
2899        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2900
2901        // reader
2902        synchronized (mPackages) {
2903            final PackageParser.Package p = mPackages.get(packageName);
2904            if (p != null) {
2905                return UserHandle.getUid(userId, p.applicationInfo.uid);
2906            }
2907            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2908                final PackageSetting ps = mSettings.mPackages.get(packageName);
2909                if (ps != null) {
2910                    return UserHandle.getUid(userId, ps.appId);
2911                }
2912            }
2913        }
2914
2915        return -1;
2916    }
2917
2918    @Override
2919    public int[] getPackageGids(String packageName, int userId) {
2920        return getPackageGidsEtc(packageName, 0, userId);
2921    }
2922
2923    @Override
2924    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2925        if (!sUserManager.exists(userId)) {
2926            return null;
2927        }
2928
2929        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2930                "getPackageGids");
2931
2932        // reader
2933        synchronized (mPackages) {
2934            final PackageParser.Package p = mPackages.get(packageName);
2935            if (p != null) {
2936                PackageSetting ps = (PackageSetting) p.mExtras;
2937                return ps.getPermissionsState().computeGids(userId);
2938            }
2939            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2940                final PackageSetting ps = mSettings.mPackages.get(packageName);
2941                if (ps != null) {
2942                    return ps.getPermissionsState().computeGids(userId);
2943                }
2944            }
2945        }
2946
2947        return null;
2948    }
2949
2950    static PermissionInfo generatePermissionInfo(
2951            BasePermission bp, int flags) {
2952        if (bp.perm != null) {
2953            return PackageParser.generatePermissionInfo(bp.perm, flags);
2954        }
2955        PermissionInfo pi = new PermissionInfo();
2956        pi.name = bp.name;
2957        pi.packageName = bp.sourcePackage;
2958        pi.nonLocalizedLabel = bp.name;
2959        pi.protectionLevel = bp.protectionLevel;
2960        return pi;
2961    }
2962
2963    @Override
2964    public PermissionInfo getPermissionInfo(String name, int flags) {
2965        // reader
2966        synchronized (mPackages) {
2967            final BasePermission p = mSettings.mPermissions.get(name);
2968            if (p != null) {
2969                return generatePermissionInfo(p, flags);
2970            }
2971            return null;
2972        }
2973    }
2974
2975    @Override
2976    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2977        // reader
2978        synchronized (mPackages) {
2979            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2980            for (BasePermission p : mSettings.mPermissions.values()) {
2981                if (group == null) {
2982                    if (p.perm == null || p.perm.info.group == null) {
2983                        out.add(generatePermissionInfo(p, flags));
2984                    }
2985                } else {
2986                    if (p.perm != null && group.equals(p.perm.info.group)) {
2987                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2988                    }
2989                }
2990            }
2991
2992            if (out.size() > 0) {
2993                return out;
2994            }
2995            return mPermissionGroups.containsKey(group) ? out : null;
2996        }
2997    }
2998
2999    @Override
3000    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3001        // reader
3002        synchronized (mPackages) {
3003            return PackageParser.generatePermissionGroupInfo(
3004                    mPermissionGroups.get(name), flags);
3005        }
3006    }
3007
3008    @Override
3009    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3010        // reader
3011        synchronized (mPackages) {
3012            final int N = mPermissionGroups.size();
3013            ArrayList<PermissionGroupInfo> out
3014                    = new ArrayList<PermissionGroupInfo>(N);
3015            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3016                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3017            }
3018            return out;
3019        }
3020    }
3021
3022    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3023            int userId) {
3024        if (!sUserManager.exists(userId)) return null;
3025        PackageSetting ps = mSettings.mPackages.get(packageName);
3026        if (ps != null) {
3027            if (ps.pkg == null) {
3028                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3029                        flags, userId);
3030                if (pInfo != null) {
3031                    return pInfo.applicationInfo;
3032                }
3033                return null;
3034            }
3035            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3036                    ps.readUserState(userId), userId);
3037        }
3038        return null;
3039    }
3040
3041    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3042            int userId) {
3043        if (!sUserManager.exists(userId)) return null;
3044        PackageSetting ps = mSettings.mPackages.get(packageName);
3045        if (ps != null) {
3046            PackageParser.Package pkg = ps.pkg;
3047            if (pkg == null) {
3048                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3049                    return null;
3050                }
3051                // Only data remains, so we aren't worried about code paths
3052                pkg = new PackageParser.Package(packageName);
3053                pkg.applicationInfo.packageName = packageName;
3054                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3055                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3056                pkg.applicationInfo.uid = ps.appId;
3057                pkg.applicationInfo.initForUser(userId);
3058                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3059                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3060            }
3061            return generatePackageInfo(pkg, flags, userId);
3062        }
3063        return null;
3064    }
3065
3066    @Override
3067    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3068        if (!sUserManager.exists(userId)) return null;
3069        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3070        // writer
3071        synchronized (mPackages) {
3072            PackageParser.Package p = mPackages.get(packageName);
3073            if (DEBUG_PACKAGE_INFO) Log.v(
3074                    TAG, "getApplicationInfo " + packageName
3075                    + ": " + p);
3076            if (p != null) {
3077                PackageSetting ps = mSettings.mPackages.get(packageName);
3078                if (ps == null) return null;
3079                // Note: isEnabledLP() does not apply here - always return info
3080                return PackageParser.generateApplicationInfo(
3081                        p, flags, ps.readUserState(userId), userId);
3082            }
3083            if ("android".equals(packageName)||"system".equals(packageName)) {
3084                return mAndroidApplication;
3085            }
3086            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3087                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3088            }
3089        }
3090        return null;
3091    }
3092
3093    @Override
3094    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3095            final IPackageDataObserver observer) {
3096        mContext.enforceCallingOrSelfPermission(
3097                android.Manifest.permission.CLEAR_APP_CACHE, null);
3098        // Queue up an async operation since clearing cache may take a little while.
3099        mHandler.post(new Runnable() {
3100            public void run() {
3101                mHandler.removeCallbacks(this);
3102                int retCode = -1;
3103                synchronized (mInstallLock) {
3104                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3105                    if (retCode < 0) {
3106                        Slog.w(TAG, "Couldn't clear application caches");
3107                    }
3108                }
3109                if (observer != null) {
3110                    try {
3111                        observer.onRemoveCompleted(null, (retCode >= 0));
3112                    } catch (RemoteException e) {
3113                        Slog.w(TAG, "RemoveException when invoking call back");
3114                    }
3115                }
3116            }
3117        });
3118    }
3119
3120    @Override
3121    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3122            final IntentSender pi) {
3123        mContext.enforceCallingOrSelfPermission(
3124                android.Manifest.permission.CLEAR_APP_CACHE, null);
3125        // Queue up an async operation since clearing cache may take a little while.
3126        mHandler.post(new Runnable() {
3127            public void run() {
3128                mHandler.removeCallbacks(this);
3129                int retCode = -1;
3130                synchronized (mInstallLock) {
3131                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3132                    if (retCode < 0) {
3133                        Slog.w(TAG, "Couldn't clear application caches");
3134                    }
3135                }
3136                if(pi != null) {
3137                    try {
3138                        // Callback via pending intent
3139                        int code = (retCode >= 0) ? 1 : 0;
3140                        pi.sendIntent(null, code, null,
3141                                null, null);
3142                    } catch (SendIntentException e1) {
3143                        Slog.i(TAG, "Failed to send pending intent");
3144                    }
3145                }
3146            }
3147        });
3148    }
3149
3150    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3151        synchronized (mInstallLock) {
3152            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3153                throw new IOException("Failed to free enough space");
3154            }
3155        }
3156    }
3157
3158    /**
3159     * Return if the user key is currently unlocked.
3160     */
3161    private boolean isUserKeyUnlocked(int userId) {
3162        if (StorageManager.isFileBasedEncryptionEnabled()) {
3163            final IMountService mount = IMountService.Stub
3164                    .asInterface(ServiceManager.getService("mount"));
3165            if (mount == null) {
3166                Slog.w(TAG, "Early during boot, assuming locked");
3167                return false;
3168            }
3169            final long token = Binder.clearCallingIdentity();
3170            try {
3171                return mount.isUserKeyUnlocked(userId);
3172            } catch (RemoteException e) {
3173                throw e.rethrowAsRuntimeException();
3174            } finally {
3175                Binder.restoreCallingIdentity(token);
3176            }
3177        } else {
3178            return true;
3179        }
3180    }
3181
3182    /**
3183     * Augment the given flags depending on current user running state. This is
3184     * purposefully done before acquiring {@link #mPackages} lock.
3185     */
3186    private int augmentFlagsForUser(int flags, int userId) {
3187        if (!isUserKeyUnlocked(userId)) {
3188            flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3189        }
3190        return flags;
3191    }
3192
3193    @Override
3194    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3195        if (!sUserManager.exists(userId)) return null;
3196        flags = augmentFlagsForUser(flags, userId);
3197        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3198        synchronized (mPackages) {
3199            PackageParser.Activity a = mActivities.mActivities.get(component);
3200
3201            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3202            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3203                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3204                if (ps == null) return null;
3205                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3206                        userId);
3207            }
3208            if (mResolveComponentName.equals(component)) {
3209                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3210                        new PackageUserState(), userId);
3211            }
3212        }
3213        return null;
3214    }
3215
3216    @Override
3217    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3218            String resolvedType) {
3219        synchronized (mPackages) {
3220            if (component.equals(mResolveComponentName)) {
3221                // The resolver supports EVERYTHING!
3222                return true;
3223            }
3224            PackageParser.Activity a = mActivities.mActivities.get(component);
3225            if (a == null) {
3226                return false;
3227            }
3228            for (int i=0; i<a.intents.size(); i++) {
3229                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3230                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3231                    return true;
3232                }
3233            }
3234            return false;
3235        }
3236    }
3237
3238    @Override
3239    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3240        if (!sUserManager.exists(userId)) return null;
3241        flags = augmentFlagsForUser(flags, userId);
3242        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3243        synchronized (mPackages) {
3244            PackageParser.Activity a = mReceivers.mActivities.get(component);
3245            if (DEBUG_PACKAGE_INFO) Log.v(
3246                TAG, "getReceiverInfo " + component + ": " + a);
3247            if (a != null && mSettings.isEnabledAndVisibleLPr(a.info, flags, userId)) {
3248                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3249                if (ps == null) return null;
3250                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3251                        userId);
3252            }
3253        }
3254        return null;
3255    }
3256
3257    @Override
3258    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3259        if (!sUserManager.exists(userId)) return null;
3260        flags = augmentFlagsForUser(flags, userId);
3261        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3262        synchronized (mPackages) {
3263            PackageParser.Service s = mServices.mServices.get(component);
3264            if (DEBUG_PACKAGE_INFO) Log.v(
3265                TAG, "getServiceInfo " + component + ": " + s);
3266            if (s != null && mSettings.isEnabledAndVisibleLPr(s.info, flags, userId)) {
3267                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3268                if (ps == null) return null;
3269                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3270                        userId);
3271            }
3272        }
3273        return null;
3274    }
3275
3276    @Override
3277    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3278        if (!sUserManager.exists(userId)) return null;
3279        flags = augmentFlagsForUser(flags, userId);
3280        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3281        synchronized (mPackages) {
3282            PackageParser.Provider p = mProviders.mProviders.get(component);
3283            if (DEBUG_PACKAGE_INFO) Log.v(
3284                TAG, "getProviderInfo " + component + ": " + p);
3285            if (p != null && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)) {
3286                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3287                if (ps == null) return null;
3288                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3289                        userId);
3290            }
3291        }
3292        return null;
3293    }
3294
3295    @Override
3296    public String[] getSystemSharedLibraryNames() {
3297        Set<String> libSet;
3298        synchronized (mPackages) {
3299            libSet = mSharedLibraries.keySet();
3300            int size = libSet.size();
3301            if (size > 0) {
3302                String[] libs = new String[size];
3303                libSet.toArray(libs);
3304                return libs;
3305            }
3306        }
3307        return null;
3308    }
3309
3310    /**
3311     * @hide
3312     */
3313    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3314        synchronized (mPackages) {
3315            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3316            if (lib != null && lib.apk != null) {
3317                return mPackages.get(lib.apk);
3318            }
3319        }
3320        return null;
3321    }
3322
3323    @Override
3324    public FeatureInfo[] getSystemAvailableFeatures() {
3325        Collection<FeatureInfo> featSet;
3326        synchronized (mPackages) {
3327            featSet = mAvailableFeatures.values();
3328            int size = featSet.size();
3329            if (size > 0) {
3330                FeatureInfo[] features = new FeatureInfo[size+1];
3331                featSet.toArray(features);
3332                FeatureInfo fi = new FeatureInfo();
3333                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3334                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3335                features[size] = fi;
3336                return features;
3337            }
3338        }
3339        return null;
3340    }
3341
3342    @Override
3343    public boolean hasSystemFeature(String name) {
3344        synchronized (mPackages) {
3345            return mAvailableFeatures.containsKey(name);
3346        }
3347    }
3348
3349    @Override
3350    public int checkPermission(String permName, String pkgName, int userId) {
3351        if (!sUserManager.exists(userId)) {
3352            return PackageManager.PERMISSION_DENIED;
3353        }
3354
3355        synchronized (mPackages) {
3356            final PackageParser.Package p = mPackages.get(pkgName);
3357            if (p != null && p.mExtras != null) {
3358                final PackageSetting ps = (PackageSetting) p.mExtras;
3359                final PermissionsState permissionsState = ps.getPermissionsState();
3360                if (permissionsState.hasPermission(permName, userId)) {
3361                    return PackageManager.PERMISSION_GRANTED;
3362                }
3363                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3364                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3365                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3366                    return PackageManager.PERMISSION_GRANTED;
3367                }
3368            }
3369        }
3370
3371        return PackageManager.PERMISSION_DENIED;
3372    }
3373
3374    @Override
3375    public int checkUidPermission(String permName, int uid) {
3376        final int userId = UserHandle.getUserId(uid);
3377
3378        if (!sUserManager.exists(userId)) {
3379            return PackageManager.PERMISSION_DENIED;
3380        }
3381
3382        synchronized (mPackages) {
3383            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3384            if (obj != null) {
3385                final SettingBase ps = (SettingBase) obj;
3386                final PermissionsState permissionsState = ps.getPermissionsState();
3387                if (permissionsState.hasPermission(permName, userId)) {
3388                    return PackageManager.PERMISSION_GRANTED;
3389                }
3390                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3391                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3392                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3393                    return PackageManager.PERMISSION_GRANTED;
3394                }
3395            } else {
3396                ArraySet<String> perms = mSystemPermissions.get(uid);
3397                if (perms != null) {
3398                    if (perms.contains(permName)) {
3399                        return PackageManager.PERMISSION_GRANTED;
3400                    }
3401                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3402                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3403                        return PackageManager.PERMISSION_GRANTED;
3404                    }
3405                }
3406            }
3407        }
3408
3409        return PackageManager.PERMISSION_DENIED;
3410    }
3411
3412    @Override
3413    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3414        if (UserHandle.getCallingUserId() != userId) {
3415            mContext.enforceCallingPermission(
3416                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3417                    "isPermissionRevokedByPolicy for user " + userId);
3418        }
3419
3420        if (checkPermission(permission, packageName, userId)
3421                == PackageManager.PERMISSION_GRANTED) {
3422            return false;
3423        }
3424
3425        final long identity = Binder.clearCallingIdentity();
3426        try {
3427            final int flags = getPermissionFlags(permission, packageName, userId);
3428            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3429        } finally {
3430            Binder.restoreCallingIdentity(identity);
3431        }
3432    }
3433
3434    @Override
3435    public String getPermissionControllerPackageName() {
3436        synchronized (mPackages) {
3437            return mRequiredInstallerPackage;
3438        }
3439    }
3440
3441    /**
3442     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3443     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3444     * @param checkShell TODO(yamasani):
3445     * @param message the message to log on security exception
3446     */
3447    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3448            boolean checkShell, String message) {
3449        if (userId < 0) {
3450            throw new IllegalArgumentException("Invalid userId " + userId);
3451        }
3452        if (checkShell) {
3453            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3454        }
3455        if (userId == UserHandle.getUserId(callingUid)) return;
3456        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3457            if (requireFullPermission) {
3458                mContext.enforceCallingOrSelfPermission(
3459                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3460            } else {
3461                try {
3462                    mContext.enforceCallingOrSelfPermission(
3463                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3464                } catch (SecurityException se) {
3465                    mContext.enforceCallingOrSelfPermission(
3466                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3467                }
3468            }
3469        }
3470    }
3471
3472    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3473        if (callingUid == Process.SHELL_UID) {
3474            if (userHandle >= 0
3475                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3476                throw new SecurityException("Shell does not have permission to access user "
3477                        + userHandle);
3478            } else if (userHandle < 0) {
3479                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3480                        + Debug.getCallers(3));
3481            }
3482        }
3483    }
3484
3485    private BasePermission findPermissionTreeLP(String permName) {
3486        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3487            if (permName.startsWith(bp.name) &&
3488                    permName.length() > bp.name.length() &&
3489                    permName.charAt(bp.name.length()) == '.') {
3490                return bp;
3491            }
3492        }
3493        return null;
3494    }
3495
3496    private BasePermission checkPermissionTreeLP(String permName) {
3497        if (permName != null) {
3498            BasePermission bp = findPermissionTreeLP(permName);
3499            if (bp != null) {
3500                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3501                    return bp;
3502                }
3503                throw new SecurityException("Calling uid "
3504                        + Binder.getCallingUid()
3505                        + " is not allowed to add to permission tree "
3506                        + bp.name + " owned by uid " + bp.uid);
3507            }
3508        }
3509        throw new SecurityException("No permission tree found for " + permName);
3510    }
3511
3512    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3513        if (s1 == null) {
3514            return s2 == null;
3515        }
3516        if (s2 == null) {
3517            return false;
3518        }
3519        if (s1.getClass() != s2.getClass()) {
3520            return false;
3521        }
3522        return s1.equals(s2);
3523    }
3524
3525    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3526        if (pi1.icon != pi2.icon) return false;
3527        if (pi1.logo != pi2.logo) return false;
3528        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3529        if (!compareStrings(pi1.name, pi2.name)) return false;
3530        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3531        // We'll take care of setting this one.
3532        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3533        // These are not currently stored in settings.
3534        //if (!compareStrings(pi1.group, pi2.group)) return false;
3535        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3536        //if (pi1.labelRes != pi2.labelRes) return false;
3537        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3538        return true;
3539    }
3540
3541    int permissionInfoFootprint(PermissionInfo info) {
3542        int size = info.name.length();
3543        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3544        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3545        return size;
3546    }
3547
3548    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3549        int size = 0;
3550        for (BasePermission perm : mSettings.mPermissions.values()) {
3551            if (perm.uid == tree.uid) {
3552                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3553            }
3554        }
3555        return size;
3556    }
3557
3558    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3559        // We calculate the max size of permissions defined by this uid and throw
3560        // if that plus the size of 'info' would exceed our stated maximum.
3561        if (tree.uid != Process.SYSTEM_UID) {
3562            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3563            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3564                throw new SecurityException("Permission tree size cap exceeded");
3565            }
3566        }
3567    }
3568
3569    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3570        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3571            throw new SecurityException("Label must be specified in permission");
3572        }
3573        BasePermission tree = checkPermissionTreeLP(info.name);
3574        BasePermission bp = mSettings.mPermissions.get(info.name);
3575        boolean added = bp == null;
3576        boolean changed = true;
3577        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3578        if (added) {
3579            enforcePermissionCapLocked(info, tree);
3580            bp = new BasePermission(info.name, tree.sourcePackage,
3581                    BasePermission.TYPE_DYNAMIC);
3582        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3583            throw new SecurityException(
3584                    "Not allowed to modify non-dynamic permission "
3585                    + info.name);
3586        } else {
3587            if (bp.protectionLevel == fixedLevel
3588                    && bp.perm.owner.equals(tree.perm.owner)
3589                    && bp.uid == tree.uid
3590                    && comparePermissionInfos(bp.perm.info, info)) {
3591                changed = false;
3592            }
3593        }
3594        bp.protectionLevel = fixedLevel;
3595        info = new PermissionInfo(info);
3596        info.protectionLevel = fixedLevel;
3597        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3598        bp.perm.info.packageName = tree.perm.info.packageName;
3599        bp.uid = tree.uid;
3600        if (added) {
3601            mSettings.mPermissions.put(info.name, bp);
3602        }
3603        if (changed) {
3604            if (!async) {
3605                mSettings.writeLPr();
3606            } else {
3607                scheduleWriteSettingsLocked();
3608            }
3609        }
3610        return added;
3611    }
3612
3613    @Override
3614    public boolean addPermission(PermissionInfo info) {
3615        synchronized (mPackages) {
3616            return addPermissionLocked(info, false);
3617        }
3618    }
3619
3620    @Override
3621    public boolean addPermissionAsync(PermissionInfo info) {
3622        synchronized (mPackages) {
3623            return addPermissionLocked(info, true);
3624        }
3625    }
3626
3627    @Override
3628    public void removePermission(String name) {
3629        synchronized (mPackages) {
3630            checkPermissionTreeLP(name);
3631            BasePermission bp = mSettings.mPermissions.get(name);
3632            if (bp != null) {
3633                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3634                    throw new SecurityException(
3635                            "Not allowed to modify non-dynamic permission "
3636                            + name);
3637                }
3638                mSettings.mPermissions.remove(name);
3639                mSettings.writeLPr();
3640            }
3641        }
3642    }
3643
3644    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3645            BasePermission bp) {
3646        int index = pkg.requestedPermissions.indexOf(bp.name);
3647        if (index == -1) {
3648            throw new SecurityException("Package " + pkg.packageName
3649                    + " has not requested permission " + bp.name);
3650        }
3651        if (!bp.isRuntime() && !bp.isDevelopment()) {
3652            throw new SecurityException("Permission " + bp.name
3653                    + " is not a changeable permission type");
3654        }
3655    }
3656
3657    @Override
3658    public void grantRuntimePermission(String packageName, String name, final int userId) {
3659        if (!sUserManager.exists(userId)) {
3660            Log.e(TAG, "No such user:" + userId);
3661            return;
3662        }
3663
3664        mContext.enforceCallingOrSelfPermission(
3665                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3666                "grantRuntimePermission");
3667
3668        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3669                "grantRuntimePermission");
3670
3671        final int uid;
3672        final SettingBase sb;
3673
3674        synchronized (mPackages) {
3675            final PackageParser.Package pkg = mPackages.get(packageName);
3676            if (pkg == null) {
3677                throw new IllegalArgumentException("Unknown package: " + packageName);
3678            }
3679
3680            final BasePermission bp = mSettings.mPermissions.get(name);
3681            if (bp == null) {
3682                throw new IllegalArgumentException("Unknown permission: " + name);
3683            }
3684
3685            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3686
3687            // If a permission review is required for legacy apps we represent
3688            // their permissions as always granted runtime ones since we need
3689            // to keep the review required permission flag per user while an
3690            // install permission's state is shared across all users.
3691            if (Build.PERMISSIONS_REVIEW_REQUIRED
3692                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3693                    && bp.isRuntime()) {
3694                return;
3695            }
3696
3697            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3698            sb = (SettingBase) pkg.mExtras;
3699            if (sb == null) {
3700                throw new IllegalArgumentException("Unknown package: " + packageName);
3701            }
3702
3703            final PermissionsState permissionsState = sb.getPermissionsState();
3704
3705            final int flags = permissionsState.getPermissionFlags(name, userId);
3706            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3707                throw new SecurityException("Cannot grant system fixed permission: "
3708                        + name + " for package: " + packageName);
3709            }
3710
3711            if (bp.isDevelopment()) {
3712                // Development permissions must be handled specially, since they are not
3713                // normal runtime permissions.  For now they apply to all users.
3714                if (permissionsState.grantInstallPermission(bp) !=
3715                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3716                    scheduleWriteSettingsLocked();
3717                }
3718                return;
3719            }
3720
3721            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3722                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3723                return;
3724            }
3725
3726            final int result = permissionsState.grantRuntimePermission(bp, userId);
3727            switch (result) {
3728                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3729                    return;
3730                }
3731
3732                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3733                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3734                    mHandler.post(new Runnable() {
3735                        @Override
3736                        public void run() {
3737                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3738                        }
3739                    });
3740                }
3741                break;
3742            }
3743
3744            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3745
3746            // Not critical if that is lost - app has to request again.
3747            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3748        }
3749
3750        // Only need to do this if user is initialized. Otherwise it's a new user
3751        // and there are no processes running as the user yet and there's no need
3752        // to make an expensive call to remount processes for the changed permissions.
3753        if (READ_EXTERNAL_STORAGE.equals(name)
3754                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3755            final long token = Binder.clearCallingIdentity();
3756            try {
3757                if (sUserManager.isInitialized(userId)) {
3758                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3759                            MountServiceInternal.class);
3760                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3761                }
3762            } finally {
3763                Binder.restoreCallingIdentity(token);
3764            }
3765        }
3766    }
3767
3768    @Override
3769    public void revokeRuntimePermission(String packageName, String name, int userId) {
3770        if (!sUserManager.exists(userId)) {
3771            Log.e(TAG, "No such user:" + userId);
3772            return;
3773        }
3774
3775        mContext.enforceCallingOrSelfPermission(
3776                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3777                "revokeRuntimePermission");
3778
3779        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3780                "revokeRuntimePermission");
3781
3782        final int appId;
3783
3784        synchronized (mPackages) {
3785            final PackageParser.Package pkg = mPackages.get(packageName);
3786            if (pkg == null) {
3787                throw new IllegalArgumentException("Unknown package: " + packageName);
3788            }
3789
3790            final BasePermission bp = mSettings.mPermissions.get(name);
3791            if (bp == null) {
3792                throw new IllegalArgumentException("Unknown permission: " + name);
3793            }
3794
3795            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3796
3797            // If a permission review is required for legacy apps we represent
3798            // their permissions as always granted runtime ones since we need
3799            // to keep the review required permission flag per user while an
3800            // install permission's state is shared across all users.
3801            if (Build.PERMISSIONS_REVIEW_REQUIRED
3802                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3803                    && bp.isRuntime()) {
3804                return;
3805            }
3806
3807            SettingBase sb = (SettingBase) pkg.mExtras;
3808            if (sb == null) {
3809                throw new IllegalArgumentException("Unknown package: " + packageName);
3810            }
3811
3812            final PermissionsState permissionsState = sb.getPermissionsState();
3813
3814            final int flags = permissionsState.getPermissionFlags(name, userId);
3815            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3816                throw new SecurityException("Cannot revoke system fixed permission: "
3817                        + name + " for package: " + packageName);
3818            }
3819
3820            if (bp.isDevelopment()) {
3821                // Development permissions must be handled specially, since they are not
3822                // normal runtime permissions.  For now they apply to all users.
3823                if (permissionsState.revokeInstallPermission(bp) !=
3824                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3825                    scheduleWriteSettingsLocked();
3826                }
3827                return;
3828            }
3829
3830            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3831                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3832                return;
3833            }
3834
3835            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3836
3837            // Critical, after this call app should never have the permission.
3838            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3839
3840            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3841        }
3842
3843        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3844    }
3845
3846    @Override
3847    public void resetRuntimePermissions() {
3848        mContext.enforceCallingOrSelfPermission(
3849                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3850                "revokeRuntimePermission");
3851
3852        int callingUid = Binder.getCallingUid();
3853        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3854            mContext.enforceCallingOrSelfPermission(
3855                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3856                    "resetRuntimePermissions");
3857        }
3858
3859        synchronized (mPackages) {
3860            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3861            for (int userId : UserManagerService.getInstance().getUserIds()) {
3862                final int packageCount = mPackages.size();
3863                for (int i = 0; i < packageCount; i++) {
3864                    PackageParser.Package pkg = mPackages.valueAt(i);
3865                    if (!(pkg.mExtras instanceof PackageSetting)) {
3866                        continue;
3867                    }
3868                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3869                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3870                }
3871            }
3872        }
3873    }
3874
3875    @Override
3876    public int getPermissionFlags(String name, String packageName, int userId) {
3877        if (!sUserManager.exists(userId)) {
3878            return 0;
3879        }
3880
3881        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3882
3883        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3884                "getPermissionFlags");
3885
3886        synchronized (mPackages) {
3887            final PackageParser.Package pkg = mPackages.get(packageName);
3888            if (pkg == null) {
3889                throw new IllegalArgumentException("Unknown package: " + packageName);
3890            }
3891
3892            final BasePermission bp = mSettings.mPermissions.get(name);
3893            if (bp == null) {
3894                throw new IllegalArgumentException("Unknown permission: " + name);
3895            }
3896
3897            SettingBase sb = (SettingBase) pkg.mExtras;
3898            if (sb == null) {
3899                throw new IllegalArgumentException("Unknown package: " + packageName);
3900            }
3901
3902            PermissionsState permissionsState = sb.getPermissionsState();
3903            return permissionsState.getPermissionFlags(name, userId);
3904        }
3905    }
3906
3907    @Override
3908    public void updatePermissionFlags(String name, String packageName, int flagMask,
3909            int flagValues, int userId) {
3910        if (!sUserManager.exists(userId)) {
3911            return;
3912        }
3913
3914        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3915
3916        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3917                "updatePermissionFlags");
3918
3919        // Only the system can change these flags and nothing else.
3920        if (getCallingUid() != Process.SYSTEM_UID) {
3921            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3922            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3923            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3924            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3925            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3926        }
3927
3928        synchronized (mPackages) {
3929            final PackageParser.Package pkg = mPackages.get(packageName);
3930            if (pkg == null) {
3931                throw new IllegalArgumentException("Unknown package: " + packageName);
3932            }
3933
3934            final BasePermission bp = mSettings.mPermissions.get(name);
3935            if (bp == null) {
3936                throw new IllegalArgumentException("Unknown permission: " + name);
3937            }
3938
3939            SettingBase sb = (SettingBase) pkg.mExtras;
3940            if (sb == null) {
3941                throw new IllegalArgumentException("Unknown package: " + packageName);
3942            }
3943
3944            PermissionsState permissionsState = sb.getPermissionsState();
3945
3946            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3947
3948            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3949                // Install and runtime permissions are stored in different places,
3950                // so figure out what permission changed and persist the change.
3951                if (permissionsState.getInstallPermissionState(name) != null) {
3952                    scheduleWriteSettingsLocked();
3953                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3954                        || hadState) {
3955                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3956                }
3957            }
3958        }
3959    }
3960
3961    /**
3962     * Update the permission flags for all packages and runtime permissions of a user in order
3963     * to allow device or profile owner to remove POLICY_FIXED.
3964     */
3965    @Override
3966    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3967        if (!sUserManager.exists(userId)) {
3968            return;
3969        }
3970
3971        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3972
3973        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3974                "updatePermissionFlagsForAllApps");
3975
3976        // Only the system can change system fixed flags.
3977        if (getCallingUid() != Process.SYSTEM_UID) {
3978            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3979            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3980        }
3981
3982        synchronized (mPackages) {
3983            boolean changed = false;
3984            final int packageCount = mPackages.size();
3985            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3986                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3987                SettingBase sb = (SettingBase) pkg.mExtras;
3988                if (sb == null) {
3989                    continue;
3990                }
3991                PermissionsState permissionsState = sb.getPermissionsState();
3992                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3993                        userId, flagMask, flagValues);
3994            }
3995            if (changed) {
3996                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3997            }
3998        }
3999    }
4000
4001    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4002        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4003                != PackageManager.PERMISSION_GRANTED
4004            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4005                != PackageManager.PERMISSION_GRANTED) {
4006            throw new SecurityException(message + " requires "
4007                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4008                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4009        }
4010    }
4011
4012    @Override
4013    public boolean shouldShowRequestPermissionRationale(String permissionName,
4014            String packageName, int userId) {
4015        if (UserHandle.getCallingUserId() != userId) {
4016            mContext.enforceCallingPermission(
4017                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4018                    "canShowRequestPermissionRationale for user " + userId);
4019        }
4020
4021        final int uid = getPackageUid(packageName, userId);
4022        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4023            return false;
4024        }
4025
4026        if (checkPermission(permissionName, packageName, userId)
4027                == PackageManager.PERMISSION_GRANTED) {
4028            return false;
4029        }
4030
4031        final int flags;
4032
4033        final long identity = Binder.clearCallingIdentity();
4034        try {
4035            flags = getPermissionFlags(permissionName,
4036                    packageName, userId);
4037        } finally {
4038            Binder.restoreCallingIdentity(identity);
4039        }
4040
4041        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4042                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4043                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4044
4045        if ((flags & fixedFlags) != 0) {
4046            return false;
4047        }
4048
4049        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4050    }
4051
4052    @Override
4053    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4054        mContext.enforceCallingOrSelfPermission(
4055                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4056                "addOnPermissionsChangeListener");
4057
4058        synchronized (mPackages) {
4059            mOnPermissionChangeListeners.addListenerLocked(listener);
4060        }
4061    }
4062
4063    @Override
4064    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4065        synchronized (mPackages) {
4066            mOnPermissionChangeListeners.removeListenerLocked(listener);
4067        }
4068    }
4069
4070    @Override
4071    public boolean isProtectedBroadcast(String actionName) {
4072        synchronized (mPackages) {
4073            if (mProtectedBroadcasts.contains(actionName)) {
4074                return true;
4075            } else if (actionName != null) {
4076                // TODO: remove these terrible hacks
4077                if (actionName.startsWith("android.net.netmon.lingerExpired")
4078                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4079                    return true;
4080                }
4081            }
4082        }
4083        return false;
4084    }
4085
4086    @Override
4087    public int checkSignatures(String pkg1, String pkg2) {
4088        synchronized (mPackages) {
4089            final PackageParser.Package p1 = mPackages.get(pkg1);
4090            final PackageParser.Package p2 = mPackages.get(pkg2);
4091            if (p1 == null || p1.mExtras == null
4092                    || p2 == null || p2.mExtras == null) {
4093                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4094            }
4095            return compareSignatures(p1.mSignatures, p2.mSignatures);
4096        }
4097    }
4098
4099    @Override
4100    public int checkUidSignatures(int uid1, int uid2) {
4101        // Map to base uids.
4102        uid1 = UserHandle.getAppId(uid1);
4103        uid2 = UserHandle.getAppId(uid2);
4104        // reader
4105        synchronized (mPackages) {
4106            Signature[] s1;
4107            Signature[] s2;
4108            Object obj = mSettings.getUserIdLPr(uid1);
4109            if (obj != null) {
4110                if (obj instanceof SharedUserSetting) {
4111                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4112                } else if (obj instanceof PackageSetting) {
4113                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4114                } else {
4115                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4116                }
4117            } else {
4118                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4119            }
4120            obj = mSettings.getUserIdLPr(uid2);
4121            if (obj != null) {
4122                if (obj instanceof SharedUserSetting) {
4123                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4124                } else if (obj instanceof PackageSetting) {
4125                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4126                } else {
4127                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4128                }
4129            } else {
4130                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4131            }
4132            return compareSignatures(s1, s2);
4133        }
4134    }
4135
4136    private void killUid(int appId, int userId, String reason) {
4137        final long identity = Binder.clearCallingIdentity();
4138        try {
4139            IActivityManager am = ActivityManagerNative.getDefault();
4140            if (am != null) {
4141                try {
4142                    am.killUid(appId, userId, reason);
4143                } catch (RemoteException e) {
4144                    /* ignore - same process */
4145                }
4146            }
4147        } finally {
4148            Binder.restoreCallingIdentity(identity);
4149        }
4150    }
4151
4152    /**
4153     * Compares two sets of signatures. Returns:
4154     * <br />
4155     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4156     * <br />
4157     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4158     * <br />
4159     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4160     * <br />
4161     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4162     * <br />
4163     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4164     */
4165    static int compareSignatures(Signature[] s1, Signature[] s2) {
4166        if (s1 == null) {
4167            return s2 == null
4168                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4169                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4170        }
4171
4172        if (s2 == null) {
4173            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4174        }
4175
4176        if (s1.length != s2.length) {
4177            return PackageManager.SIGNATURE_NO_MATCH;
4178        }
4179
4180        // Since both signature sets are of size 1, we can compare without HashSets.
4181        if (s1.length == 1) {
4182            return s1[0].equals(s2[0]) ?
4183                    PackageManager.SIGNATURE_MATCH :
4184                    PackageManager.SIGNATURE_NO_MATCH;
4185        }
4186
4187        ArraySet<Signature> set1 = new ArraySet<Signature>();
4188        for (Signature sig : s1) {
4189            set1.add(sig);
4190        }
4191        ArraySet<Signature> set2 = new ArraySet<Signature>();
4192        for (Signature sig : s2) {
4193            set2.add(sig);
4194        }
4195        // Make sure s2 contains all signatures in s1.
4196        if (set1.equals(set2)) {
4197            return PackageManager.SIGNATURE_MATCH;
4198        }
4199        return PackageManager.SIGNATURE_NO_MATCH;
4200    }
4201
4202    /**
4203     * If the database version for this type of package (internal storage or
4204     * external storage) is less than the version where package signatures
4205     * were updated, return true.
4206     */
4207    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4208        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4209        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4210    }
4211
4212    /**
4213     * Used for backward compatibility to make sure any packages with
4214     * certificate chains get upgraded to the new style. {@code existingSigs}
4215     * will be in the old format (since they were stored on disk from before the
4216     * system upgrade) and {@code scannedSigs} will be in the newer format.
4217     */
4218    private int compareSignaturesCompat(PackageSignatures existingSigs,
4219            PackageParser.Package scannedPkg) {
4220        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4221            return PackageManager.SIGNATURE_NO_MATCH;
4222        }
4223
4224        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4225        for (Signature sig : existingSigs.mSignatures) {
4226            existingSet.add(sig);
4227        }
4228        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4229        for (Signature sig : scannedPkg.mSignatures) {
4230            try {
4231                Signature[] chainSignatures = sig.getChainSignatures();
4232                for (Signature chainSig : chainSignatures) {
4233                    scannedCompatSet.add(chainSig);
4234                }
4235            } catch (CertificateEncodingException e) {
4236                scannedCompatSet.add(sig);
4237            }
4238        }
4239        /*
4240         * Make sure the expanded scanned set contains all signatures in the
4241         * existing one.
4242         */
4243        if (scannedCompatSet.equals(existingSet)) {
4244            // Migrate the old signatures to the new scheme.
4245            existingSigs.assignSignatures(scannedPkg.mSignatures);
4246            // The new KeySets will be re-added later in the scanning process.
4247            synchronized (mPackages) {
4248                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4249            }
4250            return PackageManager.SIGNATURE_MATCH;
4251        }
4252        return PackageManager.SIGNATURE_NO_MATCH;
4253    }
4254
4255    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4256        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4257        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4258    }
4259
4260    private int compareSignaturesRecover(PackageSignatures existingSigs,
4261            PackageParser.Package scannedPkg) {
4262        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4263            return PackageManager.SIGNATURE_NO_MATCH;
4264        }
4265
4266        String msg = null;
4267        try {
4268            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4269                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4270                        + scannedPkg.packageName);
4271                return PackageManager.SIGNATURE_MATCH;
4272            }
4273        } catch (CertificateException e) {
4274            msg = e.getMessage();
4275        }
4276
4277        logCriticalInfo(Log.INFO,
4278                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4279        return PackageManager.SIGNATURE_NO_MATCH;
4280    }
4281
4282    @Override
4283    public String[] getPackagesForUid(int uid) {
4284        uid = UserHandle.getAppId(uid);
4285        // reader
4286        synchronized (mPackages) {
4287            Object obj = mSettings.getUserIdLPr(uid);
4288            if (obj instanceof SharedUserSetting) {
4289                final SharedUserSetting sus = (SharedUserSetting) obj;
4290                final int N = sus.packages.size();
4291                final String[] res = new String[N];
4292                final Iterator<PackageSetting> it = sus.packages.iterator();
4293                int i = 0;
4294                while (it.hasNext()) {
4295                    res[i++] = it.next().name;
4296                }
4297                return res;
4298            } else if (obj instanceof PackageSetting) {
4299                final PackageSetting ps = (PackageSetting) obj;
4300                return new String[] { ps.name };
4301            }
4302        }
4303        return null;
4304    }
4305
4306    @Override
4307    public String getNameForUid(int uid) {
4308        // reader
4309        synchronized (mPackages) {
4310            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4311            if (obj instanceof SharedUserSetting) {
4312                final SharedUserSetting sus = (SharedUserSetting) obj;
4313                return sus.name + ":" + sus.userId;
4314            } else if (obj instanceof PackageSetting) {
4315                final PackageSetting ps = (PackageSetting) obj;
4316                return ps.name;
4317            }
4318        }
4319        return null;
4320    }
4321
4322    @Override
4323    public int getUidForSharedUser(String sharedUserName) {
4324        if(sharedUserName == null) {
4325            return -1;
4326        }
4327        // reader
4328        synchronized (mPackages) {
4329            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4330            if (suid == null) {
4331                return -1;
4332            }
4333            return suid.userId;
4334        }
4335    }
4336
4337    @Override
4338    public int getFlagsForUid(int uid) {
4339        synchronized (mPackages) {
4340            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4341            if (obj instanceof SharedUserSetting) {
4342                final SharedUserSetting sus = (SharedUserSetting) obj;
4343                return sus.pkgFlags;
4344            } else if (obj instanceof PackageSetting) {
4345                final PackageSetting ps = (PackageSetting) obj;
4346                return ps.pkgFlags;
4347            }
4348        }
4349        return 0;
4350    }
4351
4352    @Override
4353    public int getPrivateFlagsForUid(int uid) {
4354        synchronized (mPackages) {
4355            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4356            if (obj instanceof SharedUserSetting) {
4357                final SharedUserSetting sus = (SharedUserSetting) obj;
4358                return sus.pkgPrivateFlags;
4359            } else if (obj instanceof PackageSetting) {
4360                final PackageSetting ps = (PackageSetting) obj;
4361                return ps.pkgPrivateFlags;
4362            }
4363        }
4364        return 0;
4365    }
4366
4367    @Override
4368    public boolean isUidPrivileged(int uid) {
4369        uid = UserHandle.getAppId(uid);
4370        // reader
4371        synchronized (mPackages) {
4372            Object obj = mSettings.getUserIdLPr(uid);
4373            if (obj instanceof SharedUserSetting) {
4374                final SharedUserSetting sus = (SharedUserSetting) obj;
4375                final Iterator<PackageSetting> it = sus.packages.iterator();
4376                while (it.hasNext()) {
4377                    if (it.next().isPrivileged()) {
4378                        return true;
4379                    }
4380                }
4381            } else if (obj instanceof PackageSetting) {
4382                final PackageSetting ps = (PackageSetting) obj;
4383                return ps.isPrivileged();
4384            }
4385        }
4386        return false;
4387    }
4388
4389    @Override
4390    public String[] getAppOpPermissionPackages(String permissionName) {
4391        synchronized (mPackages) {
4392            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4393            if (pkgs == null) {
4394                return null;
4395            }
4396            return pkgs.toArray(new String[pkgs.size()]);
4397        }
4398    }
4399
4400    @Override
4401    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4402            int flags, int userId) {
4403        if (!sUserManager.exists(userId)) return null;
4404        flags = augmentFlagsForUser(flags, userId);
4405        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4406        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4407        final ResolveInfo bestChoice =
4408                chooseBestActivity(intent, resolvedType, flags, query, userId);
4409
4410        if (isEphemeralAllowed(intent, query, userId)) {
4411            final EphemeralResolveInfo ai =
4412                    getEphemeralResolveInfo(intent, resolvedType, userId);
4413            if (ai != null) {
4414                if (DEBUG_EPHEMERAL) {
4415                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4416                }
4417                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4418                bestChoice.ephemeralResolveInfo = ai;
4419            }
4420        }
4421        return bestChoice;
4422    }
4423
4424    @Override
4425    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4426            IntentFilter filter, int match, ComponentName activity) {
4427        final int userId = UserHandle.getCallingUserId();
4428        if (DEBUG_PREFERRED) {
4429            Log.v(TAG, "setLastChosenActivity intent=" + intent
4430                + " resolvedType=" + resolvedType
4431                + " flags=" + flags
4432                + " filter=" + filter
4433                + " match=" + match
4434                + " activity=" + activity);
4435            filter.dump(new PrintStreamPrinter(System.out), "    ");
4436        }
4437        intent.setComponent(null);
4438        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4439        // Find any earlier preferred or last chosen entries and nuke them
4440        findPreferredActivity(intent, resolvedType,
4441                flags, query, 0, false, true, false, userId);
4442        // Add the new activity as the last chosen for this filter
4443        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4444                "Setting last chosen");
4445    }
4446
4447    @Override
4448    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4449        final int userId = UserHandle.getCallingUserId();
4450        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4451        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4452        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4453                false, false, false, userId);
4454    }
4455
4456
4457    private boolean isEphemeralAllowed(
4458            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4459        // Short circuit and return early if possible.
4460        final int callingUser = UserHandle.getCallingUserId();
4461        if (callingUser != UserHandle.USER_SYSTEM) {
4462            return false;
4463        }
4464        if (mEphemeralResolverConnection == null) {
4465            return false;
4466        }
4467        if (intent.getComponent() != null) {
4468            return false;
4469        }
4470        if (intent.getPackage() != null) {
4471            return false;
4472        }
4473        final boolean isWebUri = hasWebURI(intent);
4474        if (!isWebUri) {
4475            return false;
4476        }
4477        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4478        synchronized (mPackages) {
4479            final int count = resolvedActivites.size();
4480            for (int n = 0; n < count; n++) {
4481                ResolveInfo info = resolvedActivites.get(n);
4482                String packageName = info.activityInfo.packageName;
4483                PackageSetting ps = mSettings.mPackages.get(packageName);
4484                if (ps != null) {
4485                    // Try to get the status from User settings first
4486                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4487                    int status = (int) (packedStatus >> 32);
4488                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4489                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4490                        if (DEBUG_EPHEMERAL) {
4491                            Slog.v(TAG, "DENY ephemeral apps;"
4492                                + " pkg: " + packageName + ", status: " + status);
4493                        }
4494                        return false;
4495                    }
4496                }
4497            }
4498        }
4499        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4500        return true;
4501    }
4502
4503    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4504            int userId) {
4505        MessageDigest digest = null;
4506        try {
4507            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4508        } catch (NoSuchAlgorithmException e) {
4509            // If we can't create a digest, ignore ephemeral apps.
4510            return null;
4511        }
4512
4513        final byte[] hostBytes = intent.getData().getHost().getBytes();
4514        final byte[] digestBytes = digest.digest(hostBytes);
4515        int shaPrefix =
4516                digestBytes[0] << 24
4517                | digestBytes[1] << 16
4518                | digestBytes[2] << 8
4519                | digestBytes[3] << 0;
4520        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4521                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4522        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4523            // No hash prefix match; there are no ephemeral apps for this domain.
4524            return null;
4525        }
4526        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4527            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4528            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4529                continue;
4530            }
4531            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4532            // No filters; this should never happen.
4533            if (filters.isEmpty()) {
4534                continue;
4535            }
4536            // We have a domain match; resolve the filters to see if anything matches.
4537            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4538            for (int j = filters.size() - 1; j >= 0; --j) {
4539                final EphemeralResolveIntentInfo intentInfo =
4540                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4541                ephemeralResolver.addFilter(intentInfo);
4542            }
4543            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4544                    intent, resolvedType, false /*defaultOnly*/, userId);
4545            if (!matchedResolveInfoList.isEmpty()) {
4546                return matchedResolveInfoList.get(0);
4547            }
4548        }
4549        // Hash or filter mis-match; no ephemeral apps for this domain.
4550        return null;
4551    }
4552
4553    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4554            int flags, List<ResolveInfo> query, int userId) {
4555        if (query != null) {
4556            final int N = query.size();
4557            if (N == 1) {
4558                return query.get(0);
4559            } else if (N > 1) {
4560                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4561                // If there is more than one activity with the same priority,
4562                // then let the user decide between them.
4563                ResolveInfo r0 = query.get(0);
4564                ResolveInfo r1 = query.get(1);
4565                if (DEBUG_INTENT_MATCHING || debug) {
4566                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4567                            + r1.activityInfo.name + "=" + r1.priority);
4568                }
4569                // If the first activity has a higher priority, or a different
4570                // default, then it is always desirable to pick it.
4571                if (r0.priority != r1.priority
4572                        || r0.preferredOrder != r1.preferredOrder
4573                        || r0.isDefault != r1.isDefault) {
4574                    return query.get(0);
4575                }
4576                // If we have saved a preference for a preferred activity for
4577                // this Intent, use that.
4578                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4579                        flags, query, r0.priority, true, false, debug, userId);
4580                if (ri != null) {
4581                    return ri;
4582                }
4583                ri = new ResolveInfo(mResolveInfo);
4584                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4585                ri.activityInfo.applicationInfo = new ApplicationInfo(
4586                        ri.activityInfo.applicationInfo);
4587                if (userId != 0) {
4588                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4589                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4590                }
4591                // Make sure that the resolver is displayable in car mode
4592                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4593                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4594                return ri;
4595            }
4596        }
4597        return null;
4598    }
4599
4600    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4601            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4602        final int N = query.size();
4603        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4604                .get(userId);
4605        // Get the list of persistent preferred activities that handle the intent
4606        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4607        List<PersistentPreferredActivity> pprefs = ppir != null
4608                ? ppir.queryIntent(intent, resolvedType,
4609                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4610                : null;
4611        if (pprefs != null && pprefs.size() > 0) {
4612            final int M = pprefs.size();
4613            for (int i=0; i<M; i++) {
4614                final PersistentPreferredActivity ppa = pprefs.get(i);
4615                if (DEBUG_PREFERRED || debug) {
4616                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4617                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4618                            + "\n  component=" + ppa.mComponent);
4619                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4620                }
4621                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4622                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4623                if (DEBUG_PREFERRED || debug) {
4624                    Slog.v(TAG, "Found persistent preferred activity:");
4625                    if (ai != null) {
4626                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4627                    } else {
4628                        Slog.v(TAG, "  null");
4629                    }
4630                }
4631                if (ai == null) {
4632                    // This previously registered persistent preferred activity
4633                    // component is no longer known. Ignore it and do NOT remove it.
4634                    continue;
4635                }
4636                for (int j=0; j<N; j++) {
4637                    final ResolveInfo ri = query.get(j);
4638                    if (!ri.activityInfo.applicationInfo.packageName
4639                            .equals(ai.applicationInfo.packageName)) {
4640                        continue;
4641                    }
4642                    if (!ri.activityInfo.name.equals(ai.name)) {
4643                        continue;
4644                    }
4645                    //  Found a persistent preference that can handle the intent.
4646                    if (DEBUG_PREFERRED || debug) {
4647                        Slog.v(TAG, "Returning persistent preferred activity: " +
4648                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4649                    }
4650                    return ri;
4651                }
4652            }
4653        }
4654        return null;
4655    }
4656
4657    // TODO: handle preferred activities missing while user has amnesia
4658    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4659            List<ResolveInfo> query, int priority, boolean always,
4660            boolean removeMatches, boolean debug, int userId) {
4661        if (!sUserManager.exists(userId)) return null;
4662        flags = augmentFlagsForUser(flags, userId);
4663        // writer
4664        synchronized (mPackages) {
4665            if (intent.getSelector() != null) {
4666                intent = intent.getSelector();
4667            }
4668            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4669
4670            // Try to find a matching persistent preferred activity.
4671            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4672                    debug, userId);
4673
4674            // If a persistent preferred activity matched, use it.
4675            if (pri != null) {
4676                return pri;
4677            }
4678
4679            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4680            // Get the list of preferred activities that handle the intent
4681            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4682            List<PreferredActivity> prefs = pir != null
4683                    ? pir.queryIntent(intent, resolvedType,
4684                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4685                    : null;
4686            if (prefs != null && prefs.size() > 0) {
4687                boolean changed = false;
4688                try {
4689                    // First figure out how good the original match set is.
4690                    // We will only allow preferred activities that came
4691                    // from the same match quality.
4692                    int match = 0;
4693
4694                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4695
4696                    final int N = query.size();
4697                    for (int j=0; j<N; j++) {
4698                        final ResolveInfo ri = query.get(j);
4699                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4700                                + ": 0x" + Integer.toHexString(match));
4701                        if (ri.match > match) {
4702                            match = ri.match;
4703                        }
4704                    }
4705
4706                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4707                            + Integer.toHexString(match));
4708
4709                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4710                    final int M = prefs.size();
4711                    for (int i=0; i<M; i++) {
4712                        final PreferredActivity pa = prefs.get(i);
4713                        if (DEBUG_PREFERRED || debug) {
4714                            Slog.v(TAG, "Checking PreferredActivity ds="
4715                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4716                                    + "\n  component=" + pa.mPref.mComponent);
4717                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4718                        }
4719                        if (pa.mPref.mMatch != match) {
4720                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4721                                    + Integer.toHexString(pa.mPref.mMatch));
4722                            continue;
4723                        }
4724                        // If it's not an "always" type preferred activity and that's what we're
4725                        // looking for, skip it.
4726                        if (always && !pa.mPref.mAlways) {
4727                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4728                            continue;
4729                        }
4730                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4731                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4732                        if (DEBUG_PREFERRED || debug) {
4733                            Slog.v(TAG, "Found preferred activity:");
4734                            if (ai != null) {
4735                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4736                            } else {
4737                                Slog.v(TAG, "  null");
4738                            }
4739                        }
4740                        if (ai == null) {
4741                            // This previously registered preferred activity
4742                            // component is no longer known.  Most likely an update
4743                            // to the app was installed and in the new version this
4744                            // component no longer exists.  Clean it up by removing
4745                            // it from the preferred activities list, and skip it.
4746                            Slog.w(TAG, "Removing dangling preferred activity: "
4747                                    + pa.mPref.mComponent);
4748                            pir.removeFilter(pa);
4749                            changed = true;
4750                            continue;
4751                        }
4752                        for (int j=0; j<N; j++) {
4753                            final ResolveInfo ri = query.get(j);
4754                            if (!ri.activityInfo.applicationInfo.packageName
4755                                    .equals(ai.applicationInfo.packageName)) {
4756                                continue;
4757                            }
4758                            if (!ri.activityInfo.name.equals(ai.name)) {
4759                                continue;
4760                            }
4761
4762                            if (removeMatches) {
4763                                pir.removeFilter(pa);
4764                                changed = true;
4765                                if (DEBUG_PREFERRED) {
4766                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4767                                }
4768                                break;
4769                            }
4770
4771                            // Okay we found a previously set preferred or last chosen app.
4772                            // If the result set is different from when this
4773                            // was created, we need to clear it and re-ask the
4774                            // user their preference, if we're looking for an "always" type entry.
4775                            if (always && !pa.mPref.sameSet(query)) {
4776                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4777                                        + intent + " type " + resolvedType);
4778                                if (DEBUG_PREFERRED) {
4779                                    Slog.v(TAG, "Removing preferred activity since set changed "
4780                                            + pa.mPref.mComponent);
4781                                }
4782                                pir.removeFilter(pa);
4783                                // Re-add the filter as a "last chosen" entry (!always)
4784                                PreferredActivity lastChosen = new PreferredActivity(
4785                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4786                                pir.addFilter(lastChosen);
4787                                changed = true;
4788                                return null;
4789                            }
4790
4791                            // Yay! Either the set matched or we're looking for the last chosen
4792                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4793                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4794                            return ri;
4795                        }
4796                    }
4797                } finally {
4798                    if (changed) {
4799                        if (DEBUG_PREFERRED) {
4800                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4801                        }
4802                        scheduleWritePackageRestrictionsLocked(userId);
4803                    }
4804                }
4805            }
4806        }
4807        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4808        return null;
4809    }
4810
4811    /*
4812     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4813     */
4814    @Override
4815    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4816            int targetUserId) {
4817        mContext.enforceCallingOrSelfPermission(
4818                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4819        List<CrossProfileIntentFilter> matches =
4820                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4821        if (matches != null) {
4822            int size = matches.size();
4823            for (int i = 0; i < size; i++) {
4824                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4825            }
4826        }
4827        if (hasWebURI(intent)) {
4828            // cross-profile app linking works only towards the parent.
4829            final UserInfo parent = getProfileParent(sourceUserId);
4830            synchronized(mPackages) {
4831                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4832                        intent, resolvedType, 0, sourceUserId, parent.id);
4833                return xpDomainInfo != null;
4834            }
4835        }
4836        return false;
4837    }
4838
4839    private UserInfo getProfileParent(int userId) {
4840        final long identity = Binder.clearCallingIdentity();
4841        try {
4842            return sUserManager.getProfileParent(userId);
4843        } finally {
4844            Binder.restoreCallingIdentity(identity);
4845        }
4846    }
4847
4848    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4849            String resolvedType, int userId) {
4850        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4851        if (resolver != null) {
4852            return resolver.queryIntent(intent, resolvedType, false, userId);
4853        }
4854        return null;
4855    }
4856
4857    @Override
4858    public List<ResolveInfo> queryIntentActivities(Intent intent,
4859            String resolvedType, int flags, int userId) {
4860        if (!sUserManager.exists(userId)) return Collections.emptyList();
4861        flags = augmentFlagsForUser(flags, userId);
4862        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4863        ComponentName comp = intent.getComponent();
4864        if (comp == null) {
4865            if (intent.getSelector() != null) {
4866                intent = intent.getSelector();
4867                comp = intent.getComponent();
4868            }
4869        }
4870
4871        if (comp != null) {
4872            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4873            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4874            if (ai != null) {
4875                final ResolveInfo ri = new ResolveInfo();
4876                ri.activityInfo = ai;
4877                list.add(ri);
4878            }
4879            return list;
4880        }
4881
4882        // reader
4883        synchronized (mPackages) {
4884            final String pkgName = intent.getPackage();
4885            if (pkgName == null) {
4886                List<CrossProfileIntentFilter> matchingFilters =
4887                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4888                // Check for results that need to skip the current profile.
4889                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4890                        resolvedType, flags, userId);
4891                if (xpResolveInfo != null) {
4892                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4893                    result.add(xpResolveInfo);
4894                    return filterIfNotSystemUser(result, userId);
4895                }
4896
4897                // Check for results in the current profile.
4898                List<ResolveInfo> result = mActivities.queryIntent(
4899                        intent, resolvedType, flags, userId);
4900                result = filterIfNotSystemUser(result, userId);
4901
4902                // Check for cross profile results.
4903                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4904                xpResolveInfo = queryCrossProfileIntents(
4905                        matchingFilters, intent, resolvedType, flags, userId,
4906                        hasNonNegativePriorityResult);
4907                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4908                    boolean isVisibleToUser = filterIfNotSystemUser(
4909                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4910                    if (isVisibleToUser) {
4911                        result.add(xpResolveInfo);
4912                        Collections.sort(result, mResolvePrioritySorter);
4913                    }
4914                }
4915                if (hasWebURI(intent)) {
4916                    CrossProfileDomainInfo xpDomainInfo = null;
4917                    final UserInfo parent = getProfileParent(userId);
4918                    if (parent != null) {
4919                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4920                                flags, userId, parent.id);
4921                    }
4922                    if (xpDomainInfo != null) {
4923                        if (xpResolveInfo != null) {
4924                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4925                            // in the result.
4926                            result.remove(xpResolveInfo);
4927                        }
4928                        if (result.size() == 0) {
4929                            result.add(xpDomainInfo.resolveInfo);
4930                            return result;
4931                        }
4932                    } else if (result.size() <= 1) {
4933                        return result;
4934                    }
4935                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4936                            xpDomainInfo, userId);
4937                    Collections.sort(result, mResolvePrioritySorter);
4938                }
4939                return result;
4940            }
4941            final PackageParser.Package pkg = mPackages.get(pkgName);
4942            if (pkg != null) {
4943                return filterIfNotSystemUser(
4944                        mActivities.queryIntentForPackage(
4945                                intent, resolvedType, flags, pkg.activities, userId),
4946                        userId);
4947            }
4948            return new ArrayList<ResolveInfo>();
4949        }
4950    }
4951
4952    private static class CrossProfileDomainInfo {
4953        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4954        ResolveInfo resolveInfo;
4955        /* Best domain verification status of the activities found in the other profile */
4956        int bestDomainVerificationStatus;
4957    }
4958
4959    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4960            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4961        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4962                sourceUserId)) {
4963            return null;
4964        }
4965        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4966                resolvedType, flags, parentUserId);
4967
4968        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4969            return null;
4970        }
4971        CrossProfileDomainInfo result = null;
4972        int size = resultTargetUser.size();
4973        for (int i = 0; i < size; i++) {
4974            ResolveInfo riTargetUser = resultTargetUser.get(i);
4975            // Intent filter verification is only for filters that specify a host. So don't return
4976            // those that handle all web uris.
4977            if (riTargetUser.handleAllWebDataURI) {
4978                continue;
4979            }
4980            String packageName = riTargetUser.activityInfo.packageName;
4981            PackageSetting ps = mSettings.mPackages.get(packageName);
4982            if (ps == null) {
4983                continue;
4984            }
4985            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4986            int status = (int)(verificationState >> 32);
4987            if (result == null) {
4988                result = new CrossProfileDomainInfo();
4989                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4990                        sourceUserId, parentUserId);
4991                result.bestDomainVerificationStatus = status;
4992            } else {
4993                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4994                        result.bestDomainVerificationStatus);
4995            }
4996        }
4997        // Don't consider matches with status NEVER across profiles.
4998        if (result != null && result.bestDomainVerificationStatus
4999                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5000            return null;
5001        }
5002        return result;
5003    }
5004
5005    /**
5006     * Verification statuses are ordered from the worse to the best, except for
5007     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5008     */
5009    private int bestDomainVerificationStatus(int status1, int status2) {
5010        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5011            return status2;
5012        }
5013        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5014            return status1;
5015        }
5016        return (int) MathUtils.max(status1, status2);
5017    }
5018
5019    private boolean isUserEnabled(int userId) {
5020        long callingId = Binder.clearCallingIdentity();
5021        try {
5022            UserInfo userInfo = sUserManager.getUserInfo(userId);
5023            return userInfo != null && userInfo.isEnabled();
5024        } finally {
5025            Binder.restoreCallingIdentity(callingId);
5026        }
5027    }
5028
5029    /**
5030     * Filter out activities with systemUserOnly flag set, when current user is not System.
5031     *
5032     * @return filtered list
5033     */
5034    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5035        if (userId == UserHandle.USER_SYSTEM) {
5036            return resolveInfos;
5037        }
5038        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5039            ResolveInfo info = resolveInfos.get(i);
5040            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5041                resolveInfos.remove(i);
5042            }
5043        }
5044        return resolveInfos;
5045    }
5046
5047    /**
5048     * @param resolveInfos list of resolve infos in descending priority order
5049     * @return if the list contains a resolve info with non-negative priority
5050     */
5051    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5052        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5053    }
5054
5055    private static boolean hasWebURI(Intent intent) {
5056        if (intent.getData() == null) {
5057            return false;
5058        }
5059        final String scheme = intent.getScheme();
5060        if (TextUtils.isEmpty(scheme)) {
5061            return false;
5062        }
5063        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5064    }
5065
5066    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5067            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5068            int userId) {
5069        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5070
5071        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5072            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5073                    candidates.size());
5074        }
5075
5076        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5077        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5078        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5079        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5080        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5081        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5082
5083        synchronized (mPackages) {
5084            final int count = candidates.size();
5085            // First, try to use linked apps. Partition the candidates into four lists:
5086            // one for the final results, one for the "do not use ever", one for "undefined status"
5087            // and finally one for "browser app type".
5088            for (int n=0; n<count; n++) {
5089                ResolveInfo info = candidates.get(n);
5090                String packageName = info.activityInfo.packageName;
5091                PackageSetting ps = mSettings.mPackages.get(packageName);
5092                if (ps != null) {
5093                    // Add to the special match all list (Browser use case)
5094                    if (info.handleAllWebDataURI) {
5095                        matchAllList.add(info);
5096                        continue;
5097                    }
5098                    // Try to get the status from User settings first
5099                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5100                    int status = (int)(packedStatus >> 32);
5101                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5102                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5103                        if (DEBUG_DOMAIN_VERIFICATION) {
5104                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5105                                    + " : linkgen=" + linkGeneration);
5106                        }
5107                        // Use link-enabled generation as preferredOrder, i.e.
5108                        // prefer newly-enabled over earlier-enabled.
5109                        info.preferredOrder = linkGeneration;
5110                        alwaysList.add(info);
5111                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5112                        if (DEBUG_DOMAIN_VERIFICATION) {
5113                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5114                        }
5115                        neverList.add(info);
5116                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5117                        if (DEBUG_DOMAIN_VERIFICATION) {
5118                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5119                        }
5120                        alwaysAskList.add(info);
5121                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5122                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5123                        if (DEBUG_DOMAIN_VERIFICATION) {
5124                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5125                        }
5126                        undefinedList.add(info);
5127                    }
5128                }
5129            }
5130
5131            // We'll want to include browser possibilities in a few cases
5132            boolean includeBrowser = false;
5133
5134            // First try to add the "always" resolution(s) for the current user, if any
5135            if (alwaysList.size() > 0) {
5136                result.addAll(alwaysList);
5137            } else {
5138                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5139                result.addAll(undefinedList);
5140                // Maybe add one for the other profile.
5141                if (xpDomainInfo != null && (
5142                        xpDomainInfo.bestDomainVerificationStatus
5143                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5144                    result.add(xpDomainInfo.resolveInfo);
5145                }
5146                includeBrowser = true;
5147            }
5148
5149            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5150            // If there were 'always' entries their preferred order has been set, so we also
5151            // back that off to make the alternatives equivalent
5152            if (alwaysAskList.size() > 0) {
5153                for (ResolveInfo i : result) {
5154                    i.preferredOrder = 0;
5155                }
5156                result.addAll(alwaysAskList);
5157                includeBrowser = true;
5158            }
5159
5160            if (includeBrowser) {
5161                // Also add browsers (all of them or only the default one)
5162                if (DEBUG_DOMAIN_VERIFICATION) {
5163                    Slog.v(TAG, "   ...including browsers in candidate set");
5164                }
5165                if ((matchFlags & MATCH_ALL) != 0) {
5166                    result.addAll(matchAllList);
5167                } else {
5168                    // Browser/generic handling case.  If there's a default browser, go straight
5169                    // to that (but only if there is no other higher-priority match).
5170                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5171                    int maxMatchPrio = 0;
5172                    ResolveInfo defaultBrowserMatch = null;
5173                    final int numCandidates = matchAllList.size();
5174                    for (int n = 0; n < numCandidates; n++) {
5175                        ResolveInfo info = matchAllList.get(n);
5176                        // track the highest overall match priority...
5177                        if (info.priority > maxMatchPrio) {
5178                            maxMatchPrio = info.priority;
5179                        }
5180                        // ...and the highest-priority default browser match
5181                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5182                            if (defaultBrowserMatch == null
5183                                    || (defaultBrowserMatch.priority < info.priority)) {
5184                                if (debug) {
5185                                    Slog.v(TAG, "Considering default browser match " + info);
5186                                }
5187                                defaultBrowserMatch = info;
5188                            }
5189                        }
5190                    }
5191                    if (defaultBrowserMatch != null
5192                            && defaultBrowserMatch.priority >= maxMatchPrio
5193                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5194                    {
5195                        if (debug) {
5196                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5197                        }
5198                        result.add(defaultBrowserMatch);
5199                    } else {
5200                        result.addAll(matchAllList);
5201                    }
5202                }
5203
5204                // If there is nothing selected, add all candidates and remove the ones that the user
5205                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5206                if (result.size() == 0) {
5207                    result.addAll(candidates);
5208                    result.removeAll(neverList);
5209                }
5210            }
5211        }
5212        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5213            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5214                    result.size());
5215            for (ResolveInfo info : result) {
5216                Slog.v(TAG, "  + " + info.activityInfo);
5217            }
5218        }
5219        return result;
5220    }
5221
5222    // Returns a packed value as a long:
5223    //
5224    // high 'int'-sized word: link status: undefined/ask/never/always.
5225    // low 'int'-sized word: relative priority among 'always' results.
5226    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5227        long result = ps.getDomainVerificationStatusForUser(userId);
5228        // if none available, get the master status
5229        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5230            if (ps.getIntentFilterVerificationInfo() != null) {
5231                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5232            }
5233        }
5234        return result;
5235    }
5236
5237    private ResolveInfo querySkipCurrentProfileIntents(
5238            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5239            int flags, int sourceUserId) {
5240        if (matchingFilters != null) {
5241            int size = matchingFilters.size();
5242            for (int i = 0; i < size; i ++) {
5243                CrossProfileIntentFilter filter = matchingFilters.get(i);
5244                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5245                    // Checking if there are activities in the target user that can handle the
5246                    // intent.
5247                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5248                            resolvedType, flags, sourceUserId);
5249                    if (resolveInfo != null) {
5250                        return resolveInfo;
5251                    }
5252                }
5253            }
5254        }
5255        return null;
5256    }
5257
5258    // Return matching ResolveInfo in target user if any.
5259    private ResolveInfo queryCrossProfileIntents(
5260            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5261            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5262        if (matchingFilters != null) {
5263            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5264            // match the same intent. For performance reasons, it is better not to
5265            // run queryIntent twice for the same userId
5266            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5267            int size = matchingFilters.size();
5268            for (int i = 0; i < size; i++) {
5269                CrossProfileIntentFilter filter = matchingFilters.get(i);
5270                int targetUserId = filter.getTargetUserId();
5271                boolean skipCurrentProfile =
5272                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5273                boolean skipCurrentProfileIfNoMatchFound =
5274                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5275                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5276                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5277                    // Checking if there are activities in the target user that can handle the
5278                    // intent.
5279                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5280                            resolvedType, flags, sourceUserId);
5281                    if (resolveInfo != null) return resolveInfo;
5282                    alreadyTriedUserIds.put(targetUserId, true);
5283                }
5284            }
5285        }
5286        return null;
5287    }
5288
5289    /**
5290     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5291     * will forward the intent to the filter's target user.
5292     * Otherwise, returns null.
5293     */
5294    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5295            String resolvedType, int flags, int sourceUserId) {
5296        int targetUserId = filter.getTargetUserId();
5297        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5298                resolvedType, flags, targetUserId);
5299        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5300                && isUserEnabled(targetUserId)) {
5301            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5302        }
5303        return null;
5304    }
5305
5306    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5307            int sourceUserId, int targetUserId) {
5308        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5309        long ident = Binder.clearCallingIdentity();
5310        boolean targetIsProfile;
5311        try {
5312            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5313        } finally {
5314            Binder.restoreCallingIdentity(ident);
5315        }
5316        String className;
5317        if (targetIsProfile) {
5318            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5319        } else {
5320            className = FORWARD_INTENT_TO_PARENT;
5321        }
5322        ComponentName forwardingActivityComponentName = new ComponentName(
5323                mAndroidApplication.packageName, className);
5324        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5325                sourceUserId);
5326        if (!targetIsProfile) {
5327            forwardingActivityInfo.showUserIcon = targetUserId;
5328            forwardingResolveInfo.noResourceId = true;
5329        }
5330        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5331        forwardingResolveInfo.priority = 0;
5332        forwardingResolveInfo.preferredOrder = 0;
5333        forwardingResolveInfo.match = 0;
5334        forwardingResolveInfo.isDefault = true;
5335        forwardingResolveInfo.filter = filter;
5336        forwardingResolveInfo.targetUserId = targetUserId;
5337        return forwardingResolveInfo;
5338    }
5339
5340    @Override
5341    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5342            Intent[] specifics, String[] specificTypes, Intent intent,
5343            String resolvedType, int flags, int userId) {
5344        if (!sUserManager.exists(userId)) return Collections.emptyList();
5345        flags = augmentFlagsForUser(flags, userId);
5346        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5347                false, "query intent activity options");
5348        final String resultsAction = intent.getAction();
5349
5350        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5351                | PackageManager.GET_RESOLVED_FILTER, userId);
5352
5353        if (DEBUG_INTENT_MATCHING) {
5354            Log.v(TAG, "Query " + intent + ": " + results);
5355        }
5356
5357        int specificsPos = 0;
5358        int N;
5359
5360        // todo: note that the algorithm used here is O(N^2).  This
5361        // isn't a problem in our current environment, but if we start running
5362        // into situations where we have more than 5 or 10 matches then this
5363        // should probably be changed to something smarter...
5364
5365        // First we go through and resolve each of the specific items
5366        // that were supplied, taking care of removing any corresponding
5367        // duplicate items in the generic resolve list.
5368        if (specifics != null) {
5369            for (int i=0; i<specifics.length; i++) {
5370                final Intent sintent = specifics[i];
5371                if (sintent == null) {
5372                    continue;
5373                }
5374
5375                if (DEBUG_INTENT_MATCHING) {
5376                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5377                }
5378
5379                String action = sintent.getAction();
5380                if (resultsAction != null && resultsAction.equals(action)) {
5381                    // If this action was explicitly requested, then don't
5382                    // remove things that have it.
5383                    action = null;
5384                }
5385
5386                ResolveInfo ri = null;
5387                ActivityInfo ai = null;
5388
5389                ComponentName comp = sintent.getComponent();
5390                if (comp == null) {
5391                    ri = resolveIntent(
5392                        sintent,
5393                        specificTypes != null ? specificTypes[i] : null,
5394                            flags, userId);
5395                    if (ri == null) {
5396                        continue;
5397                    }
5398                    if (ri == mResolveInfo) {
5399                        // ACK!  Must do something better with this.
5400                    }
5401                    ai = ri.activityInfo;
5402                    comp = new ComponentName(ai.applicationInfo.packageName,
5403                            ai.name);
5404                } else {
5405                    ai = getActivityInfo(comp, flags, userId);
5406                    if (ai == null) {
5407                        continue;
5408                    }
5409                }
5410
5411                // Look for any generic query activities that are duplicates
5412                // of this specific one, and remove them from the results.
5413                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5414                N = results.size();
5415                int j;
5416                for (j=specificsPos; j<N; j++) {
5417                    ResolveInfo sri = results.get(j);
5418                    if ((sri.activityInfo.name.equals(comp.getClassName())
5419                            && sri.activityInfo.applicationInfo.packageName.equals(
5420                                    comp.getPackageName()))
5421                        || (action != null && sri.filter.matchAction(action))) {
5422                        results.remove(j);
5423                        if (DEBUG_INTENT_MATCHING) Log.v(
5424                            TAG, "Removing duplicate item from " + j
5425                            + " due to specific " + specificsPos);
5426                        if (ri == null) {
5427                            ri = sri;
5428                        }
5429                        j--;
5430                        N--;
5431                    }
5432                }
5433
5434                // Add this specific item to its proper place.
5435                if (ri == null) {
5436                    ri = new ResolveInfo();
5437                    ri.activityInfo = ai;
5438                }
5439                results.add(specificsPos, ri);
5440                ri.specificIndex = i;
5441                specificsPos++;
5442            }
5443        }
5444
5445        // Now we go through the remaining generic results and remove any
5446        // duplicate actions that are found here.
5447        N = results.size();
5448        for (int i=specificsPos; i<N-1; i++) {
5449            final ResolveInfo rii = results.get(i);
5450            if (rii.filter == null) {
5451                continue;
5452            }
5453
5454            // Iterate over all of the actions of this result's intent
5455            // filter...  typically this should be just one.
5456            final Iterator<String> it = rii.filter.actionsIterator();
5457            if (it == null) {
5458                continue;
5459            }
5460            while (it.hasNext()) {
5461                final String action = it.next();
5462                if (resultsAction != null && resultsAction.equals(action)) {
5463                    // If this action was explicitly requested, then don't
5464                    // remove things that have it.
5465                    continue;
5466                }
5467                for (int j=i+1; j<N; j++) {
5468                    final ResolveInfo rij = results.get(j);
5469                    if (rij.filter != null && rij.filter.hasAction(action)) {
5470                        results.remove(j);
5471                        if (DEBUG_INTENT_MATCHING) Log.v(
5472                            TAG, "Removing duplicate item from " + j
5473                            + " due to action " + action + " at " + i);
5474                        j--;
5475                        N--;
5476                    }
5477                }
5478            }
5479
5480            // If the caller didn't request filter information, drop it now
5481            // so we don't have to marshall/unmarshall it.
5482            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5483                rii.filter = null;
5484            }
5485        }
5486
5487        // Filter out the caller activity if so requested.
5488        if (caller != null) {
5489            N = results.size();
5490            for (int i=0; i<N; i++) {
5491                ActivityInfo ainfo = results.get(i).activityInfo;
5492                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5493                        && caller.getClassName().equals(ainfo.name)) {
5494                    results.remove(i);
5495                    break;
5496                }
5497            }
5498        }
5499
5500        // If the caller didn't request filter information,
5501        // drop them now so we don't have to
5502        // marshall/unmarshall it.
5503        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5504            N = results.size();
5505            for (int i=0; i<N; i++) {
5506                results.get(i).filter = null;
5507            }
5508        }
5509
5510        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5511        return results;
5512    }
5513
5514    @Override
5515    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5516            int userId) {
5517        if (!sUserManager.exists(userId)) return Collections.emptyList();
5518        flags = augmentFlagsForUser(flags, userId);
5519        ComponentName comp = intent.getComponent();
5520        if (comp == null) {
5521            if (intent.getSelector() != null) {
5522                intent = intent.getSelector();
5523                comp = intent.getComponent();
5524            }
5525        }
5526        if (comp != null) {
5527            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5528            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5529            if (ai != null) {
5530                ResolveInfo ri = new ResolveInfo();
5531                ri.activityInfo = ai;
5532                list.add(ri);
5533            }
5534            return list;
5535        }
5536
5537        // reader
5538        synchronized (mPackages) {
5539            String pkgName = intent.getPackage();
5540            if (pkgName == null) {
5541                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5542            }
5543            final PackageParser.Package pkg = mPackages.get(pkgName);
5544            if (pkg != null) {
5545                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5546                        userId);
5547            }
5548            return null;
5549        }
5550    }
5551
5552    @Override
5553    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5554        if (!sUserManager.exists(userId)) return null;
5555        flags = augmentFlagsForUser(flags, userId);
5556        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5557        if (query != null) {
5558            if (query.size() >= 1) {
5559                // If there is more than one service with the same priority,
5560                // just arbitrarily pick the first one.
5561                return query.get(0);
5562            }
5563        }
5564        return null;
5565    }
5566
5567    @Override
5568    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5569            int userId) {
5570        if (!sUserManager.exists(userId)) return Collections.emptyList();
5571        flags = augmentFlagsForUser(flags, userId);
5572        ComponentName comp = intent.getComponent();
5573        if (comp == null) {
5574            if (intent.getSelector() != null) {
5575                intent = intent.getSelector();
5576                comp = intent.getComponent();
5577            }
5578        }
5579        if (comp != null) {
5580            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5581            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5582            if (si != null) {
5583                final ResolveInfo ri = new ResolveInfo();
5584                ri.serviceInfo = si;
5585                list.add(ri);
5586            }
5587            return list;
5588        }
5589
5590        // reader
5591        synchronized (mPackages) {
5592            String pkgName = intent.getPackage();
5593            if (pkgName == null) {
5594                return mServices.queryIntent(intent, resolvedType, flags, userId);
5595            }
5596            final PackageParser.Package pkg = mPackages.get(pkgName);
5597            if (pkg != null) {
5598                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5599                        userId);
5600            }
5601            return null;
5602        }
5603    }
5604
5605    @Override
5606    public List<ResolveInfo> queryIntentContentProviders(
5607            Intent intent, String resolvedType, int flags, int userId) {
5608        if (!sUserManager.exists(userId)) return Collections.emptyList();
5609        flags = augmentFlagsForUser(flags, userId);
5610        ComponentName comp = intent.getComponent();
5611        if (comp == null) {
5612            if (intent.getSelector() != null) {
5613                intent = intent.getSelector();
5614                comp = intent.getComponent();
5615            }
5616        }
5617        if (comp != null) {
5618            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5619            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5620            if (pi != null) {
5621                final ResolveInfo ri = new ResolveInfo();
5622                ri.providerInfo = pi;
5623                list.add(ri);
5624            }
5625            return list;
5626        }
5627
5628        // reader
5629        synchronized (mPackages) {
5630            String pkgName = intent.getPackage();
5631            if (pkgName == null) {
5632                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5633            }
5634            final PackageParser.Package pkg = mPackages.get(pkgName);
5635            if (pkg != null) {
5636                return mProviders.queryIntentForPackage(
5637                        intent, resolvedType, flags, pkg.providers, userId);
5638            }
5639            return null;
5640        }
5641    }
5642
5643    @Override
5644    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5645        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5646
5647        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5648
5649        // writer
5650        synchronized (mPackages) {
5651            ArrayList<PackageInfo> list;
5652            if (listUninstalled) {
5653                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5654                for (PackageSetting ps : mSettings.mPackages.values()) {
5655                    PackageInfo pi;
5656                    if (ps.pkg != null) {
5657                        pi = generatePackageInfo(ps.pkg, flags, userId);
5658                    } else {
5659                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5660                    }
5661                    if (pi != null) {
5662                        list.add(pi);
5663                    }
5664                }
5665            } else {
5666                list = new ArrayList<PackageInfo>(mPackages.size());
5667                for (PackageParser.Package p : mPackages.values()) {
5668                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5669                    if (pi != null) {
5670                        list.add(pi);
5671                    }
5672                }
5673            }
5674
5675            return new ParceledListSlice<PackageInfo>(list);
5676        }
5677    }
5678
5679    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5680            String[] permissions, boolean[] tmp, int flags, int userId) {
5681        int numMatch = 0;
5682        final PermissionsState permissionsState = ps.getPermissionsState();
5683        for (int i=0; i<permissions.length; i++) {
5684            final String permission = permissions[i];
5685            if (permissionsState.hasPermission(permission, userId)) {
5686                tmp[i] = true;
5687                numMatch++;
5688            } else {
5689                tmp[i] = false;
5690            }
5691        }
5692        if (numMatch == 0) {
5693            return;
5694        }
5695        PackageInfo pi;
5696        if (ps.pkg != null) {
5697            pi = generatePackageInfo(ps.pkg, flags, userId);
5698        } else {
5699            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5700        }
5701        // The above might return null in cases of uninstalled apps or install-state
5702        // skew across users/profiles.
5703        if (pi != null) {
5704            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5705                if (numMatch == permissions.length) {
5706                    pi.requestedPermissions = permissions;
5707                } else {
5708                    pi.requestedPermissions = new String[numMatch];
5709                    numMatch = 0;
5710                    for (int i=0; i<permissions.length; i++) {
5711                        if (tmp[i]) {
5712                            pi.requestedPermissions[numMatch] = permissions[i];
5713                            numMatch++;
5714                        }
5715                    }
5716                }
5717            }
5718            list.add(pi);
5719        }
5720    }
5721
5722    @Override
5723    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5724            String[] permissions, int flags, int userId) {
5725        if (!sUserManager.exists(userId)) return null;
5726        flags = augmentFlagsForUser(flags, userId);
5727        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5728
5729        // writer
5730        synchronized (mPackages) {
5731            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5732            boolean[] tmpBools = new boolean[permissions.length];
5733            if (listUninstalled) {
5734                for (PackageSetting ps : mSettings.mPackages.values()) {
5735                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5736                }
5737            } else {
5738                for (PackageParser.Package pkg : mPackages.values()) {
5739                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5740                    if (ps != null) {
5741                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5742                                userId);
5743                    }
5744                }
5745            }
5746
5747            return new ParceledListSlice<PackageInfo>(list);
5748        }
5749    }
5750
5751    @Override
5752    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5753        if (!sUserManager.exists(userId)) return null;
5754        flags = augmentFlagsForUser(flags, userId);
5755        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5756
5757        // writer
5758        synchronized (mPackages) {
5759            ArrayList<ApplicationInfo> list;
5760            if (listUninstalled) {
5761                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5762                for (PackageSetting ps : mSettings.mPackages.values()) {
5763                    ApplicationInfo ai;
5764                    if (ps.pkg != null) {
5765                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5766                                ps.readUserState(userId), userId);
5767                    } else {
5768                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5769                    }
5770                    if (ai != null) {
5771                        list.add(ai);
5772                    }
5773                }
5774            } else {
5775                list = new ArrayList<ApplicationInfo>(mPackages.size());
5776                for (PackageParser.Package p : mPackages.values()) {
5777                    if (p.mExtras != null) {
5778                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5779                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5780                        if (ai != null) {
5781                            list.add(ai);
5782                        }
5783                    }
5784                }
5785            }
5786
5787            return new ParceledListSlice<ApplicationInfo>(list);
5788        }
5789    }
5790
5791    @Override
5792    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5793        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5794                "getEphemeralApplications");
5795        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5796                "getEphemeralApplications");
5797        synchronized (mPackages) {
5798            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5799                    .getEphemeralApplicationsLPw(userId);
5800            if (ephemeralApps != null) {
5801                return new ParceledListSlice<>(ephemeralApps);
5802            }
5803        }
5804        return null;
5805    }
5806
5807    @Override
5808    public boolean isEphemeralApplication(String packageName, int userId) {
5809        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5810                "isEphemeral");
5811        if (!isCallerSameApp(packageName)) {
5812            return false;
5813        }
5814        synchronized (mPackages) {
5815            PackageParser.Package pkg = mPackages.get(packageName);
5816            if (pkg != null) {
5817                return pkg.applicationInfo.isEphemeralApp();
5818            }
5819        }
5820        return false;
5821    }
5822
5823    @Override
5824    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5825        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5826                "getCookie");
5827        if (!isCallerSameApp(packageName)) {
5828            return null;
5829        }
5830        synchronized (mPackages) {
5831            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5832                    packageName, userId);
5833        }
5834    }
5835
5836    @Override
5837    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5838        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5839                "setCookie");
5840        if (!isCallerSameApp(packageName)) {
5841            return false;
5842        }
5843        synchronized (mPackages) {
5844            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5845                    packageName, cookie, userId);
5846        }
5847    }
5848
5849    @Override
5850    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5851        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5852                "getEphemeralApplicationIcon");
5853        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5854                "getEphemeralApplicationIcon");
5855        synchronized (mPackages) {
5856            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5857                    packageName, userId);
5858        }
5859    }
5860
5861    private boolean isCallerSameApp(String packageName) {
5862        PackageParser.Package pkg = mPackages.get(packageName);
5863        return pkg != null
5864                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5865    }
5866
5867    public List<ApplicationInfo> getPersistentApplications(int flags) {
5868        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5869
5870        // reader
5871        synchronized (mPackages) {
5872            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5873            final int userId = UserHandle.getCallingUserId();
5874            while (i.hasNext()) {
5875                final PackageParser.Package p = i.next();
5876                if (p.applicationInfo != null
5877                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5878                        && (!mSafeMode || isSystemApp(p))) {
5879                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5880                    if (ps != null) {
5881                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5882                                ps.readUserState(userId), userId);
5883                        if (ai != null) {
5884                            finalList.add(ai);
5885                        }
5886                    }
5887                }
5888            }
5889        }
5890
5891        return finalList;
5892    }
5893
5894    @Override
5895    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5896        if (!sUserManager.exists(userId)) return null;
5897        flags = augmentFlagsForUser(flags, userId);
5898        // reader
5899        synchronized (mPackages) {
5900            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5901            PackageSetting ps = provider != null
5902                    ? mSettings.mPackages.get(provider.owner.packageName)
5903                    : null;
5904            return ps != null
5905                    && mSettings.isEnabledAndVisibleLPr(provider.info, flags, userId)
5906                    && (!mSafeMode || (provider.info.applicationInfo.flags
5907                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5908                    ? PackageParser.generateProviderInfo(provider, flags,
5909                            ps.readUserState(userId), userId)
5910                    : null;
5911        }
5912    }
5913
5914    /**
5915     * @deprecated
5916     */
5917    @Deprecated
5918    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5919        // reader
5920        synchronized (mPackages) {
5921            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5922                    .entrySet().iterator();
5923            final int userId = UserHandle.getCallingUserId();
5924            while (i.hasNext()) {
5925                Map.Entry<String, PackageParser.Provider> entry = i.next();
5926                PackageParser.Provider p = entry.getValue();
5927                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5928
5929                if (ps != null && p.syncable
5930                        && (!mSafeMode || (p.info.applicationInfo.flags
5931                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5932                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5933                            ps.readUserState(userId), userId);
5934                    if (info != null) {
5935                        outNames.add(entry.getKey());
5936                        outInfo.add(info);
5937                    }
5938                }
5939            }
5940        }
5941    }
5942
5943    @Override
5944    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5945            int uid, int flags) {
5946        final int userId = processName != null ? UserHandle.getUserId(uid)
5947                : UserHandle.getCallingUserId();
5948        if (!sUserManager.exists(userId)) return null;
5949        flags = augmentFlagsForUser(flags, userId);
5950
5951        ArrayList<ProviderInfo> finalList = null;
5952        // reader
5953        synchronized (mPackages) {
5954            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5955            while (i.hasNext()) {
5956                final PackageParser.Provider p = i.next();
5957                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5958                if (ps != null && p.info.authority != null
5959                        && (processName == null
5960                                || (p.info.processName.equals(processName)
5961                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5962                        && mSettings.isEnabledAndVisibleLPr(p.info, flags, userId)
5963                        && (!mSafeMode
5964                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5965                    if (finalList == null) {
5966                        finalList = new ArrayList<ProviderInfo>(3);
5967                    }
5968                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5969                            ps.readUserState(userId), userId);
5970                    if (info != null) {
5971                        finalList.add(info);
5972                    }
5973                }
5974            }
5975        }
5976
5977        if (finalList != null) {
5978            Collections.sort(finalList, mProviderInitOrderSorter);
5979            return new ParceledListSlice<ProviderInfo>(finalList);
5980        }
5981
5982        return null;
5983    }
5984
5985    @Override
5986    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5987            int flags) {
5988        // reader
5989        synchronized (mPackages) {
5990            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5991            return PackageParser.generateInstrumentationInfo(i, flags);
5992        }
5993    }
5994
5995    @Override
5996    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5997            int flags) {
5998        ArrayList<InstrumentationInfo> finalList =
5999            new ArrayList<InstrumentationInfo>();
6000
6001        // reader
6002        synchronized (mPackages) {
6003            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6004            while (i.hasNext()) {
6005                final PackageParser.Instrumentation p = i.next();
6006                if (targetPackage == null
6007                        || targetPackage.equals(p.info.targetPackage)) {
6008                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6009                            flags);
6010                    if (ii != null) {
6011                        finalList.add(ii);
6012                    }
6013                }
6014            }
6015        }
6016
6017        return finalList;
6018    }
6019
6020    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6021        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6022        if (overlays == null) {
6023            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6024            return;
6025        }
6026        for (PackageParser.Package opkg : overlays.values()) {
6027            // Not much to do if idmap fails: we already logged the error
6028            // and we certainly don't want to abort installation of pkg simply
6029            // because an overlay didn't fit properly. For these reasons,
6030            // ignore the return value of createIdmapForPackagePairLI.
6031            createIdmapForPackagePairLI(pkg, opkg);
6032        }
6033    }
6034
6035    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6036            PackageParser.Package opkg) {
6037        if (!opkg.mTrustedOverlay) {
6038            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6039                    opkg.baseCodePath + ": overlay not trusted");
6040            return false;
6041        }
6042        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6043        if (overlaySet == null) {
6044            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6045                    opkg.baseCodePath + " but target package has no known overlays");
6046            return false;
6047        }
6048        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6049        // TODO: generate idmap for split APKs
6050        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6051            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6052                    + opkg.baseCodePath);
6053            return false;
6054        }
6055        PackageParser.Package[] overlayArray =
6056            overlaySet.values().toArray(new PackageParser.Package[0]);
6057        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6058            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6059                return p1.mOverlayPriority - p2.mOverlayPriority;
6060            }
6061        };
6062        Arrays.sort(overlayArray, cmp);
6063
6064        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6065        int i = 0;
6066        for (PackageParser.Package p : overlayArray) {
6067            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6068        }
6069        return true;
6070    }
6071
6072    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6073        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6074        try {
6075            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6076        } finally {
6077            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6078        }
6079    }
6080
6081    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6082        final File[] files = dir.listFiles();
6083        if (ArrayUtils.isEmpty(files)) {
6084            Log.d(TAG, "No files in app dir " + dir);
6085            return;
6086        }
6087
6088        if (DEBUG_PACKAGE_SCANNING) {
6089            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6090                    + " flags=0x" + Integer.toHexString(parseFlags));
6091        }
6092
6093        for (File file : files) {
6094            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6095                    && !PackageInstallerService.isStageName(file.getName());
6096            if (!isPackage) {
6097                // Ignore entries which are not packages
6098                continue;
6099            }
6100            try {
6101                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6102                        scanFlags, currentTime, null);
6103            } catch (PackageManagerException e) {
6104                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6105
6106                // Delete invalid userdata apps
6107                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6108                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6109                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6110                    if (file.isDirectory()) {
6111                        mInstaller.rmPackageDir(file.getAbsolutePath());
6112                    } else {
6113                        file.delete();
6114                    }
6115                }
6116            }
6117        }
6118    }
6119
6120    private static File getSettingsProblemFile() {
6121        File dataDir = Environment.getDataDirectory();
6122        File systemDir = new File(dataDir, "system");
6123        File fname = new File(systemDir, "uiderrors.txt");
6124        return fname;
6125    }
6126
6127    static void reportSettingsProblem(int priority, String msg) {
6128        logCriticalInfo(priority, msg);
6129    }
6130
6131    static void logCriticalInfo(int priority, String msg) {
6132        Slog.println(priority, TAG, msg);
6133        EventLogTags.writePmCriticalInfo(msg);
6134        try {
6135            File fname = getSettingsProblemFile();
6136            FileOutputStream out = new FileOutputStream(fname, true);
6137            PrintWriter pw = new FastPrintWriter(out);
6138            SimpleDateFormat formatter = new SimpleDateFormat();
6139            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6140            pw.println(dateString + ": " + msg);
6141            pw.close();
6142            FileUtils.setPermissions(
6143                    fname.toString(),
6144                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6145                    -1, -1);
6146        } catch (java.io.IOException e) {
6147        }
6148    }
6149
6150    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6151            PackageParser.Package pkg, File srcFile, int parseFlags)
6152            throws PackageManagerException {
6153        if (ps != null
6154                && ps.codePath.equals(srcFile)
6155                && ps.timeStamp == srcFile.lastModified()
6156                && !isCompatSignatureUpdateNeeded(pkg)
6157                && !isRecoverSignatureUpdateNeeded(pkg)) {
6158            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6159            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6160            ArraySet<PublicKey> signingKs;
6161            synchronized (mPackages) {
6162                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6163            }
6164            if (ps.signatures.mSignatures != null
6165                    && ps.signatures.mSignatures.length != 0
6166                    && signingKs != null) {
6167                // Optimization: reuse the existing cached certificates
6168                // if the package appears to be unchanged.
6169                pkg.mSignatures = ps.signatures.mSignatures;
6170                pkg.mSigningKeys = signingKs;
6171                return;
6172            }
6173
6174            Slog.w(TAG, "PackageSetting for " + ps.name
6175                    + " is missing signatures.  Collecting certs again to recover them.");
6176        } else {
6177            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6178        }
6179
6180        try {
6181            pp.collectCertificates(pkg, parseFlags);
6182            pp.collectManifestDigest(pkg);
6183        } catch (PackageParserException e) {
6184            throw PackageManagerException.from(e);
6185        }
6186    }
6187
6188    /**
6189     *  Traces a package scan.
6190     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6191     */
6192    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6193            long currentTime, UserHandle user) throws PackageManagerException {
6194        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6195        try {
6196            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6197        } finally {
6198            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6199        }
6200    }
6201
6202    /**
6203     *  Scans a package and returns the newly parsed package.
6204     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6205     */
6206    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6207            long currentTime, UserHandle user) throws PackageManagerException {
6208        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6209        parseFlags |= mDefParseFlags;
6210        PackageParser pp = new PackageParser();
6211        pp.setSeparateProcesses(mSeparateProcesses);
6212        pp.setOnlyCoreApps(mOnlyCore);
6213        pp.setDisplayMetrics(mMetrics);
6214
6215        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6216            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6217        }
6218
6219        final PackageParser.Package pkg;
6220        try {
6221            pkg = pp.parsePackage(scanFile, parseFlags);
6222        } catch (PackageParserException e) {
6223            throw PackageManagerException.from(e);
6224        }
6225
6226        PackageSetting ps = null;
6227        PackageSetting updatedPkg;
6228        // reader
6229        synchronized (mPackages) {
6230            // Look to see if we already know about this package.
6231            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6232            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6233                // This package has been renamed to its original name.  Let's
6234                // use that.
6235                ps = mSettings.peekPackageLPr(oldName);
6236            }
6237            // If there was no original package, see one for the real package name.
6238            if (ps == null) {
6239                ps = mSettings.peekPackageLPr(pkg.packageName);
6240            }
6241            // Check to see if this package could be hiding/updating a system
6242            // package.  Must look for it either under the original or real
6243            // package name depending on our state.
6244            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6245            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6246        }
6247        boolean updatedPkgBetter = false;
6248        // First check if this is a system package that may involve an update
6249        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6250            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6251            // it needs to drop FLAG_PRIVILEGED.
6252            if (locationIsPrivileged(scanFile)) {
6253                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6254            } else {
6255                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6256            }
6257
6258            if (ps != null && !ps.codePath.equals(scanFile)) {
6259                // The path has changed from what was last scanned...  check the
6260                // version of the new path against what we have stored to determine
6261                // what to do.
6262                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6263                if (pkg.mVersionCode <= ps.versionCode) {
6264                    // The system package has been updated and the code path does not match
6265                    // Ignore entry. Skip it.
6266                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6267                            + " ignored: updated version " + ps.versionCode
6268                            + " better than this " + pkg.mVersionCode);
6269                    if (!updatedPkg.codePath.equals(scanFile)) {
6270                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6271                                + ps.name + " changing from " + updatedPkg.codePathString
6272                                + " to " + scanFile);
6273                        updatedPkg.codePath = scanFile;
6274                        updatedPkg.codePathString = scanFile.toString();
6275                        updatedPkg.resourcePath = scanFile;
6276                        updatedPkg.resourcePathString = scanFile.toString();
6277                    }
6278                    updatedPkg.pkg = pkg;
6279                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6280                            "Package " + ps.name + " at " + scanFile
6281                                    + " ignored: updated version " + ps.versionCode
6282                                    + " better than this " + pkg.mVersionCode);
6283                } else {
6284                    // The current app on the system partition is better than
6285                    // what we have updated to on the data partition; switch
6286                    // back to the system partition version.
6287                    // At this point, its safely assumed that package installation for
6288                    // apps in system partition will go through. If not there won't be a working
6289                    // version of the app
6290                    // writer
6291                    synchronized (mPackages) {
6292                        // Just remove the loaded entries from package lists.
6293                        mPackages.remove(ps.name);
6294                    }
6295
6296                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6297                            + " reverting from " + ps.codePathString
6298                            + ": new version " + pkg.mVersionCode
6299                            + " better than installed " + ps.versionCode);
6300
6301                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6302                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6303                    synchronized (mInstallLock) {
6304                        args.cleanUpResourcesLI();
6305                    }
6306                    synchronized (mPackages) {
6307                        mSettings.enableSystemPackageLPw(ps.name);
6308                    }
6309                    updatedPkgBetter = true;
6310                }
6311            }
6312        }
6313
6314        if (updatedPkg != null) {
6315            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6316            // initially
6317            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6318
6319            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6320            // flag set initially
6321            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6322                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6323            }
6324        }
6325
6326        // Verify certificates against what was last scanned
6327        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6328
6329        /*
6330         * A new system app appeared, but we already had a non-system one of the
6331         * same name installed earlier.
6332         */
6333        boolean shouldHideSystemApp = false;
6334        if (updatedPkg == null && ps != null
6335                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6336            /*
6337             * Check to make sure the signatures match first. If they don't,
6338             * wipe the installed application and its data.
6339             */
6340            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6341                    != PackageManager.SIGNATURE_MATCH) {
6342                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6343                        + " signatures don't match existing userdata copy; removing");
6344                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6345                ps = null;
6346            } else {
6347                /*
6348                 * If the newly-added system app is an older version than the
6349                 * already installed version, hide it. It will be scanned later
6350                 * and re-added like an update.
6351                 */
6352                if (pkg.mVersionCode <= ps.versionCode) {
6353                    shouldHideSystemApp = true;
6354                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6355                            + " but new version " + pkg.mVersionCode + " better than installed "
6356                            + ps.versionCode + "; hiding system");
6357                } else {
6358                    /*
6359                     * The newly found system app is a newer version that the
6360                     * one previously installed. Simply remove the
6361                     * already-installed application and replace it with our own
6362                     * while keeping the application data.
6363                     */
6364                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6365                            + " reverting from " + ps.codePathString + ": new version "
6366                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6367                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6368                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6369                    synchronized (mInstallLock) {
6370                        args.cleanUpResourcesLI();
6371                    }
6372                }
6373            }
6374        }
6375
6376        // The apk is forward locked (not public) if its code and resources
6377        // are kept in different files. (except for app in either system or
6378        // vendor path).
6379        // TODO grab this value from PackageSettings
6380        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6381            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6382                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6383            }
6384        }
6385
6386        // TODO: extend to support forward-locked splits
6387        String resourcePath = null;
6388        String baseResourcePath = null;
6389        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6390            if (ps != null && ps.resourcePathString != null) {
6391                resourcePath = ps.resourcePathString;
6392                baseResourcePath = ps.resourcePathString;
6393            } else {
6394                // Should not happen at all. Just log an error.
6395                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6396            }
6397        } else {
6398            resourcePath = pkg.codePath;
6399            baseResourcePath = pkg.baseCodePath;
6400        }
6401
6402        // Set application objects path explicitly.
6403        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6404        pkg.applicationInfo.setCodePath(pkg.codePath);
6405        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6406        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6407        pkg.applicationInfo.setResourcePath(resourcePath);
6408        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6409        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6410
6411        // Note that we invoke the following method only if we are about to unpack an application
6412        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6413                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6414
6415        /*
6416         * If the system app should be overridden by a previously installed
6417         * data, hide the system app now and let the /data/app scan pick it up
6418         * again.
6419         */
6420        if (shouldHideSystemApp) {
6421            synchronized (mPackages) {
6422                mSettings.disableSystemPackageLPw(pkg.packageName);
6423            }
6424        }
6425
6426        return scannedPkg;
6427    }
6428
6429    private static String fixProcessName(String defProcessName,
6430            String processName, int uid) {
6431        if (processName == null) {
6432            return defProcessName;
6433        }
6434        return processName;
6435    }
6436
6437    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6438            throws PackageManagerException {
6439        if (pkgSetting.signatures.mSignatures != null) {
6440            // Already existing package. Make sure signatures match
6441            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6442                    == PackageManager.SIGNATURE_MATCH;
6443            if (!match) {
6444                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6445                        == PackageManager.SIGNATURE_MATCH;
6446            }
6447            if (!match) {
6448                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6449                        == PackageManager.SIGNATURE_MATCH;
6450            }
6451            if (!match) {
6452                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6453                        + pkg.packageName + " signatures do not match the "
6454                        + "previously installed version; ignoring!");
6455            }
6456        }
6457
6458        // Check for shared user signatures
6459        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6460            // Already existing package. Make sure signatures match
6461            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6462                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6463            if (!match) {
6464                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6465                        == PackageManager.SIGNATURE_MATCH;
6466            }
6467            if (!match) {
6468                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6469                        == PackageManager.SIGNATURE_MATCH;
6470            }
6471            if (!match) {
6472                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6473                        "Package " + pkg.packageName
6474                        + " has no signatures that match those in shared user "
6475                        + pkgSetting.sharedUser.name + "; ignoring!");
6476            }
6477        }
6478    }
6479
6480    /**
6481     * Enforces that only the system UID or root's UID can call a method exposed
6482     * via Binder.
6483     *
6484     * @param message used as message if SecurityException is thrown
6485     * @throws SecurityException if the caller is not system or root
6486     */
6487    private static final void enforceSystemOrRoot(String message) {
6488        final int uid = Binder.getCallingUid();
6489        if (uid != Process.SYSTEM_UID && uid != 0) {
6490            throw new SecurityException(message);
6491        }
6492    }
6493
6494    @Override
6495    public void performFstrimIfNeeded() {
6496        enforceSystemOrRoot("Only the system can request fstrim");
6497
6498        // Before everything else, see whether we need to fstrim.
6499        try {
6500            IMountService ms = PackageHelper.getMountService();
6501            if (ms != null) {
6502                final boolean isUpgrade = isUpgrade();
6503                boolean doTrim = isUpgrade;
6504                if (doTrim) {
6505                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6506                } else {
6507                    final long interval = android.provider.Settings.Global.getLong(
6508                            mContext.getContentResolver(),
6509                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6510                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6511                    if (interval > 0) {
6512                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6513                        if (timeSinceLast > interval) {
6514                            doTrim = true;
6515                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6516                                    + "; running immediately");
6517                        }
6518                    }
6519                }
6520                if (doTrim) {
6521                    if (!isFirstBoot()) {
6522                        try {
6523                            ActivityManagerNative.getDefault().showBootMessage(
6524                                    mContext.getResources().getString(
6525                                            R.string.android_upgrading_fstrim), true);
6526                        } catch (RemoteException e) {
6527                        }
6528                    }
6529                    ms.runMaintenance();
6530                }
6531            } else {
6532                Slog.e(TAG, "Mount service unavailable!");
6533            }
6534        } catch (RemoteException e) {
6535            // Can't happen; MountService is local
6536        }
6537    }
6538
6539    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6540        List<ResolveInfo> ris = null;
6541        try {
6542            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6543                    intent, null, 0, userId);
6544        } catch (RemoteException e) {
6545        }
6546        ArraySet<String> pkgNames = new ArraySet<String>();
6547        if (ris != null) {
6548            for (ResolveInfo ri : ris) {
6549                pkgNames.add(ri.activityInfo.packageName);
6550            }
6551        }
6552        return pkgNames;
6553    }
6554
6555    @Override
6556    public void notifyPackageUse(String packageName) {
6557        synchronized (mPackages) {
6558            PackageParser.Package p = mPackages.get(packageName);
6559            if (p == null) {
6560                return;
6561            }
6562            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6563        }
6564    }
6565
6566    @Override
6567    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6568        return performDexOptTraced(packageName, instructionSet);
6569    }
6570
6571    public boolean performDexOpt(String packageName, String instructionSet) {
6572        return performDexOptTraced(packageName, instructionSet);
6573    }
6574
6575    private boolean performDexOptTraced(String packageName, String instructionSet) {
6576        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6577        try {
6578            return performDexOptInternal(packageName, instructionSet);
6579        } finally {
6580            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6581        }
6582    }
6583
6584    private boolean performDexOptInternal(String packageName, String instructionSet) {
6585        PackageParser.Package p;
6586        final String targetInstructionSet;
6587        synchronized (mPackages) {
6588            p = mPackages.get(packageName);
6589            if (p == null) {
6590                return false;
6591            }
6592            mPackageUsage.write(false);
6593
6594            targetInstructionSet = instructionSet != null ? instructionSet :
6595                    getPrimaryInstructionSet(p.applicationInfo);
6596            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6597                return false;
6598            }
6599        }
6600        long callingId = Binder.clearCallingIdentity();
6601        try {
6602            synchronized (mInstallLock) {
6603                final String[] instructionSets = new String[] { targetInstructionSet };
6604                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6605                        true /* inclDependencies */);
6606                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6607            }
6608        } finally {
6609            Binder.restoreCallingIdentity(callingId);
6610        }
6611    }
6612
6613    public ArraySet<String> getPackagesThatNeedDexOpt() {
6614        ArraySet<String> pkgs = null;
6615        synchronized (mPackages) {
6616            for (PackageParser.Package p : mPackages.values()) {
6617                if (DEBUG_DEXOPT) {
6618                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6619                }
6620                if (!p.mDexOptPerformed.isEmpty()) {
6621                    continue;
6622                }
6623                if (pkgs == null) {
6624                    pkgs = new ArraySet<String>();
6625                }
6626                pkgs.add(p.packageName);
6627            }
6628        }
6629        return pkgs;
6630    }
6631
6632    public void shutdown() {
6633        mPackageUsage.write(true);
6634    }
6635
6636    @Override
6637    public void forceDexOpt(String packageName) {
6638        enforceSystemOrRoot("forceDexOpt");
6639
6640        PackageParser.Package pkg;
6641        synchronized (mPackages) {
6642            pkg = mPackages.get(packageName);
6643            if (pkg == null) {
6644                throw new IllegalArgumentException("Missing package: " + packageName);
6645            }
6646        }
6647
6648        synchronized (mInstallLock) {
6649            final String[] instructionSets = new String[] {
6650                    getPrimaryInstructionSet(pkg.applicationInfo) };
6651
6652            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6653
6654            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6655                    true /* inclDependencies */);
6656
6657            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6658            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6659                throw new IllegalStateException("Failed to dexopt: " + res);
6660            }
6661        }
6662    }
6663
6664    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6665        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6666            Slog.w(TAG, "Unable to update from " + oldPkg.name
6667                    + " to " + newPkg.packageName
6668                    + ": old package not in system partition");
6669            return false;
6670        } else if (mPackages.get(oldPkg.name) != null) {
6671            Slog.w(TAG, "Unable to update from " + oldPkg.name
6672                    + " to " + newPkg.packageName
6673                    + ": old package still exists");
6674            return false;
6675        }
6676        return true;
6677    }
6678
6679    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6680            throws PackageManagerException {
6681        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6682        if (res != 0) {
6683            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6684                    "Failed to install " + packageName + ": " + res);
6685        }
6686
6687        final int[] users = sUserManager.getUserIds();
6688        for (int user : users) {
6689            if (user != 0) {
6690                res = mInstaller.createUserData(volumeUuid, packageName,
6691                        UserHandle.getUid(user, uid), user, seinfo);
6692                if (res != 0) {
6693                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6694                            "Failed to createUserData " + packageName + ": " + res);
6695                }
6696            }
6697        }
6698    }
6699
6700    private int removeDataDirsLI(String volumeUuid, String packageName) {
6701        int[] users = sUserManager.getUserIds();
6702        int res = 0;
6703        for (int user : users) {
6704            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6705            if (resInner < 0) {
6706                res = resInner;
6707            }
6708        }
6709
6710        return res;
6711    }
6712
6713    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6714        int[] users = sUserManager.getUserIds();
6715        int res = 0;
6716        for (int user : users) {
6717            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6718            if (resInner < 0) {
6719                res = resInner;
6720            }
6721        }
6722        return res;
6723    }
6724
6725    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6726            PackageParser.Package changingLib) {
6727        if (file.path != null) {
6728            usesLibraryFiles.add(file.path);
6729            return;
6730        }
6731        PackageParser.Package p = mPackages.get(file.apk);
6732        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6733            // If we are doing this while in the middle of updating a library apk,
6734            // then we need to make sure to use that new apk for determining the
6735            // dependencies here.  (We haven't yet finished committing the new apk
6736            // to the package manager state.)
6737            if (p == null || p.packageName.equals(changingLib.packageName)) {
6738                p = changingLib;
6739            }
6740        }
6741        if (p != null) {
6742            usesLibraryFiles.addAll(p.getAllCodePaths());
6743        }
6744    }
6745
6746    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6747            PackageParser.Package changingLib) throws PackageManagerException {
6748        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6749            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6750            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6751            for (int i=0; i<N; i++) {
6752                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6753                if (file == null) {
6754                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6755                            "Package " + pkg.packageName + " requires unavailable shared library "
6756                            + pkg.usesLibraries.get(i) + "; failing!");
6757                }
6758                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6759            }
6760            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6761            for (int i=0; i<N; i++) {
6762                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6763                if (file == null) {
6764                    Slog.w(TAG, "Package " + pkg.packageName
6765                            + " desires unavailable shared library "
6766                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6767                } else {
6768                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6769                }
6770            }
6771            N = usesLibraryFiles.size();
6772            if (N > 0) {
6773                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6774            } else {
6775                pkg.usesLibraryFiles = null;
6776            }
6777        }
6778    }
6779
6780    private static boolean hasString(List<String> list, List<String> which) {
6781        if (list == null) {
6782            return false;
6783        }
6784        for (int i=list.size()-1; i>=0; i--) {
6785            for (int j=which.size()-1; j>=0; j--) {
6786                if (which.get(j).equals(list.get(i))) {
6787                    return true;
6788                }
6789            }
6790        }
6791        return false;
6792    }
6793
6794    private void updateAllSharedLibrariesLPw() {
6795        for (PackageParser.Package pkg : mPackages.values()) {
6796            try {
6797                updateSharedLibrariesLPw(pkg, null);
6798            } catch (PackageManagerException e) {
6799                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6800            }
6801        }
6802    }
6803
6804    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6805            PackageParser.Package changingPkg) {
6806        ArrayList<PackageParser.Package> res = null;
6807        for (PackageParser.Package pkg : mPackages.values()) {
6808            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6809                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6810                if (res == null) {
6811                    res = new ArrayList<PackageParser.Package>();
6812                }
6813                res.add(pkg);
6814                try {
6815                    updateSharedLibrariesLPw(pkg, changingPkg);
6816                } catch (PackageManagerException e) {
6817                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6818                }
6819            }
6820        }
6821        return res;
6822    }
6823
6824    /**
6825     * Derive the value of the {@code cpuAbiOverride} based on the provided
6826     * value and an optional stored value from the package settings.
6827     */
6828    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6829        String cpuAbiOverride = null;
6830
6831        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6832            cpuAbiOverride = null;
6833        } else if (abiOverride != null) {
6834            cpuAbiOverride = abiOverride;
6835        } else if (settings != null) {
6836            cpuAbiOverride = settings.cpuAbiOverrideString;
6837        }
6838
6839        return cpuAbiOverride;
6840    }
6841
6842    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6843            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6844        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6845        try {
6846            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6847        } finally {
6848            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6849        }
6850    }
6851
6852    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6853            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6854        boolean success = false;
6855        try {
6856            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6857                    currentTime, user);
6858            success = true;
6859            return res;
6860        } finally {
6861            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6862                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6863            }
6864        }
6865    }
6866
6867    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6868            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6869        final File scanFile = new File(pkg.codePath);
6870        if (pkg.applicationInfo.getCodePath() == null ||
6871                pkg.applicationInfo.getResourcePath() == null) {
6872            // Bail out. The resource and code paths haven't been set.
6873            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6874                    "Code and resource paths haven't been set correctly");
6875        }
6876
6877        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6878            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6879        } else {
6880            // Only allow system apps to be flagged as core apps.
6881            pkg.coreApp = false;
6882        }
6883
6884        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6885            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6886        }
6887
6888        if (mCustomResolverComponentName != null &&
6889                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6890            setUpCustomResolverActivity(pkg);
6891        }
6892
6893        if (pkg.packageName.equals("android")) {
6894            synchronized (mPackages) {
6895                if (mAndroidApplication != null) {
6896                    Slog.w(TAG, "*************************************************");
6897                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6898                    Slog.w(TAG, " file=" + scanFile);
6899                    Slog.w(TAG, "*************************************************");
6900                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6901                            "Core android package being redefined.  Skipping.");
6902                }
6903
6904                // Set up information for our fall-back user intent resolution activity.
6905                mPlatformPackage = pkg;
6906                pkg.mVersionCode = mSdkVersion;
6907                mAndroidApplication = pkg.applicationInfo;
6908
6909                if (!mResolverReplaced) {
6910                    mResolveActivity.applicationInfo = mAndroidApplication;
6911                    mResolveActivity.name = ResolverActivity.class.getName();
6912                    mResolveActivity.packageName = mAndroidApplication.packageName;
6913                    mResolveActivity.processName = "system:ui";
6914                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6915                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6916                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6917                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6918                    mResolveActivity.exported = true;
6919                    mResolveActivity.enabled = true;
6920                    mResolveInfo.activityInfo = mResolveActivity;
6921                    mResolveInfo.priority = 0;
6922                    mResolveInfo.preferredOrder = 0;
6923                    mResolveInfo.match = 0;
6924                    mResolveComponentName = new ComponentName(
6925                            mAndroidApplication.packageName, mResolveActivity.name);
6926                }
6927            }
6928        }
6929
6930        if (DEBUG_PACKAGE_SCANNING) {
6931            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6932                Log.d(TAG, "Scanning package " + pkg.packageName);
6933        }
6934
6935        if (mPackages.containsKey(pkg.packageName)
6936                || mSharedLibraries.containsKey(pkg.packageName)) {
6937            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6938                    "Application package " + pkg.packageName
6939                    + " already installed.  Skipping duplicate.");
6940        }
6941
6942        // If we're only installing presumed-existing packages, require that the
6943        // scanned APK is both already known and at the path previously established
6944        // for it.  Previously unknown packages we pick up normally, but if we have an
6945        // a priori expectation about this package's install presence, enforce it.
6946        // With a singular exception for new system packages. When an OTA contains
6947        // a new system package, we allow the codepath to change from a system location
6948        // to the user-installed location. If we don't allow this change, any newer,
6949        // user-installed version of the application will be ignored.
6950        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6951            if (mExpectingBetter.containsKey(pkg.packageName)) {
6952                logCriticalInfo(Log.WARN,
6953                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6954            } else {
6955                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6956                if (known != null) {
6957                    if (DEBUG_PACKAGE_SCANNING) {
6958                        Log.d(TAG, "Examining " + pkg.codePath
6959                                + " and requiring known paths " + known.codePathString
6960                                + " & " + known.resourcePathString);
6961                    }
6962                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6963                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6964                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6965                                "Application package " + pkg.packageName
6966                                + " found at " + pkg.applicationInfo.getCodePath()
6967                                + " but expected at " + known.codePathString + "; ignoring.");
6968                    }
6969                }
6970            }
6971        }
6972
6973        // Initialize package source and resource directories
6974        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6975        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6976
6977        SharedUserSetting suid = null;
6978        PackageSetting pkgSetting = null;
6979
6980        if (!isSystemApp(pkg)) {
6981            // Only system apps can use these features.
6982            pkg.mOriginalPackages = null;
6983            pkg.mRealPackage = null;
6984            pkg.mAdoptPermissions = null;
6985        }
6986
6987        // writer
6988        synchronized (mPackages) {
6989            if (pkg.mSharedUserId != null) {
6990                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6991                if (suid == null) {
6992                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6993                            "Creating application package " + pkg.packageName
6994                            + " for shared user failed");
6995                }
6996                if (DEBUG_PACKAGE_SCANNING) {
6997                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6998                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6999                                + "): packages=" + suid.packages);
7000                }
7001            }
7002
7003            // Check if we are renaming from an original package name.
7004            PackageSetting origPackage = null;
7005            String realName = null;
7006            if (pkg.mOriginalPackages != null) {
7007                // This package may need to be renamed to a previously
7008                // installed name.  Let's check on that...
7009                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7010                if (pkg.mOriginalPackages.contains(renamed)) {
7011                    // This package had originally been installed as the
7012                    // original name, and we have already taken care of
7013                    // transitioning to the new one.  Just update the new
7014                    // one to continue using the old name.
7015                    realName = pkg.mRealPackage;
7016                    if (!pkg.packageName.equals(renamed)) {
7017                        // Callers into this function may have already taken
7018                        // care of renaming the package; only do it here if
7019                        // it is not already done.
7020                        pkg.setPackageName(renamed);
7021                    }
7022
7023                } else {
7024                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7025                        if ((origPackage = mSettings.peekPackageLPr(
7026                                pkg.mOriginalPackages.get(i))) != null) {
7027                            // We do have the package already installed under its
7028                            // original name...  should we use it?
7029                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7030                                // New package is not compatible with original.
7031                                origPackage = null;
7032                                continue;
7033                            } else if (origPackage.sharedUser != null) {
7034                                // Make sure uid is compatible between packages.
7035                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7036                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7037                                            + " to " + pkg.packageName + ": old uid "
7038                                            + origPackage.sharedUser.name
7039                                            + " differs from " + pkg.mSharedUserId);
7040                                    origPackage = null;
7041                                    continue;
7042                                }
7043                            } else {
7044                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7045                                        + pkg.packageName + " to old name " + origPackage.name);
7046                            }
7047                            break;
7048                        }
7049                    }
7050                }
7051            }
7052
7053            if (mTransferedPackages.contains(pkg.packageName)) {
7054                Slog.w(TAG, "Package " + pkg.packageName
7055                        + " was transferred to another, but its .apk remains");
7056            }
7057
7058            // Just create the setting, don't add it yet. For already existing packages
7059            // the PkgSetting exists already and doesn't have to be created.
7060            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7061                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7062                    pkg.applicationInfo.primaryCpuAbi,
7063                    pkg.applicationInfo.secondaryCpuAbi,
7064                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7065                    user, false);
7066            if (pkgSetting == null) {
7067                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7068                        "Creating application package " + pkg.packageName + " failed");
7069            }
7070
7071            if (pkgSetting.origPackage != null) {
7072                // If we are first transitioning from an original package,
7073                // fix up the new package's name now.  We need to do this after
7074                // looking up the package under its new name, so getPackageLP
7075                // can take care of fiddling things correctly.
7076                pkg.setPackageName(origPackage.name);
7077
7078                // File a report about this.
7079                String msg = "New package " + pkgSetting.realName
7080                        + " renamed to replace old package " + pkgSetting.name;
7081                reportSettingsProblem(Log.WARN, msg);
7082
7083                // Make a note of it.
7084                mTransferedPackages.add(origPackage.name);
7085
7086                // No longer need to retain this.
7087                pkgSetting.origPackage = null;
7088            }
7089
7090            if (realName != null) {
7091                // Make a note of it.
7092                mTransferedPackages.add(pkg.packageName);
7093            }
7094
7095            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7096                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7097            }
7098
7099            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7100                // Check all shared libraries and map to their actual file path.
7101                // We only do this here for apps not on a system dir, because those
7102                // are the only ones that can fail an install due to this.  We
7103                // will take care of the system apps by updating all of their
7104                // library paths after the scan is done.
7105                updateSharedLibrariesLPw(pkg, null);
7106            }
7107
7108            if (mFoundPolicyFile) {
7109                SELinuxMMAC.assignSeinfoValue(pkg);
7110            }
7111
7112            pkg.applicationInfo.uid = pkgSetting.appId;
7113            pkg.mExtras = pkgSetting;
7114            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7115                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7116                    // We just determined the app is signed correctly, so bring
7117                    // over the latest parsed certs.
7118                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7119                } else {
7120                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7121                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7122                                "Package " + pkg.packageName + " upgrade keys do not match the "
7123                                + "previously installed version");
7124                    } else {
7125                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7126                        String msg = "System package " + pkg.packageName
7127                            + " signature changed; retaining data.";
7128                        reportSettingsProblem(Log.WARN, msg);
7129                    }
7130                }
7131            } else {
7132                try {
7133                    verifySignaturesLP(pkgSetting, pkg);
7134                    // We just determined the app is signed correctly, so bring
7135                    // over the latest parsed certs.
7136                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7137                } catch (PackageManagerException e) {
7138                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7139                        throw e;
7140                    }
7141                    // The signature has changed, but this package is in the system
7142                    // image...  let's recover!
7143                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7144                    // However...  if this package is part of a shared user, but it
7145                    // doesn't match the signature of the shared user, let's fail.
7146                    // What this means is that you can't change the signatures
7147                    // associated with an overall shared user, which doesn't seem all
7148                    // that unreasonable.
7149                    if (pkgSetting.sharedUser != null) {
7150                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7151                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7152                            throw new PackageManagerException(
7153                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7154                                            "Signature mismatch for shared user : "
7155                                            + pkgSetting.sharedUser);
7156                        }
7157                    }
7158                    // File a report about this.
7159                    String msg = "System package " + pkg.packageName
7160                        + " signature changed; retaining data.";
7161                    reportSettingsProblem(Log.WARN, msg);
7162                }
7163            }
7164            // Verify that this new package doesn't have any content providers
7165            // that conflict with existing packages.  Only do this if the
7166            // package isn't already installed, since we don't want to break
7167            // things that are installed.
7168            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7169                final int N = pkg.providers.size();
7170                int i;
7171                for (i=0; i<N; i++) {
7172                    PackageParser.Provider p = pkg.providers.get(i);
7173                    if (p.info.authority != null) {
7174                        String names[] = p.info.authority.split(";");
7175                        for (int j = 0; j < names.length; j++) {
7176                            if (mProvidersByAuthority.containsKey(names[j])) {
7177                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7178                                final String otherPackageName =
7179                                        ((other != null && other.getComponentName() != null) ?
7180                                                other.getComponentName().getPackageName() : "?");
7181                                throw new PackageManagerException(
7182                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7183                                                "Can't install because provider name " + names[j]
7184                                                + " (in package " + pkg.applicationInfo.packageName
7185                                                + ") is already used by " + otherPackageName);
7186                            }
7187                        }
7188                    }
7189                }
7190            }
7191
7192            if (pkg.mAdoptPermissions != null) {
7193                // This package wants to adopt ownership of permissions from
7194                // another package.
7195                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7196                    final String origName = pkg.mAdoptPermissions.get(i);
7197                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7198                    if (orig != null) {
7199                        if (verifyPackageUpdateLPr(orig, pkg)) {
7200                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7201                                    + pkg.packageName);
7202                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7203                        }
7204                    }
7205                }
7206            }
7207        }
7208
7209        final String pkgName = pkg.packageName;
7210
7211        final long scanFileTime = scanFile.lastModified();
7212        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7213        pkg.applicationInfo.processName = fixProcessName(
7214                pkg.applicationInfo.packageName,
7215                pkg.applicationInfo.processName,
7216                pkg.applicationInfo.uid);
7217
7218        if (pkg != mPlatformPackage) {
7219            // This is a normal package, need to make its data directory.
7220            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7221                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7222
7223            boolean uidError = false;
7224            if (dataPath.exists()) {
7225                int currentUid = 0;
7226                try {
7227                    StructStat stat = Os.stat(dataPath.getPath());
7228                    currentUid = stat.st_uid;
7229                } catch (ErrnoException e) {
7230                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7231                }
7232
7233                // If we have mismatched owners for the data path, we have a problem.
7234                if (currentUid != pkg.applicationInfo.uid) {
7235                    boolean recovered = false;
7236                    if (currentUid == 0) {
7237                        // The directory somehow became owned by root.  Wow.
7238                        // This is probably because the system was stopped while
7239                        // installd was in the middle of messing with its libs
7240                        // directory.  Ask installd to fix that.
7241                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7242                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7243                        if (ret >= 0) {
7244                            recovered = true;
7245                            String msg = "Package " + pkg.packageName
7246                                    + " unexpectedly changed to uid 0; recovered to " +
7247                                    + pkg.applicationInfo.uid;
7248                            reportSettingsProblem(Log.WARN, msg);
7249                        }
7250                    }
7251                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7252                            || (scanFlags&SCAN_BOOTING) != 0)) {
7253                        // If this is a system app, we can at least delete its
7254                        // current data so the application will still work.
7255                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7256                        if (ret >= 0) {
7257                            // TODO: Kill the processes first
7258                            // Old data gone!
7259                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7260                                    ? "System package " : "Third party package ";
7261                            String msg = prefix + pkg.packageName
7262                                    + " has changed from uid: "
7263                                    + currentUid + " to "
7264                                    + pkg.applicationInfo.uid + "; old data erased";
7265                            reportSettingsProblem(Log.WARN, msg);
7266                            recovered = true;
7267                        }
7268                        if (!recovered) {
7269                            mHasSystemUidErrors = true;
7270                        }
7271                    } else if (!recovered) {
7272                        // If we allow this install to proceed, we will be broken.
7273                        // Abort, abort!
7274                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7275                                "scanPackageLI");
7276                    }
7277                    if (!recovered) {
7278                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7279                            + pkg.applicationInfo.uid + "/fs_"
7280                            + currentUid;
7281                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7282                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7283                        String msg = "Package " + pkg.packageName
7284                                + " has mismatched uid: "
7285                                + currentUid + " on disk, "
7286                                + pkg.applicationInfo.uid + " in settings";
7287                        // writer
7288                        synchronized (mPackages) {
7289                            mSettings.mReadMessages.append(msg);
7290                            mSettings.mReadMessages.append('\n');
7291                            uidError = true;
7292                            if (!pkgSetting.uidError) {
7293                                reportSettingsProblem(Log.ERROR, msg);
7294                            }
7295                        }
7296                    }
7297                }
7298
7299                // Ensure that directories are prepared
7300                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7301                        pkg.applicationInfo.seinfo);
7302
7303                if (mShouldRestoreconData) {
7304                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7305                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7306                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7307                }
7308            } else {
7309                if (DEBUG_PACKAGE_SCANNING) {
7310                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7311                        Log.v(TAG, "Want this data dir: " + dataPath);
7312                }
7313                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7314                        pkg.applicationInfo.seinfo);
7315            }
7316
7317            // Get all of our default paths setup
7318            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7319
7320            pkgSetting.uidError = uidError;
7321        }
7322
7323        final String path = scanFile.getPath();
7324        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7325
7326        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7327            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7328
7329            // Some system apps still use directory structure for native libraries
7330            // in which case we might end up not detecting abi solely based on apk
7331            // structure. Try to detect abi based on directory structure.
7332            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7333                    pkg.applicationInfo.primaryCpuAbi == null) {
7334                setBundledAppAbisAndRoots(pkg, pkgSetting);
7335                setNativeLibraryPaths(pkg);
7336            }
7337
7338        } else {
7339            if ((scanFlags & SCAN_MOVE) != 0) {
7340                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7341                // but we already have this packages package info in the PackageSetting. We just
7342                // use that and derive the native library path based on the new codepath.
7343                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7344                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7345            }
7346
7347            // Set native library paths again. For moves, the path will be updated based on the
7348            // ABIs we've determined above. For non-moves, the path will be updated based on the
7349            // ABIs we determined during compilation, but the path will depend on the final
7350            // package path (after the rename away from the stage path).
7351            setNativeLibraryPaths(pkg);
7352        }
7353
7354        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7355        final int[] userIds = sUserManager.getUserIds();
7356        synchronized (mInstallLock) {
7357            // Make sure all user data directories are ready to roll; we're okay
7358            // if they already exist
7359            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7360                for (int userId : userIds) {
7361                    if (userId != UserHandle.USER_SYSTEM) {
7362                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7363                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7364                                pkg.applicationInfo.seinfo);
7365                    }
7366                }
7367            }
7368
7369            // Create a native library symlink only if we have native libraries
7370            // and if the native libraries are 32 bit libraries. We do not provide
7371            // this symlink for 64 bit libraries.
7372            if (pkg.applicationInfo.primaryCpuAbi != null &&
7373                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7374                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7375                try {
7376                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7377                    for (int userId : userIds) {
7378                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7379                                nativeLibPath, userId) < 0) {
7380                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7381                                    "Failed linking native library dir (user=" + userId + ")");
7382                        }
7383                    }
7384                } finally {
7385                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7386                }
7387            }
7388        }
7389
7390        // This is a special case for the "system" package, where the ABI is
7391        // dictated by the zygote configuration (and init.rc). We should keep track
7392        // of this ABI so that we can deal with "normal" applications that run under
7393        // the same UID correctly.
7394        if (mPlatformPackage == pkg) {
7395            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7396                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7397        }
7398
7399        // If there's a mismatch between the abi-override in the package setting
7400        // and the abiOverride specified for the install. Warn about this because we
7401        // would've already compiled the app without taking the package setting into
7402        // account.
7403        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7404            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7405                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7406                        " for package: " + pkg.packageName);
7407            }
7408        }
7409
7410        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7411        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7412        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7413
7414        // Copy the derived override back to the parsed package, so that we can
7415        // update the package settings accordingly.
7416        pkg.cpuAbiOverride = cpuAbiOverride;
7417
7418        if (DEBUG_ABI_SELECTION) {
7419            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7420                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7421                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7422        }
7423
7424        // Push the derived path down into PackageSettings so we know what to
7425        // clean up at uninstall time.
7426        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7427
7428        if (DEBUG_ABI_SELECTION) {
7429            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7430                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7431                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7432        }
7433
7434        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7435            // We don't do this here during boot because we can do it all
7436            // at once after scanning all existing packages.
7437            //
7438            // We also do this *before* we perform dexopt on this package, so that
7439            // we can avoid redundant dexopts, and also to make sure we've got the
7440            // code and package path correct.
7441            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7442                    pkg, true /* boot complete */);
7443        }
7444
7445        if (mFactoryTest && pkg.requestedPermissions.contains(
7446                android.Manifest.permission.FACTORY_TEST)) {
7447            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7448        }
7449
7450        ArrayList<PackageParser.Package> clientLibPkgs = null;
7451
7452        // writer
7453        synchronized (mPackages) {
7454            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7455                // Only system apps can add new shared libraries.
7456                if (pkg.libraryNames != null) {
7457                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7458                        String name = pkg.libraryNames.get(i);
7459                        boolean allowed = false;
7460                        if (pkg.isUpdatedSystemApp()) {
7461                            // New library entries can only be added through the
7462                            // system image.  This is important to get rid of a lot
7463                            // of nasty edge cases: for example if we allowed a non-
7464                            // system update of the app to add a library, then uninstalling
7465                            // the update would make the library go away, and assumptions
7466                            // we made such as through app install filtering would now
7467                            // have allowed apps on the device which aren't compatible
7468                            // with it.  Better to just have the restriction here, be
7469                            // conservative, and create many fewer cases that can negatively
7470                            // impact the user experience.
7471                            final PackageSetting sysPs = mSettings
7472                                    .getDisabledSystemPkgLPr(pkg.packageName);
7473                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7474                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7475                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7476                                        allowed = true;
7477                                        break;
7478                                    }
7479                                }
7480                            }
7481                        } else {
7482                            allowed = true;
7483                        }
7484                        if (allowed) {
7485                            if (!mSharedLibraries.containsKey(name)) {
7486                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7487                            } else if (!name.equals(pkg.packageName)) {
7488                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7489                                        + name + " already exists; skipping");
7490                            }
7491                        } else {
7492                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7493                                    + name + " that is not declared on system image; skipping");
7494                        }
7495                    }
7496                    if ((scanFlags & SCAN_BOOTING) == 0) {
7497                        // If we are not booting, we need to update any applications
7498                        // that are clients of our shared library.  If we are booting,
7499                        // this will all be done once the scan is complete.
7500                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7501                    }
7502                }
7503            }
7504        }
7505
7506        // Request the ActivityManager to kill the process(only for existing packages)
7507        // so that we do not end up in a confused state while the user is still using the older
7508        // version of the application while the new one gets installed.
7509        if ((scanFlags & SCAN_REPLACING) != 0) {
7510            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7511
7512            killApplication(pkg.applicationInfo.packageName,
7513                        pkg.applicationInfo.uid, "replace pkg");
7514
7515            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7516        }
7517
7518        // Also need to kill any apps that are dependent on the library.
7519        if (clientLibPkgs != null) {
7520            for (int i=0; i<clientLibPkgs.size(); i++) {
7521                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7522                killApplication(clientPkg.applicationInfo.packageName,
7523                        clientPkg.applicationInfo.uid, "update lib");
7524            }
7525        }
7526
7527        // Make sure we're not adding any bogus keyset info
7528        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7529        ksms.assertScannedPackageValid(pkg);
7530
7531        // writer
7532        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7533
7534        boolean createIdmapFailed = false;
7535        synchronized (mPackages) {
7536            // We don't expect installation to fail beyond this point
7537
7538            // Add the new setting to mSettings
7539            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7540            // Add the new setting to mPackages
7541            mPackages.put(pkg.applicationInfo.packageName, pkg);
7542            // Make sure we don't accidentally delete its data.
7543            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7544            while (iter.hasNext()) {
7545                PackageCleanItem item = iter.next();
7546                if (pkgName.equals(item.packageName)) {
7547                    iter.remove();
7548                }
7549            }
7550
7551            // Take care of first install / last update times.
7552            if (currentTime != 0) {
7553                if (pkgSetting.firstInstallTime == 0) {
7554                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7555                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7556                    pkgSetting.lastUpdateTime = currentTime;
7557                }
7558            } else if (pkgSetting.firstInstallTime == 0) {
7559                // We need *something*.  Take time time stamp of the file.
7560                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7561            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7562                if (scanFileTime != pkgSetting.timeStamp) {
7563                    // A package on the system image has changed; consider this
7564                    // to be an update.
7565                    pkgSetting.lastUpdateTime = scanFileTime;
7566                }
7567            }
7568
7569            // Add the package's KeySets to the global KeySetManagerService
7570            ksms.addScannedPackageLPw(pkg);
7571
7572            int N = pkg.providers.size();
7573            StringBuilder r = null;
7574            int i;
7575            for (i=0; i<N; i++) {
7576                PackageParser.Provider p = pkg.providers.get(i);
7577                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7578                        p.info.processName, pkg.applicationInfo.uid);
7579                mProviders.addProvider(p);
7580                p.syncable = p.info.isSyncable;
7581                if (p.info.authority != null) {
7582                    String names[] = p.info.authority.split(";");
7583                    p.info.authority = null;
7584                    for (int j = 0; j < names.length; j++) {
7585                        if (j == 1 && p.syncable) {
7586                            // We only want the first authority for a provider to possibly be
7587                            // syncable, so if we already added this provider using a different
7588                            // authority clear the syncable flag. We copy the provider before
7589                            // changing it because the mProviders object contains a reference
7590                            // to a provider that we don't want to change.
7591                            // Only do this for the second authority since the resulting provider
7592                            // object can be the same for all future authorities for this provider.
7593                            p = new PackageParser.Provider(p);
7594                            p.syncable = false;
7595                        }
7596                        if (!mProvidersByAuthority.containsKey(names[j])) {
7597                            mProvidersByAuthority.put(names[j], p);
7598                            if (p.info.authority == null) {
7599                                p.info.authority = names[j];
7600                            } else {
7601                                p.info.authority = p.info.authority + ";" + names[j];
7602                            }
7603                            if (DEBUG_PACKAGE_SCANNING) {
7604                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7605                                    Log.d(TAG, "Registered content provider: " + names[j]
7606                                            + ", className = " + p.info.name + ", isSyncable = "
7607                                            + p.info.isSyncable);
7608                            }
7609                        } else {
7610                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7611                            Slog.w(TAG, "Skipping provider name " + names[j] +
7612                                    " (in package " + pkg.applicationInfo.packageName +
7613                                    "): name already used by "
7614                                    + ((other != null && other.getComponentName() != null)
7615                                            ? other.getComponentName().getPackageName() : "?"));
7616                        }
7617                    }
7618                }
7619                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7620                    if (r == null) {
7621                        r = new StringBuilder(256);
7622                    } else {
7623                        r.append(' ');
7624                    }
7625                    r.append(p.info.name);
7626                }
7627            }
7628            if (r != null) {
7629                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7630            }
7631
7632            N = pkg.services.size();
7633            r = null;
7634            for (i=0; i<N; i++) {
7635                PackageParser.Service s = pkg.services.get(i);
7636                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7637                        s.info.processName, pkg.applicationInfo.uid);
7638                mServices.addService(s);
7639                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7640                    if (r == null) {
7641                        r = new StringBuilder(256);
7642                    } else {
7643                        r.append(' ');
7644                    }
7645                    r.append(s.info.name);
7646                }
7647            }
7648            if (r != null) {
7649                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7650            }
7651
7652            N = pkg.receivers.size();
7653            r = null;
7654            for (i=0; i<N; i++) {
7655                PackageParser.Activity a = pkg.receivers.get(i);
7656                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7657                        a.info.processName, pkg.applicationInfo.uid);
7658                mReceivers.addActivity(a, "receiver");
7659                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7660                    if (r == null) {
7661                        r = new StringBuilder(256);
7662                    } else {
7663                        r.append(' ');
7664                    }
7665                    r.append(a.info.name);
7666                }
7667            }
7668            if (r != null) {
7669                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7670            }
7671
7672            N = pkg.activities.size();
7673            r = null;
7674            for (i=0; i<N; i++) {
7675                PackageParser.Activity a = pkg.activities.get(i);
7676                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7677                        a.info.processName, pkg.applicationInfo.uid);
7678                mActivities.addActivity(a, "activity");
7679                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7680                    if (r == null) {
7681                        r = new StringBuilder(256);
7682                    } else {
7683                        r.append(' ');
7684                    }
7685                    r.append(a.info.name);
7686                }
7687            }
7688            if (r != null) {
7689                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7690            }
7691
7692            N = pkg.permissionGroups.size();
7693            r = null;
7694            for (i=0; i<N; i++) {
7695                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7696                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7697                if (cur == null) {
7698                    mPermissionGroups.put(pg.info.name, pg);
7699                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7700                        if (r == null) {
7701                            r = new StringBuilder(256);
7702                        } else {
7703                            r.append(' ');
7704                        }
7705                        r.append(pg.info.name);
7706                    }
7707                } else {
7708                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7709                            + pg.info.packageName + " ignored: original from "
7710                            + cur.info.packageName);
7711                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7712                        if (r == null) {
7713                            r = new StringBuilder(256);
7714                        } else {
7715                            r.append(' ');
7716                        }
7717                        r.append("DUP:");
7718                        r.append(pg.info.name);
7719                    }
7720                }
7721            }
7722            if (r != null) {
7723                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7724            }
7725
7726            N = pkg.permissions.size();
7727            r = null;
7728            for (i=0; i<N; i++) {
7729                PackageParser.Permission p = pkg.permissions.get(i);
7730
7731                // Assume by default that we did not install this permission into the system.
7732                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7733
7734                // Now that permission groups have a special meaning, we ignore permission
7735                // groups for legacy apps to prevent unexpected behavior. In particular,
7736                // permissions for one app being granted to someone just becuase they happen
7737                // to be in a group defined by another app (before this had no implications).
7738                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7739                    p.group = mPermissionGroups.get(p.info.group);
7740                    // Warn for a permission in an unknown group.
7741                    if (p.info.group != null && p.group == null) {
7742                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7743                                + p.info.packageName + " in an unknown group " + p.info.group);
7744                    }
7745                }
7746
7747                ArrayMap<String, BasePermission> permissionMap =
7748                        p.tree ? mSettings.mPermissionTrees
7749                                : mSettings.mPermissions;
7750                BasePermission bp = permissionMap.get(p.info.name);
7751
7752                // Allow system apps to redefine non-system permissions
7753                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7754                    final boolean currentOwnerIsSystem = (bp.perm != null
7755                            && isSystemApp(bp.perm.owner));
7756                    if (isSystemApp(p.owner)) {
7757                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7758                            // It's a built-in permission and no owner, take ownership now
7759                            bp.packageSetting = pkgSetting;
7760                            bp.perm = p;
7761                            bp.uid = pkg.applicationInfo.uid;
7762                            bp.sourcePackage = p.info.packageName;
7763                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7764                        } else if (!currentOwnerIsSystem) {
7765                            String msg = "New decl " + p.owner + " of permission  "
7766                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7767                            reportSettingsProblem(Log.WARN, msg);
7768                            bp = null;
7769                        }
7770                    }
7771                }
7772
7773                if (bp == null) {
7774                    bp = new BasePermission(p.info.name, p.info.packageName,
7775                            BasePermission.TYPE_NORMAL);
7776                    permissionMap.put(p.info.name, bp);
7777                }
7778
7779                if (bp.perm == null) {
7780                    if (bp.sourcePackage == null
7781                            || bp.sourcePackage.equals(p.info.packageName)) {
7782                        BasePermission tree = findPermissionTreeLP(p.info.name);
7783                        if (tree == null
7784                                || tree.sourcePackage.equals(p.info.packageName)) {
7785                            bp.packageSetting = pkgSetting;
7786                            bp.perm = p;
7787                            bp.uid = pkg.applicationInfo.uid;
7788                            bp.sourcePackage = p.info.packageName;
7789                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7790                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7791                                if (r == null) {
7792                                    r = new StringBuilder(256);
7793                                } else {
7794                                    r.append(' ');
7795                                }
7796                                r.append(p.info.name);
7797                            }
7798                        } else {
7799                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7800                                    + p.info.packageName + " ignored: base tree "
7801                                    + tree.name + " is from package "
7802                                    + tree.sourcePackage);
7803                        }
7804                    } else {
7805                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7806                                + p.info.packageName + " ignored: original from "
7807                                + bp.sourcePackage);
7808                    }
7809                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7810                    if (r == null) {
7811                        r = new StringBuilder(256);
7812                    } else {
7813                        r.append(' ');
7814                    }
7815                    r.append("DUP:");
7816                    r.append(p.info.name);
7817                }
7818                if (bp.perm == p) {
7819                    bp.protectionLevel = p.info.protectionLevel;
7820                }
7821            }
7822
7823            if (r != null) {
7824                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7825            }
7826
7827            N = pkg.instrumentation.size();
7828            r = null;
7829            for (i=0; i<N; i++) {
7830                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7831                a.info.packageName = pkg.applicationInfo.packageName;
7832                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7833                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7834                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7835                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7836                a.info.dataDir = pkg.applicationInfo.dataDir;
7837                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7838                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7839
7840                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7841                // need other information about the application, like the ABI and what not ?
7842                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7843                mInstrumentation.put(a.getComponentName(), a);
7844                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7845                    if (r == null) {
7846                        r = new StringBuilder(256);
7847                    } else {
7848                        r.append(' ');
7849                    }
7850                    r.append(a.info.name);
7851                }
7852            }
7853            if (r != null) {
7854                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7855            }
7856
7857            if (pkg.protectedBroadcasts != null) {
7858                N = pkg.protectedBroadcasts.size();
7859                for (i=0; i<N; i++) {
7860                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7861                }
7862            }
7863
7864            pkgSetting.setTimeStamp(scanFileTime);
7865
7866            // Create idmap files for pairs of (packages, overlay packages).
7867            // Note: "android", ie framework-res.apk, is handled by native layers.
7868            if (pkg.mOverlayTarget != null) {
7869                // This is an overlay package.
7870                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7871                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7872                        mOverlays.put(pkg.mOverlayTarget,
7873                                new ArrayMap<String, PackageParser.Package>());
7874                    }
7875                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7876                    map.put(pkg.packageName, pkg);
7877                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7878                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7879                        createIdmapFailed = true;
7880                    }
7881                }
7882            } else if (mOverlays.containsKey(pkg.packageName) &&
7883                    !pkg.packageName.equals("android")) {
7884                // This is a regular package, with one or more known overlay packages.
7885                createIdmapsForPackageLI(pkg);
7886            }
7887        }
7888
7889        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7890
7891        if (createIdmapFailed) {
7892            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7893                    "scanPackageLI failed to createIdmap");
7894        }
7895        return pkg;
7896    }
7897
7898    /**
7899     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7900     * is derived purely on the basis of the contents of {@code scanFile} and
7901     * {@code cpuAbiOverride}.
7902     *
7903     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7904     */
7905    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7906                                 String cpuAbiOverride, boolean extractLibs)
7907            throws PackageManagerException {
7908        // TODO: We can probably be smarter about this stuff. For installed apps,
7909        // we can calculate this information at install time once and for all. For
7910        // system apps, we can probably assume that this information doesn't change
7911        // after the first boot scan. As things stand, we do lots of unnecessary work.
7912
7913        // Give ourselves some initial paths; we'll come back for another
7914        // pass once we've determined ABI below.
7915        setNativeLibraryPaths(pkg);
7916
7917        // We would never need to extract libs for forward-locked and external packages,
7918        // since the container service will do it for us. We shouldn't attempt to
7919        // extract libs from system app when it was not updated.
7920        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7921                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7922            extractLibs = false;
7923        }
7924
7925        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7926        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7927
7928        NativeLibraryHelper.Handle handle = null;
7929        try {
7930            handle = NativeLibraryHelper.Handle.create(pkg);
7931            // TODO(multiArch): This can be null for apps that didn't go through the
7932            // usual installation process. We can calculate it again, like we
7933            // do during install time.
7934            //
7935            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7936            // unnecessary.
7937            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7938
7939            // Null out the abis so that they can be recalculated.
7940            pkg.applicationInfo.primaryCpuAbi = null;
7941            pkg.applicationInfo.secondaryCpuAbi = null;
7942            if (isMultiArch(pkg.applicationInfo)) {
7943                // Warn if we've set an abiOverride for multi-lib packages..
7944                // By definition, we need to copy both 32 and 64 bit libraries for
7945                // such packages.
7946                if (pkg.cpuAbiOverride != null
7947                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7948                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7949                }
7950
7951                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7952                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7953                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7954                    if (extractLibs) {
7955                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7956                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7957                                useIsaSpecificSubdirs);
7958                    } else {
7959                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7960                    }
7961                }
7962
7963                maybeThrowExceptionForMultiArchCopy(
7964                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7965
7966                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7967                    if (extractLibs) {
7968                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7969                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7970                                useIsaSpecificSubdirs);
7971                    } else {
7972                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7973                    }
7974                }
7975
7976                maybeThrowExceptionForMultiArchCopy(
7977                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7978
7979                if (abi64 >= 0) {
7980                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7981                }
7982
7983                if (abi32 >= 0) {
7984                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7985                    if (abi64 >= 0) {
7986                        pkg.applicationInfo.secondaryCpuAbi = abi;
7987                    } else {
7988                        pkg.applicationInfo.primaryCpuAbi = abi;
7989                    }
7990                }
7991            } else {
7992                String[] abiList = (cpuAbiOverride != null) ?
7993                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7994
7995                // Enable gross and lame hacks for apps that are built with old
7996                // SDK tools. We must scan their APKs for renderscript bitcode and
7997                // not launch them if it's present. Don't bother checking on devices
7998                // that don't have 64 bit support.
7999                boolean needsRenderScriptOverride = false;
8000                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8001                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8002                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8003                    needsRenderScriptOverride = true;
8004                }
8005
8006                final int copyRet;
8007                if (extractLibs) {
8008                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8009                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8010                } else {
8011                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8012                }
8013
8014                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8015                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8016                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8017                }
8018
8019                if (copyRet >= 0) {
8020                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8021                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8022                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8023                } else if (needsRenderScriptOverride) {
8024                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8025                }
8026            }
8027        } catch (IOException ioe) {
8028            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8029        } finally {
8030            IoUtils.closeQuietly(handle);
8031        }
8032
8033        // Now that we've calculated the ABIs and determined if it's an internal app,
8034        // we will go ahead and populate the nativeLibraryPath.
8035        setNativeLibraryPaths(pkg);
8036    }
8037
8038    /**
8039     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8040     * i.e, so that all packages can be run inside a single process if required.
8041     *
8042     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8043     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8044     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8045     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8046     * updating a package that belongs to a shared user.
8047     *
8048     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8049     * adds unnecessary complexity.
8050     */
8051    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8052            PackageParser.Package scannedPackage, boolean bootComplete) {
8053        String requiredInstructionSet = null;
8054        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8055            requiredInstructionSet = VMRuntime.getInstructionSet(
8056                     scannedPackage.applicationInfo.primaryCpuAbi);
8057        }
8058
8059        PackageSetting requirer = null;
8060        for (PackageSetting ps : packagesForUser) {
8061            // If packagesForUser contains scannedPackage, we skip it. This will happen
8062            // when scannedPackage is an update of an existing package. Without this check,
8063            // we will never be able to change the ABI of any package belonging to a shared
8064            // user, even if it's compatible with other packages.
8065            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8066                if (ps.primaryCpuAbiString == null) {
8067                    continue;
8068                }
8069
8070                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8071                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8072                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8073                    // this but there's not much we can do.
8074                    String errorMessage = "Instruction set mismatch, "
8075                            + ((requirer == null) ? "[caller]" : requirer)
8076                            + " requires " + requiredInstructionSet + " whereas " + ps
8077                            + " requires " + instructionSet;
8078                    Slog.w(TAG, errorMessage);
8079                }
8080
8081                if (requiredInstructionSet == null) {
8082                    requiredInstructionSet = instructionSet;
8083                    requirer = ps;
8084                }
8085            }
8086        }
8087
8088        if (requiredInstructionSet != null) {
8089            String adjustedAbi;
8090            if (requirer != null) {
8091                // requirer != null implies that either scannedPackage was null or that scannedPackage
8092                // did not require an ABI, in which case we have to adjust scannedPackage to match
8093                // the ABI of the set (which is the same as requirer's ABI)
8094                adjustedAbi = requirer.primaryCpuAbiString;
8095                if (scannedPackage != null) {
8096                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8097                }
8098            } else {
8099                // requirer == null implies that we're updating all ABIs in the set to
8100                // match scannedPackage.
8101                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8102            }
8103
8104            for (PackageSetting ps : packagesForUser) {
8105                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8106                    if (ps.primaryCpuAbiString != null) {
8107                        continue;
8108                    }
8109
8110                    ps.primaryCpuAbiString = adjustedAbi;
8111                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8112                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8113                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8114                        mInstaller.rmdex(ps.codePathString,
8115                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8116                    }
8117                }
8118            }
8119        }
8120    }
8121
8122    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8123        synchronized (mPackages) {
8124            mResolverReplaced = true;
8125            // Set up information for custom user intent resolution activity.
8126            mResolveActivity.applicationInfo = pkg.applicationInfo;
8127            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8128            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8129            mResolveActivity.processName = pkg.applicationInfo.packageName;
8130            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8131            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8132                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8133            mResolveActivity.theme = 0;
8134            mResolveActivity.exported = true;
8135            mResolveActivity.enabled = true;
8136            mResolveInfo.activityInfo = mResolveActivity;
8137            mResolveInfo.priority = 0;
8138            mResolveInfo.preferredOrder = 0;
8139            mResolveInfo.match = 0;
8140            mResolveComponentName = mCustomResolverComponentName;
8141            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8142                    mResolveComponentName);
8143        }
8144    }
8145
8146    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8147        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8148
8149        // Set up information for ephemeral installer activity
8150        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8151        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8152        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8153        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8154        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8155        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8156                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8157        mEphemeralInstallerActivity.theme = 0;
8158        mEphemeralInstallerActivity.exported = true;
8159        mEphemeralInstallerActivity.enabled = true;
8160        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8161        mEphemeralInstallerInfo.priority = 0;
8162        mEphemeralInstallerInfo.preferredOrder = 0;
8163        mEphemeralInstallerInfo.match = 0;
8164
8165        if (DEBUG_EPHEMERAL) {
8166            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8167        }
8168    }
8169
8170    private static String calculateBundledApkRoot(final String codePathString) {
8171        final File codePath = new File(codePathString);
8172        final File codeRoot;
8173        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8174            codeRoot = Environment.getRootDirectory();
8175        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8176            codeRoot = Environment.getOemDirectory();
8177        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8178            codeRoot = Environment.getVendorDirectory();
8179        } else {
8180            // Unrecognized code path; take its top real segment as the apk root:
8181            // e.g. /something/app/blah.apk => /something
8182            try {
8183                File f = codePath.getCanonicalFile();
8184                File parent = f.getParentFile();    // non-null because codePath is a file
8185                File tmp;
8186                while ((tmp = parent.getParentFile()) != null) {
8187                    f = parent;
8188                    parent = tmp;
8189                }
8190                codeRoot = f;
8191                Slog.w(TAG, "Unrecognized code path "
8192                        + codePath + " - using " + codeRoot);
8193            } catch (IOException e) {
8194                // Can't canonicalize the code path -- shenanigans?
8195                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8196                return Environment.getRootDirectory().getPath();
8197            }
8198        }
8199        return codeRoot.getPath();
8200    }
8201
8202    /**
8203     * Derive and set the location of native libraries for the given package,
8204     * which varies depending on where and how the package was installed.
8205     */
8206    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8207        final ApplicationInfo info = pkg.applicationInfo;
8208        final String codePath = pkg.codePath;
8209        final File codeFile = new File(codePath);
8210        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8211        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8212
8213        info.nativeLibraryRootDir = null;
8214        info.nativeLibraryRootRequiresIsa = false;
8215        info.nativeLibraryDir = null;
8216        info.secondaryNativeLibraryDir = null;
8217
8218        if (isApkFile(codeFile)) {
8219            // Monolithic install
8220            if (bundledApp) {
8221                // If "/system/lib64/apkname" exists, assume that is the per-package
8222                // native library directory to use; otherwise use "/system/lib/apkname".
8223                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8224                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8225                        getPrimaryInstructionSet(info));
8226
8227                // This is a bundled system app so choose the path based on the ABI.
8228                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8229                // is just the default path.
8230                final String apkName = deriveCodePathName(codePath);
8231                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8232                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8233                        apkName).getAbsolutePath();
8234
8235                if (info.secondaryCpuAbi != null) {
8236                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8237                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8238                            secondaryLibDir, apkName).getAbsolutePath();
8239                }
8240            } else if (asecApp) {
8241                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8242                        .getAbsolutePath();
8243            } else {
8244                final String apkName = deriveCodePathName(codePath);
8245                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8246                        .getAbsolutePath();
8247            }
8248
8249            info.nativeLibraryRootRequiresIsa = false;
8250            info.nativeLibraryDir = info.nativeLibraryRootDir;
8251        } else {
8252            // Cluster install
8253            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8254            info.nativeLibraryRootRequiresIsa = true;
8255
8256            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8257                    getPrimaryInstructionSet(info)).getAbsolutePath();
8258
8259            if (info.secondaryCpuAbi != null) {
8260                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8261                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8262            }
8263        }
8264    }
8265
8266    /**
8267     * Calculate the abis and roots for a bundled app. These can uniquely
8268     * be determined from the contents of the system partition, i.e whether
8269     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8270     * of this information, and instead assume that the system was built
8271     * sensibly.
8272     */
8273    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8274                                           PackageSetting pkgSetting) {
8275        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8276
8277        // If "/system/lib64/apkname" exists, assume that is the per-package
8278        // native library directory to use; otherwise use "/system/lib/apkname".
8279        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8280        setBundledAppAbi(pkg, apkRoot, apkName);
8281        // pkgSetting might be null during rescan following uninstall of updates
8282        // to a bundled app, so accommodate that possibility.  The settings in
8283        // that case will be established later from the parsed package.
8284        //
8285        // If the settings aren't null, sync them up with what we've just derived.
8286        // note that apkRoot isn't stored in the package settings.
8287        if (pkgSetting != null) {
8288            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8289            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8290        }
8291    }
8292
8293    /**
8294     * Deduces the ABI of a bundled app and sets the relevant fields on the
8295     * parsed pkg object.
8296     *
8297     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8298     *        under which system libraries are installed.
8299     * @param apkName the name of the installed package.
8300     */
8301    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8302        final File codeFile = new File(pkg.codePath);
8303
8304        final boolean has64BitLibs;
8305        final boolean has32BitLibs;
8306        if (isApkFile(codeFile)) {
8307            // Monolithic install
8308            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8309            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8310        } else {
8311            // Cluster install
8312            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8313            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8314                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8315                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8316                has64BitLibs = (new File(rootDir, isa)).exists();
8317            } else {
8318                has64BitLibs = false;
8319            }
8320            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8321                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8322                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8323                has32BitLibs = (new File(rootDir, isa)).exists();
8324            } else {
8325                has32BitLibs = false;
8326            }
8327        }
8328
8329        if (has64BitLibs && !has32BitLibs) {
8330            // The package has 64 bit libs, but not 32 bit libs. Its primary
8331            // ABI should be 64 bit. We can safely assume here that the bundled
8332            // native libraries correspond to the most preferred ABI in the list.
8333
8334            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8335            pkg.applicationInfo.secondaryCpuAbi = null;
8336        } else if (has32BitLibs && !has64BitLibs) {
8337            // The package has 32 bit libs but not 64 bit libs. Its primary
8338            // ABI should be 32 bit.
8339
8340            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8341            pkg.applicationInfo.secondaryCpuAbi = null;
8342        } else if (has32BitLibs && has64BitLibs) {
8343            // The application has both 64 and 32 bit bundled libraries. We check
8344            // here that the app declares multiArch support, and warn if it doesn't.
8345            //
8346            // We will be lenient here and record both ABIs. The primary will be the
8347            // ABI that's higher on the list, i.e, a device that's configured to prefer
8348            // 64 bit apps will see a 64 bit primary ABI,
8349
8350            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8351                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8352            }
8353
8354            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8355                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8356                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8357            } else {
8358                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8359                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8360            }
8361        } else {
8362            pkg.applicationInfo.primaryCpuAbi = null;
8363            pkg.applicationInfo.secondaryCpuAbi = null;
8364        }
8365    }
8366
8367    private void killApplication(String pkgName, int appId, String reason) {
8368        // Request the ActivityManager to kill the process(only for existing packages)
8369        // so that we do not end up in a confused state while the user is still using the older
8370        // version of the application while the new one gets installed.
8371        IActivityManager am = ActivityManagerNative.getDefault();
8372        if (am != null) {
8373            try {
8374                am.killApplicationWithAppId(pkgName, appId, reason);
8375            } catch (RemoteException e) {
8376            }
8377        }
8378    }
8379
8380    void removePackageLI(PackageSetting ps, boolean chatty) {
8381        if (DEBUG_INSTALL) {
8382            if (chatty)
8383                Log.d(TAG, "Removing package " + ps.name);
8384        }
8385
8386        // writer
8387        synchronized (mPackages) {
8388            mPackages.remove(ps.name);
8389            final PackageParser.Package pkg = ps.pkg;
8390            if (pkg != null) {
8391                cleanPackageDataStructuresLILPw(pkg, chatty);
8392            }
8393        }
8394    }
8395
8396    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8397        if (DEBUG_INSTALL) {
8398            if (chatty)
8399                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8400        }
8401
8402        // writer
8403        synchronized (mPackages) {
8404            mPackages.remove(pkg.applicationInfo.packageName);
8405            cleanPackageDataStructuresLILPw(pkg, chatty);
8406        }
8407    }
8408
8409    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8410        int N = pkg.providers.size();
8411        StringBuilder r = null;
8412        int i;
8413        for (i=0; i<N; i++) {
8414            PackageParser.Provider p = pkg.providers.get(i);
8415            mProviders.removeProvider(p);
8416            if (p.info.authority == null) {
8417
8418                /* There was another ContentProvider with this authority when
8419                 * this app was installed so this authority is null,
8420                 * Ignore it as we don't have to unregister the provider.
8421                 */
8422                continue;
8423            }
8424            String names[] = p.info.authority.split(";");
8425            for (int j = 0; j < names.length; j++) {
8426                if (mProvidersByAuthority.get(names[j]) == p) {
8427                    mProvidersByAuthority.remove(names[j]);
8428                    if (DEBUG_REMOVE) {
8429                        if (chatty)
8430                            Log.d(TAG, "Unregistered content provider: " + names[j]
8431                                    + ", className = " + p.info.name + ", isSyncable = "
8432                                    + p.info.isSyncable);
8433                    }
8434                }
8435            }
8436            if (DEBUG_REMOVE && chatty) {
8437                if (r == null) {
8438                    r = new StringBuilder(256);
8439                } else {
8440                    r.append(' ');
8441                }
8442                r.append(p.info.name);
8443            }
8444        }
8445        if (r != null) {
8446            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8447        }
8448
8449        N = pkg.services.size();
8450        r = null;
8451        for (i=0; i<N; i++) {
8452            PackageParser.Service s = pkg.services.get(i);
8453            mServices.removeService(s);
8454            if (chatty) {
8455                if (r == null) {
8456                    r = new StringBuilder(256);
8457                } else {
8458                    r.append(' ');
8459                }
8460                r.append(s.info.name);
8461            }
8462        }
8463        if (r != null) {
8464            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8465        }
8466
8467        N = pkg.receivers.size();
8468        r = null;
8469        for (i=0; i<N; i++) {
8470            PackageParser.Activity a = pkg.receivers.get(i);
8471            mReceivers.removeActivity(a, "receiver");
8472            if (DEBUG_REMOVE && chatty) {
8473                if (r == null) {
8474                    r = new StringBuilder(256);
8475                } else {
8476                    r.append(' ');
8477                }
8478                r.append(a.info.name);
8479            }
8480        }
8481        if (r != null) {
8482            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8483        }
8484
8485        N = pkg.activities.size();
8486        r = null;
8487        for (i=0; i<N; i++) {
8488            PackageParser.Activity a = pkg.activities.get(i);
8489            mActivities.removeActivity(a, "activity");
8490            if (DEBUG_REMOVE && chatty) {
8491                if (r == null) {
8492                    r = new StringBuilder(256);
8493                } else {
8494                    r.append(' ');
8495                }
8496                r.append(a.info.name);
8497            }
8498        }
8499        if (r != null) {
8500            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8501        }
8502
8503        N = pkg.permissions.size();
8504        r = null;
8505        for (i=0; i<N; i++) {
8506            PackageParser.Permission p = pkg.permissions.get(i);
8507            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8508            if (bp == null) {
8509                bp = mSettings.mPermissionTrees.get(p.info.name);
8510            }
8511            if (bp != null && bp.perm == p) {
8512                bp.perm = null;
8513                if (DEBUG_REMOVE && chatty) {
8514                    if (r == null) {
8515                        r = new StringBuilder(256);
8516                    } else {
8517                        r.append(' ');
8518                    }
8519                    r.append(p.info.name);
8520                }
8521            }
8522            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8523                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8524                if (appOpPkgs != null) {
8525                    appOpPkgs.remove(pkg.packageName);
8526                }
8527            }
8528        }
8529        if (r != null) {
8530            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8531        }
8532
8533        N = pkg.requestedPermissions.size();
8534        r = null;
8535        for (i=0; i<N; i++) {
8536            String perm = pkg.requestedPermissions.get(i);
8537            BasePermission bp = mSettings.mPermissions.get(perm);
8538            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8539                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8540                if (appOpPkgs != null) {
8541                    appOpPkgs.remove(pkg.packageName);
8542                    if (appOpPkgs.isEmpty()) {
8543                        mAppOpPermissionPackages.remove(perm);
8544                    }
8545                }
8546            }
8547        }
8548        if (r != null) {
8549            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8550        }
8551
8552        N = pkg.instrumentation.size();
8553        r = null;
8554        for (i=0; i<N; i++) {
8555            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8556            mInstrumentation.remove(a.getComponentName());
8557            if (DEBUG_REMOVE && chatty) {
8558                if (r == null) {
8559                    r = new StringBuilder(256);
8560                } else {
8561                    r.append(' ');
8562                }
8563                r.append(a.info.name);
8564            }
8565        }
8566        if (r != null) {
8567            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8568        }
8569
8570        r = null;
8571        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8572            // Only system apps can hold shared libraries.
8573            if (pkg.libraryNames != null) {
8574                for (i=0; i<pkg.libraryNames.size(); i++) {
8575                    String name = pkg.libraryNames.get(i);
8576                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8577                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8578                        mSharedLibraries.remove(name);
8579                        if (DEBUG_REMOVE && chatty) {
8580                            if (r == null) {
8581                                r = new StringBuilder(256);
8582                            } else {
8583                                r.append(' ');
8584                            }
8585                            r.append(name);
8586                        }
8587                    }
8588                }
8589            }
8590        }
8591        if (r != null) {
8592            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8593        }
8594    }
8595
8596    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8597        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8598            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8599                return true;
8600            }
8601        }
8602        return false;
8603    }
8604
8605    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8606    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8607    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8608
8609    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8610            int flags) {
8611        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8612        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8613    }
8614
8615    private void updatePermissionsLPw(String changingPkg,
8616            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8617        // Make sure there are no dangling permission trees.
8618        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8619        while (it.hasNext()) {
8620            final BasePermission bp = it.next();
8621            if (bp.packageSetting == null) {
8622                // We may not yet have parsed the package, so just see if
8623                // we still know about its settings.
8624                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8625            }
8626            if (bp.packageSetting == null) {
8627                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8628                        + " from package " + bp.sourcePackage);
8629                it.remove();
8630            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8631                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8632                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8633                            + " from package " + bp.sourcePackage);
8634                    flags |= UPDATE_PERMISSIONS_ALL;
8635                    it.remove();
8636                }
8637            }
8638        }
8639
8640        // Make sure all dynamic permissions have been assigned to a package,
8641        // and make sure there are no dangling permissions.
8642        it = mSettings.mPermissions.values().iterator();
8643        while (it.hasNext()) {
8644            final BasePermission bp = it.next();
8645            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8646                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8647                        + bp.name + " pkg=" + bp.sourcePackage
8648                        + " info=" + bp.pendingInfo);
8649                if (bp.packageSetting == null && bp.pendingInfo != null) {
8650                    final BasePermission tree = findPermissionTreeLP(bp.name);
8651                    if (tree != null && tree.perm != null) {
8652                        bp.packageSetting = tree.packageSetting;
8653                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8654                                new PermissionInfo(bp.pendingInfo));
8655                        bp.perm.info.packageName = tree.perm.info.packageName;
8656                        bp.perm.info.name = bp.name;
8657                        bp.uid = tree.uid;
8658                    }
8659                }
8660            }
8661            if (bp.packageSetting == null) {
8662                // We may not yet have parsed the package, so just see if
8663                // we still know about its settings.
8664                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8665            }
8666            if (bp.packageSetting == null) {
8667                Slog.w(TAG, "Removing dangling permission: " + bp.name
8668                        + " from package " + bp.sourcePackage);
8669                it.remove();
8670            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8671                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8672                    Slog.i(TAG, "Removing old permission: " + bp.name
8673                            + " from package " + bp.sourcePackage);
8674                    flags |= UPDATE_PERMISSIONS_ALL;
8675                    it.remove();
8676                }
8677            }
8678        }
8679
8680        // Now update the permissions for all packages, in particular
8681        // replace the granted permissions of the system packages.
8682        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8683            for (PackageParser.Package pkg : mPackages.values()) {
8684                if (pkg != pkgInfo) {
8685                    // Only replace for packages on requested volume
8686                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8687                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8688                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8689                    grantPermissionsLPw(pkg, replace, changingPkg);
8690                }
8691            }
8692        }
8693
8694        if (pkgInfo != null) {
8695            // Only replace for packages on requested volume
8696            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8697            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8698                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8699            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8700        }
8701    }
8702
8703    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8704            String packageOfInterest) {
8705        // IMPORTANT: There are two types of permissions: install and runtime.
8706        // Install time permissions are granted when the app is installed to
8707        // all device users and users added in the future. Runtime permissions
8708        // are granted at runtime explicitly to specific users. Normal and signature
8709        // protected permissions are install time permissions. Dangerous permissions
8710        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8711        // otherwise they are runtime permissions. This function does not manage
8712        // runtime permissions except for the case an app targeting Lollipop MR1
8713        // being upgraded to target a newer SDK, in which case dangerous permissions
8714        // are transformed from install time to runtime ones.
8715
8716        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8717        if (ps == null) {
8718            return;
8719        }
8720
8721        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8722
8723        PermissionsState permissionsState = ps.getPermissionsState();
8724        PermissionsState origPermissions = permissionsState;
8725
8726        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8727
8728        boolean runtimePermissionsRevoked = false;
8729        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8730
8731        boolean changedInstallPermission = false;
8732
8733        if (replace) {
8734            ps.installPermissionsFixed = false;
8735            if (!ps.isSharedUser()) {
8736                origPermissions = new PermissionsState(permissionsState);
8737                permissionsState.reset();
8738            } else {
8739                // We need to know only about runtime permission changes since the
8740                // calling code always writes the install permissions state but
8741                // the runtime ones are written only if changed. The only cases of
8742                // changed runtime permissions here are promotion of an install to
8743                // runtime and revocation of a runtime from a shared user.
8744                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8745                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8746                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8747                    runtimePermissionsRevoked = true;
8748                }
8749            }
8750        }
8751
8752        permissionsState.setGlobalGids(mGlobalGids);
8753
8754        final int N = pkg.requestedPermissions.size();
8755        for (int i=0; i<N; i++) {
8756            final String name = pkg.requestedPermissions.get(i);
8757            final BasePermission bp = mSettings.mPermissions.get(name);
8758
8759            if (DEBUG_INSTALL) {
8760                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8761            }
8762
8763            if (bp == null || bp.packageSetting == null) {
8764                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8765                    Slog.w(TAG, "Unknown permission " + name
8766                            + " in package " + pkg.packageName);
8767                }
8768                continue;
8769            }
8770
8771            final String perm = bp.name;
8772            boolean allowedSig = false;
8773            int grant = GRANT_DENIED;
8774
8775            // Keep track of app op permissions.
8776            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8777                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8778                if (pkgs == null) {
8779                    pkgs = new ArraySet<>();
8780                    mAppOpPermissionPackages.put(bp.name, pkgs);
8781                }
8782                pkgs.add(pkg.packageName);
8783            }
8784
8785            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8786            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8787                    >= Build.VERSION_CODES.M;
8788            switch (level) {
8789                case PermissionInfo.PROTECTION_NORMAL: {
8790                    // For all apps normal permissions are install time ones.
8791                    grant = GRANT_INSTALL;
8792                } break;
8793
8794                case PermissionInfo.PROTECTION_DANGEROUS: {
8795                    // If a permission review is required for legacy apps we represent
8796                    // their permissions as always granted runtime ones since we need
8797                    // to keep the review required permission flag per user while an
8798                    // install permission's state is shared across all users.
8799                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8800                        // For legacy apps dangerous permissions are install time ones.
8801                        grant = GRANT_INSTALL;
8802                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8803                        // For legacy apps that became modern, install becomes runtime.
8804                        grant = GRANT_UPGRADE;
8805                    } else if (mPromoteSystemApps
8806                            && isSystemApp(ps)
8807                            && mExistingSystemPackages.contains(ps.name)) {
8808                        // For legacy system apps, install becomes runtime.
8809                        // We cannot check hasInstallPermission() for system apps since those
8810                        // permissions were granted implicitly and not persisted pre-M.
8811                        grant = GRANT_UPGRADE;
8812                    } else {
8813                        // For modern apps keep runtime permissions unchanged.
8814                        grant = GRANT_RUNTIME;
8815                    }
8816                } break;
8817
8818                case PermissionInfo.PROTECTION_SIGNATURE: {
8819                    // For all apps signature permissions are install time ones.
8820                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8821                    if (allowedSig) {
8822                        grant = GRANT_INSTALL;
8823                    }
8824                } break;
8825            }
8826
8827            if (DEBUG_INSTALL) {
8828                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8829            }
8830
8831            if (grant != GRANT_DENIED) {
8832                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8833                    // If this is an existing, non-system package, then
8834                    // we can't add any new permissions to it.
8835                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8836                        // Except...  if this is a permission that was added
8837                        // to the platform (note: need to only do this when
8838                        // updating the platform).
8839                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8840                            grant = GRANT_DENIED;
8841                        }
8842                    }
8843                }
8844
8845                switch (grant) {
8846                    case GRANT_INSTALL: {
8847                        // Revoke this as runtime permission to handle the case of
8848                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8849                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8850                            if (origPermissions.getRuntimePermissionState(
8851                                    bp.name, userId) != null) {
8852                                // Revoke the runtime permission and clear the flags.
8853                                origPermissions.revokeRuntimePermission(bp, userId);
8854                                origPermissions.updatePermissionFlags(bp, userId,
8855                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8856                                // If we revoked a permission permission, we have to write.
8857                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8858                                        changedRuntimePermissionUserIds, userId);
8859                            }
8860                        }
8861                        // Grant an install permission.
8862                        if (permissionsState.grantInstallPermission(bp) !=
8863                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8864                            changedInstallPermission = true;
8865                        }
8866                    } break;
8867
8868                    case GRANT_RUNTIME: {
8869                        // Grant previously granted runtime permissions.
8870                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8871                            PermissionState permissionState = origPermissions
8872                                    .getRuntimePermissionState(bp.name, userId);
8873                            int flags = permissionState != null
8874                                    ? permissionState.getFlags() : 0;
8875                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8876                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8877                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8878                                    // If we cannot put the permission as it was, we have to write.
8879                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8880                                            changedRuntimePermissionUserIds, userId);
8881                                }
8882                                // If the app supports runtime permissions no need for a review.
8883                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8884                                        && appSupportsRuntimePermissions
8885                                        && (flags & PackageManager
8886                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8887                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8888                                    // Since we changed the flags, we have to write.
8889                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8890                                            changedRuntimePermissionUserIds, userId);
8891                                }
8892                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8893                                    && !appSupportsRuntimePermissions) {
8894                                // For legacy apps that need a permission review, every new
8895                                // runtime permission is granted but it is pending a review.
8896                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8897                                    permissionsState.grantRuntimePermission(bp, userId);
8898                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8899                                    // We changed the permission and flags, hence have to write.
8900                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8901                                            changedRuntimePermissionUserIds, userId);
8902                                }
8903                            }
8904                            // Propagate the permission flags.
8905                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8906                        }
8907                    } break;
8908
8909                    case GRANT_UPGRADE: {
8910                        // Grant runtime permissions for a previously held install permission.
8911                        PermissionState permissionState = origPermissions
8912                                .getInstallPermissionState(bp.name);
8913                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8914
8915                        if (origPermissions.revokeInstallPermission(bp)
8916                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8917                            // We will be transferring the permission flags, so clear them.
8918                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8919                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8920                            changedInstallPermission = true;
8921                        }
8922
8923                        // If the permission is not to be promoted to runtime we ignore it and
8924                        // also its other flags as they are not applicable to install permissions.
8925                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8926                            for (int userId : currentUserIds) {
8927                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8928                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8929                                    // Transfer the permission flags.
8930                                    permissionsState.updatePermissionFlags(bp, userId,
8931                                            flags, flags);
8932                                    // If we granted the permission, we have to write.
8933                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8934                                            changedRuntimePermissionUserIds, userId);
8935                                }
8936                            }
8937                        }
8938                    } break;
8939
8940                    default: {
8941                        if (packageOfInterest == null
8942                                || packageOfInterest.equals(pkg.packageName)) {
8943                            Slog.w(TAG, "Not granting permission " + perm
8944                                    + " to package " + pkg.packageName
8945                                    + " because it was previously installed without");
8946                        }
8947                    } break;
8948                }
8949            } else {
8950                if (permissionsState.revokeInstallPermission(bp) !=
8951                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8952                    // Also drop the permission flags.
8953                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8954                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8955                    changedInstallPermission = true;
8956                    Slog.i(TAG, "Un-granting permission " + perm
8957                            + " from package " + pkg.packageName
8958                            + " (protectionLevel=" + bp.protectionLevel
8959                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8960                            + ")");
8961                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8962                    // Don't print warning for app op permissions, since it is fine for them
8963                    // not to be granted, there is a UI for the user to decide.
8964                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8965                        Slog.w(TAG, "Not granting permission " + perm
8966                                + " to package " + pkg.packageName
8967                                + " (protectionLevel=" + bp.protectionLevel
8968                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8969                                + ")");
8970                    }
8971                }
8972            }
8973        }
8974
8975        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8976                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8977            // This is the first that we have heard about this package, so the
8978            // permissions we have now selected are fixed until explicitly
8979            // changed.
8980            ps.installPermissionsFixed = true;
8981        }
8982
8983        // Persist the runtime permissions state for users with changes. If permissions
8984        // were revoked because no app in the shared user declares them we have to
8985        // write synchronously to avoid losing runtime permissions state.
8986        for (int userId : changedRuntimePermissionUserIds) {
8987            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8988        }
8989
8990        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8991    }
8992
8993    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8994        boolean allowed = false;
8995        final int NP = PackageParser.NEW_PERMISSIONS.length;
8996        for (int ip=0; ip<NP; ip++) {
8997            final PackageParser.NewPermissionInfo npi
8998                    = PackageParser.NEW_PERMISSIONS[ip];
8999            if (npi.name.equals(perm)
9000                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9001                allowed = true;
9002                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9003                        + pkg.packageName);
9004                break;
9005            }
9006        }
9007        return allowed;
9008    }
9009
9010    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9011            BasePermission bp, PermissionsState origPermissions) {
9012        boolean allowed;
9013        allowed = (compareSignatures(
9014                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9015                        == PackageManager.SIGNATURE_MATCH)
9016                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9017                        == PackageManager.SIGNATURE_MATCH);
9018        if (!allowed && (bp.protectionLevel
9019                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9020            if (isSystemApp(pkg)) {
9021                // For updated system applications, a system permission
9022                // is granted only if it had been defined by the original application.
9023                if (pkg.isUpdatedSystemApp()) {
9024                    final PackageSetting sysPs = mSettings
9025                            .getDisabledSystemPkgLPr(pkg.packageName);
9026                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9027                        // If the original was granted this permission, we take
9028                        // that grant decision as read and propagate it to the
9029                        // update.
9030                        if (sysPs.isPrivileged()) {
9031                            allowed = true;
9032                        }
9033                    } else {
9034                        // The system apk may have been updated with an older
9035                        // version of the one on the data partition, but which
9036                        // granted a new system permission that it didn't have
9037                        // before.  In this case we do want to allow the app to
9038                        // now get the new permission if the ancestral apk is
9039                        // privileged to get it.
9040                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9041                            for (int j=0;
9042                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9043                                if (perm.equals(
9044                                        sysPs.pkg.requestedPermissions.get(j))) {
9045                                    allowed = true;
9046                                    break;
9047                                }
9048                            }
9049                        }
9050                    }
9051                } else {
9052                    allowed = isPrivilegedApp(pkg);
9053                }
9054            }
9055        }
9056        if (!allowed) {
9057            if (!allowed && (bp.protectionLevel
9058                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9059                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9060                // If this was a previously normal/dangerous permission that got moved
9061                // to a system permission as part of the runtime permission redesign, then
9062                // we still want to blindly grant it to old apps.
9063                allowed = true;
9064            }
9065            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9066                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9067                // If this permission is to be granted to the system installer and
9068                // this app is an installer, then it gets the permission.
9069                allowed = true;
9070            }
9071            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9072                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9073                // If this permission is to be granted to the system verifier and
9074                // this app is a verifier, then it gets the permission.
9075                allowed = true;
9076            }
9077            if (!allowed && (bp.protectionLevel
9078                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9079                    && isSystemApp(pkg)) {
9080                // Any pre-installed system app is allowed to get this permission.
9081                allowed = true;
9082            }
9083            if (!allowed && (bp.protectionLevel
9084                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9085                // For development permissions, a development permission
9086                // is granted only if it was already granted.
9087                allowed = origPermissions.hasInstallPermission(perm);
9088            }
9089        }
9090        return allowed;
9091    }
9092
9093    final class ActivityIntentResolver
9094            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9095        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9096                boolean defaultOnly, int userId) {
9097            if (!sUserManager.exists(userId)) return null;
9098            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9099            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9100        }
9101
9102        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9103                int userId) {
9104            if (!sUserManager.exists(userId)) return null;
9105            mFlags = flags;
9106            return super.queryIntent(intent, resolvedType,
9107                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9108        }
9109
9110        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9111                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9112            if (!sUserManager.exists(userId)) return null;
9113            if (packageActivities == null) {
9114                return null;
9115            }
9116            mFlags = flags;
9117            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9118            final int N = packageActivities.size();
9119            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9120                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9121
9122            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9123            for (int i = 0; i < N; ++i) {
9124                intentFilters = packageActivities.get(i).intents;
9125                if (intentFilters != null && intentFilters.size() > 0) {
9126                    PackageParser.ActivityIntentInfo[] array =
9127                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9128                    intentFilters.toArray(array);
9129                    listCut.add(array);
9130                }
9131            }
9132            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9133        }
9134
9135        public final void addActivity(PackageParser.Activity a, String type) {
9136            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9137            mActivities.put(a.getComponentName(), a);
9138            if (DEBUG_SHOW_INFO)
9139                Log.v(
9140                TAG, "  " + type + " " +
9141                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9142            if (DEBUG_SHOW_INFO)
9143                Log.v(TAG, "    Class=" + a.info.name);
9144            final int NI = a.intents.size();
9145            for (int j=0; j<NI; j++) {
9146                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9147                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9148                    intent.setPriority(0);
9149                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9150                            + a.className + " with priority > 0, forcing to 0");
9151                }
9152                if (DEBUG_SHOW_INFO) {
9153                    Log.v(TAG, "    IntentFilter:");
9154                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9155                }
9156                if (!intent.debugCheck()) {
9157                    Log.w(TAG, "==> For Activity " + a.info.name);
9158                }
9159                addFilter(intent);
9160            }
9161        }
9162
9163        public final void removeActivity(PackageParser.Activity a, String type) {
9164            mActivities.remove(a.getComponentName());
9165            if (DEBUG_SHOW_INFO) {
9166                Log.v(TAG, "  " + type + " "
9167                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9168                                : a.info.name) + ":");
9169                Log.v(TAG, "    Class=" + a.info.name);
9170            }
9171            final int NI = a.intents.size();
9172            for (int j=0; j<NI; j++) {
9173                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9174                if (DEBUG_SHOW_INFO) {
9175                    Log.v(TAG, "    IntentFilter:");
9176                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9177                }
9178                removeFilter(intent);
9179            }
9180        }
9181
9182        @Override
9183        protected boolean allowFilterResult(
9184                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9185            ActivityInfo filterAi = filter.activity.info;
9186            for (int i=dest.size()-1; i>=0; i--) {
9187                ActivityInfo destAi = dest.get(i).activityInfo;
9188                if (destAi.name == filterAi.name
9189                        && destAi.packageName == filterAi.packageName) {
9190                    return false;
9191                }
9192            }
9193            return true;
9194        }
9195
9196        @Override
9197        protected ActivityIntentInfo[] newArray(int size) {
9198            return new ActivityIntentInfo[size];
9199        }
9200
9201        @Override
9202        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9203            if (!sUserManager.exists(userId)) return true;
9204            PackageParser.Package p = filter.activity.owner;
9205            if (p != null) {
9206                PackageSetting ps = (PackageSetting)p.mExtras;
9207                if (ps != null) {
9208                    // System apps are never considered stopped for purposes of
9209                    // filtering, because there may be no way for the user to
9210                    // actually re-launch them.
9211                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9212                            && ps.getStopped(userId);
9213                }
9214            }
9215            return false;
9216        }
9217
9218        @Override
9219        protected boolean isPackageForFilter(String packageName,
9220                PackageParser.ActivityIntentInfo info) {
9221            return packageName.equals(info.activity.owner.packageName);
9222        }
9223
9224        @Override
9225        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9226                int match, int userId) {
9227            if (!sUserManager.exists(userId)) return null;
9228            if (!mSettings.isEnabledAndVisibleLPr(info.activity.info, mFlags, userId)) {
9229                return null;
9230            }
9231            final PackageParser.Activity activity = info.activity;
9232            if (mSafeMode && (activity.info.applicationInfo.flags
9233                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9234                return null;
9235            }
9236            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9237            if (ps == null) {
9238                return null;
9239            }
9240            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9241                    ps.readUserState(userId), userId);
9242            if (ai == null) {
9243                return null;
9244            }
9245            final ResolveInfo res = new ResolveInfo();
9246            res.activityInfo = ai;
9247            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9248                res.filter = info;
9249            }
9250            if (info != null) {
9251                res.handleAllWebDataURI = info.handleAllWebDataURI();
9252            }
9253            res.priority = info.getPriority();
9254            res.preferredOrder = activity.owner.mPreferredOrder;
9255            //System.out.println("Result: " + res.activityInfo.className +
9256            //                   " = " + res.priority);
9257            res.match = match;
9258            res.isDefault = info.hasDefault;
9259            res.labelRes = info.labelRes;
9260            res.nonLocalizedLabel = info.nonLocalizedLabel;
9261            if (userNeedsBadging(userId)) {
9262                res.noResourceId = true;
9263            } else {
9264                res.icon = info.icon;
9265            }
9266            res.iconResourceId = info.icon;
9267            res.system = res.activityInfo.applicationInfo.isSystemApp();
9268            return res;
9269        }
9270
9271        @Override
9272        protected void sortResults(List<ResolveInfo> results) {
9273            Collections.sort(results, mResolvePrioritySorter);
9274        }
9275
9276        @Override
9277        protected void dumpFilter(PrintWriter out, String prefix,
9278                PackageParser.ActivityIntentInfo filter) {
9279            out.print(prefix); out.print(
9280                    Integer.toHexString(System.identityHashCode(filter.activity)));
9281                    out.print(' ');
9282                    filter.activity.printComponentShortName(out);
9283                    out.print(" filter ");
9284                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9285        }
9286
9287        @Override
9288        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9289            return filter.activity;
9290        }
9291
9292        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9293            PackageParser.Activity activity = (PackageParser.Activity)label;
9294            out.print(prefix); out.print(
9295                    Integer.toHexString(System.identityHashCode(activity)));
9296                    out.print(' ');
9297                    activity.printComponentShortName(out);
9298            if (count > 1) {
9299                out.print(" ("); out.print(count); out.print(" filters)");
9300            }
9301            out.println();
9302        }
9303
9304//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9305//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9306//            final List<ResolveInfo> retList = Lists.newArrayList();
9307//            while (i.hasNext()) {
9308//                final ResolveInfo resolveInfo = i.next();
9309//                if (isEnabledLP(resolveInfo.activityInfo)) {
9310//                    retList.add(resolveInfo);
9311//                }
9312//            }
9313//            return retList;
9314//        }
9315
9316        // Keys are String (activity class name), values are Activity.
9317        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9318                = new ArrayMap<ComponentName, PackageParser.Activity>();
9319        private int mFlags;
9320    }
9321
9322    private final class ServiceIntentResolver
9323            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9324        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9325                boolean defaultOnly, int userId) {
9326            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9327            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9328        }
9329
9330        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9331                int userId) {
9332            if (!sUserManager.exists(userId)) return null;
9333            mFlags = flags;
9334            return super.queryIntent(intent, resolvedType,
9335                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9336        }
9337
9338        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9339                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9340            if (!sUserManager.exists(userId)) return null;
9341            if (packageServices == null) {
9342                return null;
9343            }
9344            mFlags = flags;
9345            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9346            final int N = packageServices.size();
9347            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9348                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9349
9350            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9351            for (int i = 0; i < N; ++i) {
9352                intentFilters = packageServices.get(i).intents;
9353                if (intentFilters != null && intentFilters.size() > 0) {
9354                    PackageParser.ServiceIntentInfo[] array =
9355                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9356                    intentFilters.toArray(array);
9357                    listCut.add(array);
9358                }
9359            }
9360            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9361        }
9362
9363        public final void addService(PackageParser.Service s) {
9364            mServices.put(s.getComponentName(), s);
9365            if (DEBUG_SHOW_INFO) {
9366                Log.v(TAG, "  "
9367                        + (s.info.nonLocalizedLabel != null
9368                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9369                Log.v(TAG, "    Class=" + s.info.name);
9370            }
9371            final int NI = s.intents.size();
9372            int j;
9373            for (j=0; j<NI; j++) {
9374                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9375                if (DEBUG_SHOW_INFO) {
9376                    Log.v(TAG, "    IntentFilter:");
9377                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9378                }
9379                if (!intent.debugCheck()) {
9380                    Log.w(TAG, "==> For Service " + s.info.name);
9381                }
9382                addFilter(intent);
9383            }
9384        }
9385
9386        public final void removeService(PackageParser.Service s) {
9387            mServices.remove(s.getComponentName());
9388            if (DEBUG_SHOW_INFO) {
9389                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9390                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9391                Log.v(TAG, "    Class=" + s.info.name);
9392            }
9393            final int NI = s.intents.size();
9394            int j;
9395            for (j=0; j<NI; j++) {
9396                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9397                if (DEBUG_SHOW_INFO) {
9398                    Log.v(TAG, "    IntentFilter:");
9399                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9400                }
9401                removeFilter(intent);
9402            }
9403        }
9404
9405        @Override
9406        protected boolean allowFilterResult(
9407                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9408            ServiceInfo filterSi = filter.service.info;
9409            for (int i=dest.size()-1; i>=0; i--) {
9410                ServiceInfo destAi = dest.get(i).serviceInfo;
9411                if (destAi.name == filterSi.name
9412                        && destAi.packageName == filterSi.packageName) {
9413                    return false;
9414                }
9415            }
9416            return true;
9417        }
9418
9419        @Override
9420        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9421            return new PackageParser.ServiceIntentInfo[size];
9422        }
9423
9424        @Override
9425        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9426            if (!sUserManager.exists(userId)) return true;
9427            PackageParser.Package p = filter.service.owner;
9428            if (p != null) {
9429                PackageSetting ps = (PackageSetting)p.mExtras;
9430                if (ps != null) {
9431                    // System apps are never considered stopped for purposes of
9432                    // filtering, because there may be no way for the user to
9433                    // actually re-launch them.
9434                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9435                            && ps.getStopped(userId);
9436                }
9437            }
9438            return false;
9439        }
9440
9441        @Override
9442        protected boolean isPackageForFilter(String packageName,
9443                PackageParser.ServiceIntentInfo info) {
9444            return packageName.equals(info.service.owner.packageName);
9445        }
9446
9447        @Override
9448        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9449                int match, int userId) {
9450            if (!sUserManager.exists(userId)) return null;
9451            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9452            if (!mSettings.isEnabledAndVisibleLPr(info.service.info, mFlags, userId)) {
9453                return null;
9454            }
9455            final PackageParser.Service service = info.service;
9456            if (mSafeMode && (service.info.applicationInfo.flags
9457                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9458                return null;
9459            }
9460            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9461            if (ps == null) {
9462                return null;
9463            }
9464            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9465                    ps.readUserState(userId), userId);
9466            if (si == null) {
9467                return null;
9468            }
9469            final ResolveInfo res = new ResolveInfo();
9470            res.serviceInfo = si;
9471            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9472                res.filter = filter;
9473            }
9474            res.priority = info.getPriority();
9475            res.preferredOrder = service.owner.mPreferredOrder;
9476            res.match = match;
9477            res.isDefault = info.hasDefault;
9478            res.labelRes = info.labelRes;
9479            res.nonLocalizedLabel = info.nonLocalizedLabel;
9480            res.icon = info.icon;
9481            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9482            return res;
9483        }
9484
9485        @Override
9486        protected void sortResults(List<ResolveInfo> results) {
9487            Collections.sort(results, mResolvePrioritySorter);
9488        }
9489
9490        @Override
9491        protected void dumpFilter(PrintWriter out, String prefix,
9492                PackageParser.ServiceIntentInfo filter) {
9493            out.print(prefix); out.print(
9494                    Integer.toHexString(System.identityHashCode(filter.service)));
9495                    out.print(' ');
9496                    filter.service.printComponentShortName(out);
9497                    out.print(" filter ");
9498                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9499        }
9500
9501        @Override
9502        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9503            return filter.service;
9504        }
9505
9506        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9507            PackageParser.Service service = (PackageParser.Service)label;
9508            out.print(prefix); out.print(
9509                    Integer.toHexString(System.identityHashCode(service)));
9510                    out.print(' ');
9511                    service.printComponentShortName(out);
9512            if (count > 1) {
9513                out.print(" ("); out.print(count); out.print(" filters)");
9514            }
9515            out.println();
9516        }
9517
9518//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9519//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9520//            final List<ResolveInfo> retList = Lists.newArrayList();
9521//            while (i.hasNext()) {
9522//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9523//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9524//                    retList.add(resolveInfo);
9525//                }
9526//            }
9527//            return retList;
9528//        }
9529
9530        // Keys are String (activity class name), values are Activity.
9531        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9532                = new ArrayMap<ComponentName, PackageParser.Service>();
9533        private int mFlags;
9534    };
9535
9536    private final class ProviderIntentResolver
9537            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9538        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9539                boolean defaultOnly, int userId) {
9540            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9541            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9542        }
9543
9544        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9545                int userId) {
9546            if (!sUserManager.exists(userId))
9547                return null;
9548            mFlags = flags;
9549            return super.queryIntent(intent, resolvedType,
9550                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9551        }
9552
9553        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9554                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9555            if (!sUserManager.exists(userId))
9556                return null;
9557            if (packageProviders == null) {
9558                return null;
9559            }
9560            mFlags = flags;
9561            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9562            final int N = packageProviders.size();
9563            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9564                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9565
9566            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9567            for (int i = 0; i < N; ++i) {
9568                intentFilters = packageProviders.get(i).intents;
9569                if (intentFilters != null && intentFilters.size() > 0) {
9570                    PackageParser.ProviderIntentInfo[] array =
9571                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9572                    intentFilters.toArray(array);
9573                    listCut.add(array);
9574                }
9575            }
9576            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9577        }
9578
9579        public final void addProvider(PackageParser.Provider p) {
9580            if (mProviders.containsKey(p.getComponentName())) {
9581                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9582                return;
9583            }
9584
9585            mProviders.put(p.getComponentName(), p);
9586            if (DEBUG_SHOW_INFO) {
9587                Log.v(TAG, "  "
9588                        + (p.info.nonLocalizedLabel != null
9589                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9590                Log.v(TAG, "    Class=" + p.info.name);
9591            }
9592            final int NI = p.intents.size();
9593            int j;
9594            for (j = 0; j < NI; j++) {
9595                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9596                if (DEBUG_SHOW_INFO) {
9597                    Log.v(TAG, "    IntentFilter:");
9598                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9599                }
9600                if (!intent.debugCheck()) {
9601                    Log.w(TAG, "==> For Provider " + p.info.name);
9602                }
9603                addFilter(intent);
9604            }
9605        }
9606
9607        public final void removeProvider(PackageParser.Provider p) {
9608            mProviders.remove(p.getComponentName());
9609            if (DEBUG_SHOW_INFO) {
9610                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9611                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9612                Log.v(TAG, "    Class=" + p.info.name);
9613            }
9614            final int NI = p.intents.size();
9615            int j;
9616            for (j = 0; j < NI; j++) {
9617                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9618                if (DEBUG_SHOW_INFO) {
9619                    Log.v(TAG, "    IntentFilter:");
9620                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9621                }
9622                removeFilter(intent);
9623            }
9624        }
9625
9626        @Override
9627        protected boolean allowFilterResult(
9628                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9629            ProviderInfo filterPi = filter.provider.info;
9630            for (int i = dest.size() - 1; i >= 0; i--) {
9631                ProviderInfo destPi = dest.get(i).providerInfo;
9632                if (destPi.name == filterPi.name
9633                        && destPi.packageName == filterPi.packageName) {
9634                    return false;
9635                }
9636            }
9637            return true;
9638        }
9639
9640        @Override
9641        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9642            return new PackageParser.ProviderIntentInfo[size];
9643        }
9644
9645        @Override
9646        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9647            if (!sUserManager.exists(userId))
9648                return true;
9649            PackageParser.Package p = filter.provider.owner;
9650            if (p != null) {
9651                PackageSetting ps = (PackageSetting) p.mExtras;
9652                if (ps != null) {
9653                    // System apps are never considered stopped for purposes of
9654                    // filtering, because there may be no way for the user to
9655                    // actually re-launch them.
9656                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9657                            && ps.getStopped(userId);
9658                }
9659            }
9660            return false;
9661        }
9662
9663        @Override
9664        protected boolean isPackageForFilter(String packageName,
9665                PackageParser.ProviderIntentInfo info) {
9666            return packageName.equals(info.provider.owner.packageName);
9667        }
9668
9669        @Override
9670        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9671                int match, int userId) {
9672            if (!sUserManager.exists(userId))
9673                return null;
9674            final PackageParser.ProviderIntentInfo info = filter;
9675            if (!mSettings.isEnabledAndVisibleLPr(info.provider.info, mFlags, userId)) {
9676                return null;
9677            }
9678            final PackageParser.Provider provider = info.provider;
9679            if (mSafeMode && (provider.info.applicationInfo.flags
9680                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9681                return null;
9682            }
9683            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9684            if (ps == null) {
9685                return null;
9686            }
9687            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9688                    ps.readUserState(userId), userId);
9689            if (pi == null) {
9690                return null;
9691            }
9692            final ResolveInfo res = new ResolveInfo();
9693            res.providerInfo = pi;
9694            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9695                res.filter = filter;
9696            }
9697            res.priority = info.getPriority();
9698            res.preferredOrder = provider.owner.mPreferredOrder;
9699            res.match = match;
9700            res.isDefault = info.hasDefault;
9701            res.labelRes = info.labelRes;
9702            res.nonLocalizedLabel = info.nonLocalizedLabel;
9703            res.icon = info.icon;
9704            res.system = res.providerInfo.applicationInfo.isSystemApp();
9705            return res;
9706        }
9707
9708        @Override
9709        protected void sortResults(List<ResolveInfo> results) {
9710            Collections.sort(results, mResolvePrioritySorter);
9711        }
9712
9713        @Override
9714        protected void dumpFilter(PrintWriter out, String prefix,
9715                PackageParser.ProviderIntentInfo filter) {
9716            out.print(prefix);
9717            out.print(
9718                    Integer.toHexString(System.identityHashCode(filter.provider)));
9719            out.print(' ');
9720            filter.provider.printComponentShortName(out);
9721            out.print(" filter ");
9722            out.println(Integer.toHexString(System.identityHashCode(filter)));
9723        }
9724
9725        @Override
9726        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9727            return filter.provider;
9728        }
9729
9730        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9731            PackageParser.Provider provider = (PackageParser.Provider)label;
9732            out.print(prefix); out.print(
9733                    Integer.toHexString(System.identityHashCode(provider)));
9734                    out.print(' ');
9735                    provider.printComponentShortName(out);
9736            if (count > 1) {
9737                out.print(" ("); out.print(count); out.print(" filters)");
9738            }
9739            out.println();
9740        }
9741
9742        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9743                = new ArrayMap<ComponentName, PackageParser.Provider>();
9744        private int mFlags;
9745    }
9746
9747    private static final class EphemeralIntentResolver
9748            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9749        @Override
9750        protected EphemeralResolveIntentInfo[] newArray(int size) {
9751            return new EphemeralResolveIntentInfo[size];
9752        }
9753
9754        @Override
9755        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9756            return true;
9757        }
9758
9759        @Override
9760        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9761                int userId) {
9762            if (!sUserManager.exists(userId)) {
9763                return null;
9764            }
9765            return info.getEphemeralResolveInfo();
9766        }
9767    }
9768
9769    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9770            new Comparator<ResolveInfo>() {
9771        public int compare(ResolveInfo r1, ResolveInfo r2) {
9772            int v1 = r1.priority;
9773            int v2 = r2.priority;
9774            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9775            if (v1 != v2) {
9776                return (v1 > v2) ? -1 : 1;
9777            }
9778            v1 = r1.preferredOrder;
9779            v2 = r2.preferredOrder;
9780            if (v1 != v2) {
9781                return (v1 > v2) ? -1 : 1;
9782            }
9783            if (r1.isDefault != r2.isDefault) {
9784                return r1.isDefault ? -1 : 1;
9785            }
9786            v1 = r1.match;
9787            v2 = r2.match;
9788            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9789            if (v1 != v2) {
9790                return (v1 > v2) ? -1 : 1;
9791            }
9792            if (r1.system != r2.system) {
9793                return r1.system ? -1 : 1;
9794            }
9795            if (r1.activityInfo != null) {
9796                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9797            }
9798            if (r1.serviceInfo != null) {
9799                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9800            }
9801            if (r1.providerInfo != null) {
9802                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9803            }
9804            return 0;
9805        }
9806    };
9807
9808    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9809            new Comparator<ProviderInfo>() {
9810        public int compare(ProviderInfo p1, ProviderInfo p2) {
9811            final int v1 = p1.initOrder;
9812            final int v2 = p2.initOrder;
9813            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9814        }
9815    };
9816
9817    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9818            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9819            final int[] userIds) {
9820        mHandler.post(new Runnable() {
9821            @Override
9822            public void run() {
9823                try {
9824                    final IActivityManager am = ActivityManagerNative.getDefault();
9825                    if (am == null) return;
9826                    final int[] resolvedUserIds;
9827                    if (userIds == null) {
9828                        resolvedUserIds = am.getRunningUserIds();
9829                    } else {
9830                        resolvedUserIds = userIds;
9831                    }
9832                    for (int id : resolvedUserIds) {
9833                        final Intent intent = new Intent(action,
9834                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9835                        if (extras != null) {
9836                            intent.putExtras(extras);
9837                        }
9838                        if (targetPkg != null) {
9839                            intent.setPackage(targetPkg);
9840                        }
9841                        // Modify the UID when posting to other users
9842                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9843                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9844                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9845                            intent.putExtra(Intent.EXTRA_UID, uid);
9846                        }
9847                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9848                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9849                        if (DEBUG_BROADCASTS) {
9850                            RuntimeException here = new RuntimeException("here");
9851                            here.fillInStackTrace();
9852                            Slog.d(TAG, "Sending to user " + id + ": "
9853                                    + intent.toShortString(false, true, false, false)
9854                                    + " " + intent.getExtras(), here);
9855                        }
9856                        am.broadcastIntent(null, intent, null, finishedReceiver,
9857                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9858                                null, finishedReceiver != null, false, id);
9859                    }
9860                } catch (RemoteException ex) {
9861                }
9862            }
9863        });
9864    }
9865
9866    /**
9867     * Check if the external storage media is available. This is true if there
9868     * is a mounted external storage medium or if the external storage is
9869     * emulated.
9870     */
9871    private boolean isExternalMediaAvailable() {
9872        return mMediaMounted || Environment.isExternalStorageEmulated();
9873    }
9874
9875    @Override
9876    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9877        // writer
9878        synchronized (mPackages) {
9879            if (!isExternalMediaAvailable()) {
9880                // If the external storage is no longer mounted at this point,
9881                // the caller may not have been able to delete all of this
9882                // packages files and can not delete any more.  Bail.
9883                return null;
9884            }
9885            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9886            if (lastPackage != null) {
9887                pkgs.remove(lastPackage);
9888            }
9889            if (pkgs.size() > 0) {
9890                return pkgs.get(0);
9891            }
9892        }
9893        return null;
9894    }
9895
9896    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9897        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9898                userId, andCode ? 1 : 0, packageName);
9899        if (mSystemReady) {
9900            msg.sendToTarget();
9901        } else {
9902            if (mPostSystemReadyMessages == null) {
9903                mPostSystemReadyMessages = new ArrayList<>();
9904            }
9905            mPostSystemReadyMessages.add(msg);
9906        }
9907    }
9908
9909    void startCleaningPackages() {
9910        // reader
9911        synchronized (mPackages) {
9912            if (!isExternalMediaAvailable()) {
9913                return;
9914            }
9915            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9916                return;
9917            }
9918        }
9919        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9920        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9921        IActivityManager am = ActivityManagerNative.getDefault();
9922        if (am != null) {
9923            try {
9924                am.startService(null, intent, null, mContext.getOpPackageName(),
9925                        UserHandle.USER_SYSTEM);
9926            } catch (RemoteException e) {
9927            }
9928        }
9929    }
9930
9931    @Override
9932    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9933            int installFlags, String installerPackageName, VerificationParams verificationParams,
9934            String packageAbiOverride) {
9935        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9936                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9937    }
9938
9939    @Override
9940    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9941            int installFlags, String installerPackageName, VerificationParams verificationParams,
9942            String packageAbiOverride, int userId) {
9943        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9944
9945        final int callingUid = Binder.getCallingUid();
9946        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9947
9948        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9949            try {
9950                if (observer != null) {
9951                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9952                }
9953            } catch (RemoteException re) {
9954            }
9955            return;
9956        }
9957
9958        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9959            installFlags |= PackageManager.INSTALL_FROM_ADB;
9960
9961        } else {
9962            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9963            // about installerPackageName.
9964
9965            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9966            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9967        }
9968
9969        UserHandle user;
9970        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9971            user = UserHandle.ALL;
9972        } else {
9973            user = new UserHandle(userId);
9974        }
9975
9976        // Only system components can circumvent runtime permissions when installing.
9977        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9978                && mContext.checkCallingOrSelfPermission(Manifest.permission
9979                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9980            throw new SecurityException("You need the "
9981                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9982                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9983        }
9984
9985        verificationParams.setInstallerUid(callingUid);
9986
9987        final File originFile = new File(originPath);
9988        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9989
9990        final Message msg = mHandler.obtainMessage(INIT_COPY);
9991        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9992                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9993        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9994        msg.obj = params;
9995
9996        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9997                System.identityHashCode(msg.obj));
9998        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9999                System.identityHashCode(msg.obj));
10000
10001        mHandler.sendMessage(msg);
10002    }
10003
10004    void installStage(String packageName, File stagedDir, String stagedCid,
10005            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10006            String installerPackageName, int installerUid, UserHandle user) {
10007        if (DEBUG_EPHEMERAL) {
10008            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10009                Slog.d(TAG, "Ephemeral install of " + packageName);
10010            }
10011        }
10012        final VerificationParams verifParams = new VerificationParams(
10013                null, sessionParams.originatingUri, sessionParams.referrerUri,
10014                sessionParams.originatingUid, null);
10015        verifParams.setInstallerUid(installerUid);
10016
10017        final OriginInfo origin;
10018        if (stagedDir != null) {
10019            origin = OriginInfo.fromStagedFile(stagedDir);
10020        } else {
10021            origin = OriginInfo.fromStagedContainer(stagedCid);
10022        }
10023
10024        final Message msg = mHandler.obtainMessage(INIT_COPY);
10025        final InstallParams params = new InstallParams(origin, null, observer,
10026                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10027                verifParams, user, sessionParams.abiOverride,
10028                sessionParams.grantedRuntimePermissions);
10029        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10030        msg.obj = params;
10031
10032        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10033                System.identityHashCode(msg.obj));
10034        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10035                System.identityHashCode(msg.obj));
10036
10037        mHandler.sendMessage(msg);
10038    }
10039
10040    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10041        Bundle extras = new Bundle(1);
10042        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10043
10044        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10045                packageName, extras, 0, null, null, new int[] {userId});
10046        try {
10047            IActivityManager am = ActivityManagerNative.getDefault();
10048            final boolean isSystem =
10049                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10050            if (isSystem && am.isUserRunning(userId, 0)) {
10051                // The just-installed/enabled app is bundled on the system, so presumed
10052                // to be able to run automatically without needing an explicit launch.
10053                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10054                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10055                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10056                        .setPackage(packageName);
10057                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10058                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10059            }
10060        } catch (RemoteException e) {
10061            // shouldn't happen
10062            Slog.w(TAG, "Unable to bootstrap installed package", e);
10063        }
10064    }
10065
10066    @Override
10067    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10068            int userId) {
10069        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10070        PackageSetting pkgSetting;
10071        final int uid = Binder.getCallingUid();
10072        enforceCrossUserPermission(uid, userId, true, true,
10073                "setApplicationHiddenSetting for user " + userId);
10074
10075        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10076            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10077            return false;
10078        }
10079
10080        long callingId = Binder.clearCallingIdentity();
10081        try {
10082            boolean sendAdded = false;
10083            boolean sendRemoved = false;
10084            // writer
10085            synchronized (mPackages) {
10086                pkgSetting = mSettings.mPackages.get(packageName);
10087                if (pkgSetting == null) {
10088                    return false;
10089                }
10090                if (pkgSetting.getHidden(userId) != hidden) {
10091                    pkgSetting.setHidden(hidden, userId);
10092                    mSettings.writePackageRestrictionsLPr(userId);
10093                    if (hidden) {
10094                        sendRemoved = true;
10095                    } else {
10096                        sendAdded = true;
10097                    }
10098                }
10099            }
10100            if (sendAdded) {
10101                sendPackageAddedForUser(packageName, pkgSetting, userId);
10102                return true;
10103            }
10104            if (sendRemoved) {
10105                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10106                        "hiding pkg");
10107                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10108                return true;
10109            }
10110        } finally {
10111            Binder.restoreCallingIdentity(callingId);
10112        }
10113        return false;
10114    }
10115
10116    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10117            int userId) {
10118        final PackageRemovedInfo info = new PackageRemovedInfo();
10119        info.removedPackage = packageName;
10120        info.removedUsers = new int[] {userId};
10121        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10122        info.sendBroadcast(false, false, false);
10123    }
10124
10125    /**
10126     * Returns true if application is not found or there was an error. Otherwise it returns
10127     * the hidden state of the package for the given user.
10128     */
10129    @Override
10130    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10131        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10132        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10133                false, "getApplicationHidden for user " + userId);
10134        PackageSetting pkgSetting;
10135        long callingId = Binder.clearCallingIdentity();
10136        try {
10137            // writer
10138            synchronized (mPackages) {
10139                pkgSetting = mSettings.mPackages.get(packageName);
10140                if (pkgSetting == null) {
10141                    return true;
10142                }
10143                return pkgSetting.getHidden(userId);
10144            }
10145        } finally {
10146            Binder.restoreCallingIdentity(callingId);
10147        }
10148    }
10149
10150    /**
10151     * @hide
10152     */
10153    @Override
10154    public int installExistingPackageAsUser(String packageName, int userId) {
10155        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10156                null);
10157        PackageSetting pkgSetting;
10158        final int uid = Binder.getCallingUid();
10159        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10160                + userId);
10161        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10162            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10163        }
10164
10165        long callingId = Binder.clearCallingIdentity();
10166        try {
10167            boolean sendAdded = false;
10168
10169            // writer
10170            synchronized (mPackages) {
10171                pkgSetting = mSettings.mPackages.get(packageName);
10172                if (pkgSetting == null) {
10173                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10174                }
10175                if (!pkgSetting.getInstalled(userId)) {
10176                    pkgSetting.setInstalled(true, userId);
10177                    pkgSetting.setHidden(false, userId);
10178                    mSettings.writePackageRestrictionsLPr(userId);
10179                    sendAdded = true;
10180                }
10181            }
10182
10183            if (sendAdded) {
10184                sendPackageAddedForUser(packageName, pkgSetting, userId);
10185            }
10186        } finally {
10187            Binder.restoreCallingIdentity(callingId);
10188        }
10189
10190        return PackageManager.INSTALL_SUCCEEDED;
10191    }
10192
10193    boolean isUserRestricted(int userId, String restrictionKey) {
10194        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10195        if (restrictions.getBoolean(restrictionKey, false)) {
10196            Log.w(TAG, "User is restricted: " + restrictionKey);
10197            return true;
10198        }
10199        return false;
10200    }
10201
10202    @Override
10203    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10204        mContext.enforceCallingOrSelfPermission(
10205                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10206                "Only package verification agents can verify applications");
10207
10208        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10209        final PackageVerificationResponse response = new PackageVerificationResponse(
10210                verificationCode, Binder.getCallingUid());
10211        msg.arg1 = id;
10212        msg.obj = response;
10213        mHandler.sendMessage(msg);
10214    }
10215
10216    @Override
10217    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10218            long millisecondsToDelay) {
10219        mContext.enforceCallingOrSelfPermission(
10220                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10221                "Only package verification agents can extend verification timeouts");
10222
10223        final PackageVerificationState state = mPendingVerification.get(id);
10224        final PackageVerificationResponse response = new PackageVerificationResponse(
10225                verificationCodeAtTimeout, Binder.getCallingUid());
10226
10227        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10228            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10229        }
10230        if (millisecondsToDelay < 0) {
10231            millisecondsToDelay = 0;
10232        }
10233        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10234                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10235            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10236        }
10237
10238        if ((state != null) && !state.timeoutExtended()) {
10239            state.extendTimeout();
10240
10241            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10242            msg.arg1 = id;
10243            msg.obj = response;
10244            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10245        }
10246    }
10247
10248    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10249            int verificationCode, UserHandle user) {
10250        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10251        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10252        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10253        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10254        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10255
10256        mContext.sendBroadcastAsUser(intent, user,
10257                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10258    }
10259
10260    private ComponentName matchComponentForVerifier(String packageName,
10261            List<ResolveInfo> receivers) {
10262        ActivityInfo targetReceiver = null;
10263
10264        final int NR = receivers.size();
10265        for (int i = 0; i < NR; i++) {
10266            final ResolveInfo info = receivers.get(i);
10267            if (info.activityInfo == null) {
10268                continue;
10269            }
10270
10271            if (packageName.equals(info.activityInfo.packageName)) {
10272                targetReceiver = info.activityInfo;
10273                break;
10274            }
10275        }
10276
10277        if (targetReceiver == null) {
10278            return null;
10279        }
10280
10281        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10282    }
10283
10284    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10285            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10286        if (pkgInfo.verifiers.length == 0) {
10287            return null;
10288        }
10289
10290        final int N = pkgInfo.verifiers.length;
10291        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10292        for (int i = 0; i < N; i++) {
10293            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10294
10295            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10296                    receivers);
10297            if (comp == null) {
10298                continue;
10299            }
10300
10301            final int verifierUid = getUidForVerifier(verifierInfo);
10302            if (verifierUid == -1) {
10303                continue;
10304            }
10305
10306            if (DEBUG_VERIFY) {
10307                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10308                        + " with the correct signature");
10309            }
10310            sufficientVerifiers.add(comp);
10311            verificationState.addSufficientVerifier(verifierUid);
10312        }
10313
10314        return sufficientVerifiers;
10315    }
10316
10317    private int getUidForVerifier(VerifierInfo verifierInfo) {
10318        synchronized (mPackages) {
10319            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10320            if (pkg == null) {
10321                return -1;
10322            } else if (pkg.mSignatures.length != 1) {
10323                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10324                        + " has more than one signature; ignoring");
10325                return -1;
10326            }
10327
10328            /*
10329             * If the public key of the package's signature does not match
10330             * our expected public key, then this is a different package and
10331             * we should skip.
10332             */
10333
10334            final byte[] expectedPublicKey;
10335            try {
10336                final Signature verifierSig = pkg.mSignatures[0];
10337                final PublicKey publicKey = verifierSig.getPublicKey();
10338                expectedPublicKey = publicKey.getEncoded();
10339            } catch (CertificateException e) {
10340                return -1;
10341            }
10342
10343            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10344
10345            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10346                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10347                        + " does not have the expected public key; ignoring");
10348                return -1;
10349            }
10350
10351            return pkg.applicationInfo.uid;
10352        }
10353    }
10354
10355    @Override
10356    public void finishPackageInstall(int token) {
10357        enforceSystemOrRoot("Only the system is allowed to finish installs");
10358
10359        if (DEBUG_INSTALL) {
10360            Slog.v(TAG, "BM finishing package install for " + token);
10361        }
10362        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10363
10364        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10365        mHandler.sendMessage(msg);
10366    }
10367
10368    /**
10369     * Get the verification agent timeout.
10370     *
10371     * @return verification timeout in milliseconds
10372     */
10373    private long getVerificationTimeout() {
10374        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10375                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10376                DEFAULT_VERIFICATION_TIMEOUT);
10377    }
10378
10379    /**
10380     * Get the default verification agent response code.
10381     *
10382     * @return default verification response code
10383     */
10384    private int getDefaultVerificationResponse() {
10385        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10386                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10387                DEFAULT_VERIFICATION_RESPONSE);
10388    }
10389
10390    /**
10391     * Check whether or not package verification has been enabled.
10392     *
10393     * @return true if verification should be performed
10394     */
10395    private boolean isVerificationEnabled(int userId, int installFlags) {
10396        if (!DEFAULT_VERIFY_ENABLE) {
10397            return false;
10398        }
10399        // TODO: fix b/25118622; don't bypass verification
10400        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10401            return false;
10402        }
10403        // Ephemeral apps don't get the full verification treatment
10404        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10405            if (DEBUG_EPHEMERAL) {
10406                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10407            }
10408            return false;
10409        }
10410
10411        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10412
10413        // Check if installing from ADB
10414        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10415            // Do not run verification in a test harness environment
10416            if (ActivityManager.isRunningInTestHarness()) {
10417                return false;
10418            }
10419            if (ensureVerifyAppsEnabled) {
10420                return true;
10421            }
10422            // Check if the developer does not want package verification for ADB installs
10423            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10424                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10425                return false;
10426            }
10427        }
10428
10429        if (ensureVerifyAppsEnabled) {
10430            return true;
10431        }
10432
10433        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10434                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10435    }
10436
10437    @Override
10438    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10439            throws RemoteException {
10440        mContext.enforceCallingOrSelfPermission(
10441                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10442                "Only intentfilter verification agents can verify applications");
10443
10444        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10445        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10446                Binder.getCallingUid(), verificationCode, failedDomains);
10447        msg.arg1 = id;
10448        msg.obj = response;
10449        mHandler.sendMessage(msg);
10450    }
10451
10452    @Override
10453    public int getIntentVerificationStatus(String packageName, int userId) {
10454        synchronized (mPackages) {
10455            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10456        }
10457    }
10458
10459    @Override
10460    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10461        mContext.enforceCallingOrSelfPermission(
10462                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10463
10464        boolean result = false;
10465        synchronized (mPackages) {
10466            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10467        }
10468        if (result) {
10469            scheduleWritePackageRestrictionsLocked(userId);
10470        }
10471        return result;
10472    }
10473
10474    @Override
10475    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10476        synchronized (mPackages) {
10477            return mSettings.getIntentFilterVerificationsLPr(packageName);
10478        }
10479    }
10480
10481    @Override
10482    public List<IntentFilter> getAllIntentFilters(String packageName) {
10483        if (TextUtils.isEmpty(packageName)) {
10484            return Collections.<IntentFilter>emptyList();
10485        }
10486        synchronized (mPackages) {
10487            PackageParser.Package pkg = mPackages.get(packageName);
10488            if (pkg == null || pkg.activities == null) {
10489                return Collections.<IntentFilter>emptyList();
10490            }
10491            final int count = pkg.activities.size();
10492            ArrayList<IntentFilter> result = new ArrayList<>();
10493            for (int n=0; n<count; n++) {
10494                PackageParser.Activity activity = pkg.activities.get(n);
10495                if (activity.intents != null && activity.intents.size() > 0) {
10496                    result.addAll(activity.intents);
10497                }
10498            }
10499            return result;
10500        }
10501    }
10502
10503    @Override
10504    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10505        mContext.enforceCallingOrSelfPermission(
10506                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10507
10508        synchronized (mPackages) {
10509            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10510            if (packageName != null) {
10511                result |= updateIntentVerificationStatus(packageName,
10512                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10513                        userId);
10514                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10515                        packageName, userId);
10516            }
10517            return result;
10518        }
10519    }
10520
10521    @Override
10522    public String getDefaultBrowserPackageName(int userId) {
10523        synchronized (mPackages) {
10524            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10525        }
10526    }
10527
10528    /**
10529     * Get the "allow unknown sources" setting.
10530     *
10531     * @return the current "allow unknown sources" setting
10532     */
10533    private int getUnknownSourcesSettings() {
10534        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10535                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10536                -1);
10537    }
10538
10539    @Override
10540    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10541        final int uid = Binder.getCallingUid();
10542        // writer
10543        synchronized (mPackages) {
10544            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10545            if (targetPackageSetting == null) {
10546                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10547            }
10548
10549            PackageSetting installerPackageSetting;
10550            if (installerPackageName != null) {
10551                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10552                if (installerPackageSetting == null) {
10553                    throw new IllegalArgumentException("Unknown installer package: "
10554                            + installerPackageName);
10555                }
10556            } else {
10557                installerPackageSetting = null;
10558            }
10559
10560            Signature[] callerSignature;
10561            Object obj = mSettings.getUserIdLPr(uid);
10562            if (obj != null) {
10563                if (obj instanceof SharedUserSetting) {
10564                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10565                } else if (obj instanceof PackageSetting) {
10566                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10567                } else {
10568                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10569                }
10570            } else {
10571                throw new SecurityException("Unknown calling uid " + uid);
10572            }
10573
10574            // Verify: can't set installerPackageName to a package that is
10575            // not signed with the same cert as the caller.
10576            if (installerPackageSetting != null) {
10577                if (compareSignatures(callerSignature,
10578                        installerPackageSetting.signatures.mSignatures)
10579                        != PackageManager.SIGNATURE_MATCH) {
10580                    throw new SecurityException(
10581                            "Caller does not have same cert as new installer package "
10582                            + installerPackageName);
10583                }
10584            }
10585
10586            // Verify: if target already has an installer package, it must
10587            // be signed with the same cert as the caller.
10588            if (targetPackageSetting.installerPackageName != null) {
10589                PackageSetting setting = mSettings.mPackages.get(
10590                        targetPackageSetting.installerPackageName);
10591                // If the currently set package isn't valid, then it's always
10592                // okay to change it.
10593                if (setting != null) {
10594                    if (compareSignatures(callerSignature,
10595                            setting.signatures.mSignatures)
10596                            != PackageManager.SIGNATURE_MATCH) {
10597                        throw new SecurityException(
10598                                "Caller does not have same cert as old installer package "
10599                                + targetPackageSetting.installerPackageName);
10600                    }
10601                }
10602            }
10603
10604            // Okay!
10605            targetPackageSetting.installerPackageName = installerPackageName;
10606            scheduleWriteSettingsLocked();
10607        }
10608    }
10609
10610    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10611        // Queue up an async operation since the package installation may take a little while.
10612        mHandler.post(new Runnable() {
10613            public void run() {
10614                mHandler.removeCallbacks(this);
10615                 // Result object to be returned
10616                PackageInstalledInfo res = new PackageInstalledInfo();
10617                res.returnCode = currentStatus;
10618                res.uid = -1;
10619                res.pkg = null;
10620                res.removedInfo = new PackageRemovedInfo();
10621                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10622                    args.doPreInstall(res.returnCode);
10623                    synchronized (mInstallLock) {
10624                        installPackageTracedLI(args, res);
10625                    }
10626                    args.doPostInstall(res.returnCode, res.uid);
10627                }
10628
10629                // A restore should be performed at this point if (a) the install
10630                // succeeded, (b) the operation is not an update, and (c) the new
10631                // package has not opted out of backup participation.
10632                final boolean update = res.removedInfo.removedPackage != null;
10633                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10634                boolean doRestore = !update
10635                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10636
10637                // Set up the post-install work request bookkeeping.  This will be used
10638                // and cleaned up by the post-install event handling regardless of whether
10639                // there's a restore pass performed.  Token values are >= 1.
10640                int token;
10641                if (mNextInstallToken < 0) mNextInstallToken = 1;
10642                token = mNextInstallToken++;
10643
10644                PostInstallData data = new PostInstallData(args, res);
10645                mRunningInstalls.put(token, data);
10646                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10647
10648                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10649                    // Pass responsibility to the Backup Manager.  It will perform a
10650                    // restore if appropriate, then pass responsibility back to the
10651                    // Package Manager to run the post-install observer callbacks
10652                    // and broadcasts.
10653                    IBackupManager bm = IBackupManager.Stub.asInterface(
10654                            ServiceManager.getService(Context.BACKUP_SERVICE));
10655                    if (bm != null) {
10656                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10657                                + " to BM for possible restore");
10658                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10659                        try {
10660                            // TODO: http://b/22388012
10661                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10662                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10663                            } else {
10664                                doRestore = false;
10665                            }
10666                        } catch (RemoteException e) {
10667                            // can't happen; the backup manager is local
10668                        } catch (Exception e) {
10669                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10670                            doRestore = false;
10671                        }
10672                    } else {
10673                        Slog.e(TAG, "Backup Manager not found!");
10674                        doRestore = false;
10675                    }
10676                }
10677
10678                if (!doRestore) {
10679                    // No restore possible, or the Backup Manager was mysteriously not
10680                    // available -- just fire the post-install work request directly.
10681                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10682
10683                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10684
10685                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10686                    mHandler.sendMessage(msg);
10687                }
10688            }
10689        });
10690    }
10691
10692    private abstract class HandlerParams {
10693        private static final int MAX_RETRIES = 4;
10694
10695        /**
10696         * Number of times startCopy() has been attempted and had a non-fatal
10697         * error.
10698         */
10699        private int mRetries = 0;
10700
10701        /** User handle for the user requesting the information or installation. */
10702        private final UserHandle mUser;
10703        String traceMethod;
10704        int traceCookie;
10705
10706        HandlerParams(UserHandle user) {
10707            mUser = user;
10708        }
10709
10710        UserHandle getUser() {
10711            return mUser;
10712        }
10713
10714        HandlerParams setTraceMethod(String traceMethod) {
10715            this.traceMethod = traceMethod;
10716            return this;
10717        }
10718
10719        HandlerParams setTraceCookie(int traceCookie) {
10720            this.traceCookie = traceCookie;
10721            return this;
10722        }
10723
10724        final boolean startCopy() {
10725            boolean res;
10726            try {
10727                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10728
10729                if (++mRetries > MAX_RETRIES) {
10730                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10731                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10732                    handleServiceError();
10733                    return false;
10734                } else {
10735                    handleStartCopy();
10736                    res = true;
10737                }
10738            } catch (RemoteException e) {
10739                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10740                mHandler.sendEmptyMessage(MCS_RECONNECT);
10741                res = false;
10742            }
10743            handleReturnCode();
10744            return res;
10745        }
10746
10747        final void serviceError() {
10748            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10749            handleServiceError();
10750            handleReturnCode();
10751        }
10752
10753        abstract void handleStartCopy() throws RemoteException;
10754        abstract void handleServiceError();
10755        abstract void handleReturnCode();
10756    }
10757
10758    class MeasureParams extends HandlerParams {
10759        private final PackageStats mStats;
10760        private boolean mSuccess;
10761
10762        private final IPackageStatsObserver mObserver;
10763
10764        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10765            super(new UserHandle(stats.userHandle));
10766            mObserver = observer;
10767            mStats = stats;
10768        }
10769
10770        @Override
10771        public String toString() {
10772            return "MeasureParams{"
10773                + Integer.toHexString(System.identityHashCode(this))
10774                + " " + mStats.packageName + "}";
10775        }
10776
10777        @Override
10778        void handleStartCopy() throws RemoteException {
10779            synchronized (mInstallLock) {
10780                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10781            }
10782
10783            if (mSuccess) {
10784                final boolean mounted;
10785                if (Environment.isExternalStorageEmulated()) {
10786                    mounted = true;
10787                } else {
10788                    final String status = Environment.getExternalStorageState();
10789                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10790                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10791                }
10792
10793                if (mounted) {
10794                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10795
10796                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10797                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10798
10799                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10800                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10801
10802                    // Always subtract cache size, since it's a subdirectory
10803                    mStats.externalDataSize -= mStats.externalCacheSize;
10804
10805                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10806                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10807
10808                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10809                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10810                }
10811            }
10812        }
10813
10814        @Override
10815        void handleReturnCode() {
10816            if (mObserver != null) {
10817                try {
10818                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10819                } catch (RemoteException e) {
10820                    Slog.i(TAG, "Observer no longer exists.");
10821                }
10822            }
10823        }
10824
10825        @Override
10826        void handleServiceError() {
10827            Slog.e(TAG, "Could not measure application " + mStats.packageName
10828                            + " external storage");
10829        }
10830    }
10831
10832    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10833            throws RemoteException {
10834        long result = 0;
10835        for (File path : paths) {
10836            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10837        }
10838        return result;
10839    }
10840
10841    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10842        for (File path : paths) {
10843            try {
10844                mcs.clearDirectory(path.getAbsolutePath());
10845            } catch (RemoteException e) {
10846            }
10847        }
10848    }
10849
10850    static class OriginInfo {
10851        /**
10852         * Location where install is coming from, before it has been
10853         * copied/renamed into place. This could be a single monolithic APK
10854         * file, or a cluster directory. This location may be untrusted.
10855         */
10856        final File file;
10857        final String cid;
10858
10859        /**
10860         * Flag indicating that {@link #file} or {@link #cid} has already been
10861         * staged, meaning downstream users don't need to defensively copy the
10862         * contents.
10863         */
10864        final boolean staged;
10865
10866        /**
10867         * Flag indicating that {@link #file} or {@link #cid} is an already
10868         * installed app that is being moved.
10869         */
10870        final boolean existing;
10871
10872        final String resolvedPath;
10873        final File resolvedFile;
10874
10875        static OriginInfo fromNothing() {
10876            return new OriginInfo(null, null, false, false);
10877        }
10878
10879        static OriginInfo fromUntrustedFile(File file) {
10880            return new OriginInfo(file, null, false, false);
10881        }
10882
10883        static OriginInfo fromExistingFile(File file) {
10884            return new OriginInfo(file, null, false, true);
10885        }
10886
10887        static OriginInfo fromStagedFile(File file) {
10888            return new OriginInfo(file, null, true, false);
10889        }
10890
10891        static OriginInfo fromStagedContainer(String cid) {
10892            return new OriginInfo(null, cid, true, false);
10893        }
10894
10895        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10896            this.file = file;
10897            this.cid = cid;
10898            this.staged = staged;
10899            this.existing = existing;
10900
10901            if (cid != null) {
10902                resolvedPath = PackageHelper.getSdDir(cid);
10903                resolvedFile = new File(resolvedPath);
10904            } else if (file != null) {
10905                resolvedPath = file.getAbsolutePath();
10906                resolvedFile = file;
10907            } else {
10908                resolvedPath = null;
10909                resolvedFile = null;
10910            }
10911        }
10912    }
10913
10914    static class MoveInfo {
10915        final int moveId;
10916        final String fromUuid;
10917        final String toUuid;
10918        final String packageName;
10919        final String dataAppName;
10920        final int appId;
10921        final String seinfo;
10922
10923        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10924                String dataAppName, int appId, String seinfo) {
10925            this.moveId = moveId;
10926            this.fromUuid = fromUuid;
10927            this.toUuid = toUuid;
10928            this.packageName = packageName;
10929            this.dataAppName = dataAppName;
10930            this.appId = appId;
10931            this.seinfo = seinfo;
10932        }
10933    }
10934
10935    class InstallParams extends HandlerParams {
10936        final OriginInfo origin;
10937        final MoveInfo move;
10938        final IPackageInstallObserver2 observer;
10939        int installFlags;
10940        final String installerPackageName;
10941        final String volumeUuid;
10942        final VerificationParams verificationParams;
10943        private InstallArgs mArgs;
10944        private int mRet;
10945        final String packageAbiOverride;
10946        final String[] grantedRuntimePermissions;
10947
10948        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10949                int installFlags, String installerPackageName, String volumeUuid,
10950                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10951                String[] grantedPermissions) {
10952            super(user);
10953            this.origin = origin;
10954            this.move = move;
10955            this.observer = observer;
10956            this.installFlags = installFlags;
10957            this.installerPackageName = installerPackageName;
10958            this.volumeUuid = volumeUuid;
10959            this.verificationParams = verificationParams;
10960            this.packageAbiOverride = packageAbiOverride;
10961            this.grantedRuntimePermissions = grantedPermissions;
10962        }
10963
10964        @Override
10965        public String toString() {
10966            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10967                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10968        }
10969
10970        public ManifestDigest getManifestDigest() {
10971            if (verificationParams == null) {
10972                return null;
10973            }
10974            return verificationParams.getManifestDigest();
10975        }
10976
10977        private int installLocationPolicy(PackageInfoLite pkgLite) {
10978            String packageName = pkgLite.packageName;
10979            int installLocation = pkgLite.installLocation;
10980            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10981            // reader
10982            synchronized (mPackages) {
10983                PackageParser.Package pkg = mPackages.get(packageName);
10984                if (pkg != null) {
10985                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10986                        // Check for downgrading.
10987                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10988                            try {
10989                                checkDowngrade(pkg, pkgLite);
10990                            } catch (PackageManagerException e) {
10991                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10992                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10993                            }
10994                        }
10995                        // Check for updated system application.
10996                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10997                            if (onSd) {
10998                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10999                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11000                            }
11001                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11002                        } else {
11003                            if (onSd) {
11004                                // Install flag overrides everything.
11005                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11006                            }
11007                            // If current upgrade specifies particular preference
11008                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11009                                // Application explicitly specified internal.
11010                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11011                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11012                                // App explictly prefers external. Let policy decide
11013                            } else {
11014                                // Prefer previous location
11015                                if (isExternal(pkg)) {
11016                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11017                                }
11018                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11019                            }
11020                        }
11021                    } else {
11022                        // Invalid install. Return error code
11023                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11024                    }
11025                }
11026            }
11027            // All the special cases have been taken care of.
11028            // Return result based on recommended install location.
11029            if (onSd) {
11030                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11031            }
11032            return pkgLite.recommendedInstallLocation;
11033        }
11034
11035        /*
11036         * Invoke remote method to get package information and install
11037         * location values. Override install location based on default
11038         * policy if needed and then create install arguments based
11039         * on the install location.
11040         */
11041        public void handleStartCopy() throws RemoteException {
11042            int ret = PackageManager.INSTALL_SUCCEEDED;
11043
11044            // If we're already staged, we've firmly committed to an install location
11045            if (origin.staged) {
11046                if (origin.file != null) {
11047                    installFlags |= PackageManager.INSTALL_INTERNAL;
11048                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11049                } else if (origin.cid != null) {
11050                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11051                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11052                } else {
11053                    throw new IllegalStateException("Invalid stage location");
11054                }
11055            }
11056
11057            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11058            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11059            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11060            PackageInfoLite pkgLite = null;
11061
11062            if (onInt && onSd) {
11063                // Check if both bits are set.
11064                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11065                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11066            } else if (onSd && ephemeral) {
11067                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11068                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11069            } else {
11070                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11071                        packageAbiOverride);
11072
11073                if (DEBUG_EPHEMERAL && ephemeral) {
11074                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11075                }
11076
11077                /*
11078                 * If we have too little free space, try to free cache
11079                 * before giving up.
11080                 */
11081                if (!origin.staged && pkgLite.recommendedInstallLocation
11082                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11083                    // TODO: focus freeing disk space on the target device
11084                    final StorageManager storage = StorageManager.from(mContext);
11085                    final long lowThreshold = storage.getStorageLowBytes(
11086                            Environment.getDataDirectory());
11087
11088                    final long sizeBytes = mContainerService.calculateInstalledSize(
11089                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11090
11091                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11092                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11093                                installFlags, packageAbiOverride);
11094                    }
11095
11096                    /*
11097                     * The cache free must have deleted the file we
11098                     * downloaded to install.
11099                     *
11100                     * TODO: fix the "freeCache" call to not delete
11101                     *       the file we care about.
11102                     */
11103                    if (pkgLite.recommendedInstallLocation
11104                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11105                        pkgLite.recommendedInstallLocation
11106                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11107                    }
11108                }
11109            }
11110
11111            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11112                int loc = pkgLite.recommendedInstallLocation;
11113                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11114                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11115                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11116                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11117                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11118                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11119                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11120                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11121                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11122                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11123                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11124                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11125                } else {
11126                    // Override with defaults if needed.
11127                    loc = installLocationPolicy(pkgLite);
11128                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11129                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11130                    } else if (!onSd && !onInt) {
11131                        // Override install location with flags
11132                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11133                            // Set the flag to install on external media.
11134                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11135                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11136                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11137                            if (DEBUG_EPHEMERAL) {
11138                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11139                            }
11140                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11141                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11142                                    |PackageManager.INSTALL_INTERNAL);
11143                        } else {
11144                            // Make sure the flag for installing on external
11145                            // media is unset
11146                            installFlags |= PackageManager.INSTALL_INTERNAL;
11147                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11148                        }
11149                    }
11150                }
11151            }
11152
11153            final InstallArgs args = createInstallArgs(this);
11154            mArgs = args;
11155
11156            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11157                // TODO: http://b/22976637
11158                // Apps installed for "all" users use the device owner to verify the app
11159                UserHandle verifierUser = getUser();
11160                if (verifierUser == UserHandle.ALL) {
11161                    verifierUser = UserHandle.SYSTEM;
11162                }
11163
11164                /*
11165                 * Determine if we have any installed package verifiers. If we
11166                 * do, then we'll defer to them to verify the packages.
11167                 */
11168                final int requiredUid = mRequiredVerifierPackage == null ? -1
11169                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11170                if (!origin.existing && requiredUid != -1
11171                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11172                    final Intent verification = new Intent(
11173                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11174                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11175                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11176                            PACKAGE_MIME_TYPE);
11177                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11178
11179                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11180                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11181                            verifierUser.getIdentifier());
11182
11183                    if (DEBUG_VERIFY) {
11184                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11185                                + verification.toString() + " with " + pkgLite.verifiers.length
11186                                + " optional verifiers");
11187                    }
11188
11189                    final int verificationId = mPendingVerificationToken++;
11190
11191                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11192
11193                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11194                            installerPackageName);
11195
11196                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11197                            installFlags);
11198
11199                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11200                            pkgLite.packageName);
11201
11202                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11203                            pkgLite.versionCode);
11204
11205                    if (verificationParams != null) {
11206                        if (verificationParams.getVerificationURI() != null) {
11207                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11208                                 verificationParams.getVerificationURI());
11209                        }
11210                        if (verificationParams.getOriginatingURI() != null) {
11211                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11212                                  verificationParams.getOriginatingURI());
11213                        }
11214                        if (verificationParams.getReferrer() != null) {
11215                            verification.putExtra(Intent.EXTRA_REFERRER,
11216                                  verificationParams.getReferrer());
11217                        }
11218                        if (verificationParams.getOriginatingUid() >= 0) {
11219                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11220                                  verificationParams.getOriginatingUid());
11221                        }
11222                        if (verificationParams.getInstallerUid() >= 0) {
11223                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11224                                  verificationParams.getInstallerUid());
11225                        }
11226                    }
11227
11228                    final PackageVerificationState verificationState = new PackageVerificationState(
11229                            requiredUid, args);
11230
11231                    mPendingVerification.append(verificationId, verificationState);
11232
11233                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11234                            receivers, verificationState);
11235
11236                    /*
11237                     * If any sufficient verifiers were listed in the package
11238                     * manifest, attempt to ask them.
11239                     */
11240                    if (sufficientVerifiers != null) {
11241                        final int N = sufficientVerifiers.size();
11242                        if (N == 0) {
11243                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11244                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11245                        } else {
11246                            for (int i = 0; i < N; i++) {
11247                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11248
11249                                final Intent sufficientIntent = new Intent(verification);
11250                                sufficientIntent.setComponent(verifierComponent);
11251                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11252                            }
11253                        }
11254                    }
11255
11256                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11257                            mRequiredVerifierPackage, receivers);
11258                    if (ret == PackageManager.INSTALL_SUCCEEDED
11259                            && mRequiredVerifierPackage != null) {
11260                        Trace.asyncTraceBegin(
11261                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11262                        /*
11263                         * Send the intent to the required verification agent,
11264                         * but only start the verification timeout after the
11265                         * target BroadcastReceivers have run.
11266                         */
11267                        verification.setComponent(requiredVerifierComponent);
11268                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11269                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11270                                new BroadcastReceiver() {
11271                                    @Override
11272                                    public void onReceive(Context context, Intent intent) {
11273                                        final Message msg = mHandler
11274                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11275                                        msg.arg1 = verificationId;
11276                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11277                                    }
11278                                }, null, 0, null, null);
11279
11280                        /*
11281                         * We don't want the copy to proceed until verification
11282                         * succeeds, so null out this field.
11283                         */
11284                        mArgs = null;
11285                    }
11286                } else {
11287                    /*
11288                     * No package verification is enabled, so immediately start
11289                     * the remote call to initiate copy using temporary file.
11290                     */
11291                    ret = args.copyApk(mContainerService, true);
11292                }
11293            }
11294
11295            mRet = ret;
11296        }
11297
11298        @Override
11299        void handleReturnCode() {
11300            // If mArgs is null, then MCS couldn't be reached. When it
11301            // reconnects, it will try again to install. At that point, this
11302            // will succeed.
11303            if (mArgs != null) {
11304                processPendingInstall(mArgs, mRet);
11305            }
11306        }
11307
11308        @Override
11309        void handleServiceError() {
11310            mArgs = createInstallArgs(this);
11311            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11312        }
11313
11314        public boolean isForwardLocked() {
11315            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11316        }
11317    }
11318
11319    /**
11320     * Used during creation of InstallArgs
11321     *
11322     * @param installFlags package installation flags
11323     * @return true if should be installed on external storage
11324     */
11325    private static boolean installOnExternalAsec(int installFlags) {
11326        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11327            return false;
11328        }
11329        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11330            return true;
11331        }
11332        return false;
11333    }
11334
11335    /**
11336     * Used during creation of InstallArgs
11337     *
11338     * @param installFlags package installation flags
11339     * @return true if should be installed as forward locked
11340     */
11341    private static boolean installForwardLocked(int installFlags) {
11342        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11343    }
11344
11345    private InstallArgs createInstallArgs(InstallParams params) {
11346        if (params.move != null) {
11347            return new MoveInstallArgs(params);
11348        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11349            return new AsecInstallArgs(params);
11350        } else {
11351            return new FileInstallArgs(params);
11352        }
11353    }
11354
11355    /**
11356     * Create args that describe an existing installed package. Typically used
11357     * when cleaning up old installs, or used as a move source.
11358     */
11359    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11360            String resourcePath, String[] instructionSets) {
11361        final boolean isInAsec;
11362        if (installOnExternalAsec(installFlags)) {
11363            /* Apps on SD card are always in ASEC containers. */
11364            isInAsec = true;
11365        } else if (installForwardLocked(installFlags)
11366                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11367            /*
11368             * Forward-locked apps are only in ASEC containers if they're the
11369             * new style
11370             */
11371            isInAsec = true;
11372        } else {
11373            isInAsec = false;
11374        }
11375
11376        if (isInAsec) {
11377            return new AsecInstallArgs(codePath, instructionSets,
11378                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11379        } else {
11380            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11381        }
11382    }
11383
11384    static abstract class InstallArgs {
11385        /** @see InstallParams#origin */
11386        final OriginInfo origin;
11387        /** @see InstallParams#move */
11388        final MoveInfo move;
11389
11390        final IPackageInstallObserver2 observer;
11391        // Always refers to PackageManager flags only
11392        final int installFlags;
11393        final String installerPackageName;
11394        final String volumeUuid;
11395        final ManifestDigest manifestDigest;
11396        final UserHandle user;
11397        final String abiOverride;
11398        final String[] installGrantPermissions;
11399        /** If non-null, drop an async trace when the install completes */
11400        final String traceMethod;
11401        final int traceCookie;
11402
11403        // The list of instruction sets supported by this app. This is currently
11404        // only used during the rmdex() phase to clean up resources. We can get rid of this
11405        // if we move dex files under the common app path.
11406        /* nullable */ String[] instructionSets;
11407
11408        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11409                int installFlags, String installerPackageName, String volumeUuid,
11410                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11411                String abiOverride, String[] installGrantPermissions,
11412                String traceMethod, int traceCookie) {
11413            this.origin = origin;
11414            this.move = move;
11415            this.installFlags = installFlags;
11416            this.observer = observer;
11417            this.installerPackageName = installerPackageName;
11418            this.volumeUuid = volumeUuid;
11419            this.manifestDigest = manifestDigest;
11420            this.user = user;
11421            this.instructionSets = instructionSets;
11422            this.abiOverride = abiOverride;
11423            this.installGrantPermissions = installGrantPermissions;
11424            this.traceMethod = traceMethod;
11425            this.traceCookie = traceCookie;
11426        }
11427
11428        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11429        abstract int doPreInstall(int status);
11430
11431        /**
11432         * Rename package into final resting place. All paths on the given
11433         * scanned package should be updated to reflect the rename.
11434         */
11435        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11436        abstract int doPostInstall(int status, int uid);
11437
11438        /** @see PackageSettingBase#codePathString */
11439        abstract String getCodePath();
11440        /** @see PackageSettingBase#resourcePathString */
11441        abstract String getResourcePath();
11442
11443        // Need installer lock especially for dex file removal.
11444        abstract void cleanUpResourcesLI();
11445        abstract boolean doPostDeleteLI(boolean delete);
11446
11447        /**
11448         * Called before the source arguments are copied. This is used mostly
11449         * for MoveParams when it needs to read the source file to put it in the
11450         * destination.
11451         */
11452        int doPreCopy() {
11453            return PackageManager.INSTALL_SUCCEEDED;
11454        }
11455
11456        /**
11457         * Called after the source arguments are copied. This is used mostly for
11458         * MoveParams when it needs to read the source file to put it in the
11459         * destination.
11460         *
11461         * @return
11462         */
11463        int doPostCopy(int uid) {
11464            return PackageManager.INSTALL_SUCCEEDED;
11465        }
11466
11467        protected boolean isFwdLocked() {
11468            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11469        }
11470
11471        protected boolean isExternalAsec() {
11472            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11473        }
11474
11475        protected boolean isEphemeral() {
11476            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11477        }
11478
11479        UserHandle getUser() {
11480            return user;
11481        }
11482    }
11483
11484    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11485        if (!allCodePaths.isEmpty()) {
11486            if (instructionSets == null) {
11487                throw new IllegalStateException("instructionSet == null");
11488            }
11489            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11490            for (String codePath : allCodePaths) {
11491                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11492                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11493                    if (retCode < 0) {
11494                        Slog.w(TAG, "Couldn't remove dex file for package: "
11495                                + " at location " + codePath + ", retcode=" + retCode);
11496                        // we don't consider this to be a failure of the core package deletion
11497                    }
11498                }
11499            }
11500        }
11501    }
11502
11503    /**
11504     * Logic to handle installation of non-ASEC applications, including copying
11505     * and renaming logic.
11506     */
11507    class FileInstallArgs extends InstallArgs {
11508        private File codeFile;
11509        private File resourceFile;
11510
11511        // Example topology:
11512        // /data/app/com.example/base.apk
11513        // /data/app/com.example/split_foo.apk
11514        // /data/app/com.example/lib/arm/libfoo.so
11515        // /data/app/com.example/lib/arm64/libfoo.so
11516        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11517
11518        /** New install */
11519        FileInstallArgs(InstallParams params) {
11520            super(params.origin, params.move, params.observer, params.installFlags,
11521                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11522                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11523                    params.grantedRuntimePermissions,
11524                    params.traceMethod, params.traceCookie);
11525            if (isFwdLocked()) {
11526                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11527            }
11528        }
11529
11530        /** Existing install */
11531        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11532            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11533                    null, null, null, 0);
11534            this.codeFile = (codePath != null) ? new File(codePath) : null;
11535            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11536        }
11537
11538        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11539            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11540            try {
11541                return doCopyApk(imcs, temp);
11542            } finally {
11543                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11544            }
11545        }
11546
11547        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11548            if (origin.staged) {
11549                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11550                codeFile = origin.file;
11551                resourceFile = origin.file;
11552                return PackageManager.INSTALL_SUCCEEDED;
11553            }
11554
11555            try {
11556                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11557                final File tempDir =
11558                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11559                codeFile = tempDir;
11560                resourceFile = tempDir;
11561            } catch (IOException e) {
11562                Slog.w(TAG, "Failed to create copy file: " + e);
11563                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11564            }
11565
11566            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11567                @Override
11568                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11569                    if (!FileUtils.isValidExtFilename(name)) {
11570                        throw new IllegalArgumentException("Invalid filename: " + name);
11571                    }
11572                    try {
11573                        final File file = new File(codeFile, name);
11574                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11575                                O_RDWR | O_CREAT, 0644);
11576                        Os.chmod(file.getAbsolutePath(), 0644);
11577                        return new ParcelFileDescriptor(fd);
11578                    } catch (ErrnoException e) {
11579                        throw new RemoteException("Failed to open: " + e.getMessage());
11580                    }
11581                }
11582            };
11583
11584            int ret = PackageManager.INSTALL_SUCCEEDED;
11585            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11586            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11587                Slog.e(TAG, "Failed to copy package");
11588                return ret;
11589            }
11590
11591            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11592            NativeLibraryHelper.Handle handle = null;
11593            try {
11594                handle = NativeLibraryHelper.Handle.create(codeFile);
11595                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11596                        abiOverride);
11597            } catch (IOException e) {
11598                Slog.e(TAG, "Copying native libraries failed", e);
11599                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11600            } finally {
11601                IoUtils.closeQuietly(handle);
11602            }
11603
11604            return ret;
11605        }
11606
11607        int doPreInstall(int status) {
11608            if (status != PackageManager.INSTALL_SUCCEEDED) {
11609                cleanUp();
11610            }
11611            return status;
11612        }
11613
11614        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11615            if (status != PackageManager.INSTALL_SUCCEEDED) {
11616                cleanUp();
11617                return false;
11618            }
11619
11620            final File targetDir = codeFile.getParentFile();
11621            final File beforeCodeFile = codeFile;
11622            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11623
11624            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11625            try {
11626                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11627            } catch (ErrnoException e) {
11628                Slog.w(TAG, "Failed to rename", e);
11629                return false;
11630            }
11631
11632            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11633                Slog.w(TAG, "Failed to restorecon");
11634                return false;
11635            }
11636
11637            // Reflect the rename internally
11638            codeFile = afterCodeFile;
11639            resourceFile = afterCodeFile;
11640
11641            // Reflect the rename in scanned details
11642            pkg.codePath = afterCodeFile.getAbsolutePath();
11643            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11644                    pkg.baseCodePath);
11645            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11646                    pkg.splitCodePaths);
11647
11648            // Reflect the rename in app info
11649            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11650            pkg.applicationInfo.setCodePath(pkg.codePath);
11651            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11652            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11653            pkg.applicationInfo.setResourcePath(pkg.codePath);
11654            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11655            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11656
11657            return true;
11658        }
11659
11660        int doPostInstall(int status, int uid) {
11661            if (status != PackageManager.INSTALL_SUCCEEDED) {
11662                cleanUp();
11663            }
11664            return status;
11665        }
11666
11667        @Override
11668        String getCodePath() {
11669            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11670        }
11671
11672        @Override
11673        String getResourcePath() {
11674            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11675        }
11676
11677        private boolean cleanUp() {
11678            if (codeFile == null || !codeFile.exists()) {
11679                return false;
11680            }
11681
11682            if (codeFile.isDirectory()) {
11683                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11684            } else {
11685                codeFile.delete();
11686            }
11687
11688            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11689                resourceFile.delete();
11690            }
11691
11692            return true;
11693        }
11694
11695        void cleanUpResourcesLI() {
11696            // Try enumerating all code paths before deleting
11697            List<String> allCodePaths = Collections.EMPTY_LIST;
11698            if (codeFile != null && codeFile.exists()) {
11699                try {
11700                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11701                    allCodePaths = pkg.getAllCodePaths();
11702                } catch (PackageParserException e) {
11703                    // Ignored; we tried our best
11704                }
11705            }
11706
11707            cleanUp();
11708            removeDexFiles(allCodePaths, instructionSets);
11709        }
11710
11711        boolean doPostDeleteLI(boolean delete) {
11712            // XXX err, shouldn't we respect the delete flag?
11713            cleanUpResourcesLI();
11714            return true;
11715        }
11716    }
11717
11718    private boolean isAsecExternal(String cid) {
11719        final String asecPath = PackageHelper.getSdFilesystem(cid);
11720        return !asecPath.startsWith(mAsecInternalPath);
11721    }
11722
11723    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11724            PackageManagerException {
11725        if (copyRet < 0) {
11726            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11727                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11728                throw new PackageManagerException(copyRet, message);
11729            }
11730        }
11731    }
11732
11733    /**
11734     * Extract the MountService "container ID" from the full code path of an
11735     * .apk.
11736     */
11737    static String cidFromCodePath(String fullCodePath) {
11738        int eidx = fullCodePath.lastIndexOf("/");
11739        String subStr1 = fullCodePath.substring(0, eidx);
11740        int sidx = subStr1.lastIndexOf("/");
11741        return subStr1.substring(sidx+1, eidx);
11742    }
11743
11744    /**
11745     * Logic to handle installation of ASEC applications, including copying and
11746     * renaming logic.
11747     */
11748    class AsecInstallArgs extends InstallArgs {
11749        static final String RES_FILE_NAME = "pkg.apk";
11750        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11751
11752        String cid;
11753        String packagePath;
11754        String resourcePath;
11755
11756        /** New install */
11757        AsecInstallArgs(InstallParams params) {
11758            super(params.origin, params.move, params.observer, params.installFlags,
11759                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11760                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11761                    params.grantedRuntimePermissions,
11762                    params.traceMethod, params.traceCookie);
11763        }
11764
11765        /** Existing install */
11766        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11767                        boolean isExternal, boolean isForwardLocked) {
11768            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11769                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11770                    instructionSets, null, null, null, 0);
11771            // Hackily pretend we're still looking at a full code path
11772            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11773                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11774            }
11775
11776            // Extract cid from fullCodePath
11777            int eidx = fullCodePath.lastIndexOf("/");
11778            String subStr1 = fullCodePath.substring(0, eidx);
11779            int sidx = subStr1.lastIndexOf("/");
11780            cid = subStr1.substring(sidx+1, eidx);
11781            setMountPath(subStr1);
11782        }
11783
11784        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11785            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11786                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11787                    instructionSets, null, null, null, 0);
11788            this.cid = cid;
11789            setMountPath(PackageHelper.getSdDir(cid));
11790        }
11791
11792        void createCopyFile() {
11793            cid = mInstallerService.allocateExternalStageCidLegacy();
11794        }
11795
11796        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11797            if (origin.staged && origin.cid != null) {
11798                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11799                cid = origin.cid;
11800                setMountPath(PackageHelper.getSdDir(cid));
11801                return PackageManager.INSTALL_SUCCEEDED;
11802            }
11803
11804            if (temp) {
11805                createCopyFile();
11806            } else {
11807                /*
11808                 * Pre-emptively destroy the container since it's destroyed if
11809                 * copying fails due to it existing anyway.
11810                 */
11811                PackageHelper.destroySdDir(cid);
11812            }
11813
11814            final String newMountPath = imcs.copyPackageToContainer(
11815                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11816                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11817
11818            if (newMountPath != null) {
11819                setMountPath(newMountPath);
11820                return PackageManager.INSTALL_SUCCEEDED;
11821            } else {
11822                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11823            }
11824        }
11825
11826        @Override
11827        String getCodePath() {
11828            return packagePath;
11829        }
11830
11831        @Override
11832        String getResourcePath() {
11833            return resourcePath;
11834        }
11835
11836        int doPreInstall(int status) {
11837            if (status != PackageManager.INSTALL_SUCCEEDED) {
11838                // Destroy container
11839                PackageHelper.destroySdDir(cid);
11840            } else {
11841                boolean mounted = PackageHelper.isContainerMounted(cid);
11842                if (!mounted) {
11843                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11844                            Process.SYSTEM_UID);
11845                    if (newMountPath != null) {
11846                        setMountPath(newMountPath);
11847                    } else {
11848                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11849                    }
11850                }
11851            }
11852            return status;
11853        }
11854
11855        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11856            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11857            String newMountPath = null;
11858            if (PackageHelper.isContainerMounted(cid)) {
11859                // Unmount the container
11860                if (!PackageHelper.unMountSdDir(cid)) {
11861                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11862                    return false;
11863                }
11864            }
11865            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11866                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11867                        " which might be stale. Will try to clean up.");
11868                // Clean up the stale container and proceed to recreate.
11869                if (!PackageHelper.destroySdDir(newCacheId)) {
11870                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11871                    return false;
11872                }
11873                // Successfully cleaned up stale container. Try to rename again.
11874                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11875                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11876                            + " inspite of cleaning it up.");
11877                    return false;
11878                }
11879            }
11880            if (!PackageHelper.isContainerMounted(newCacheId)) {
11881                Slog.w(TAG, "Mounting container " + newCacheId);
11882                newMountPath = PackageHelper.mountSdDir(newCacheId,
11883                        getEncryptKey(), Process.SYSTEM_UID);
11884            } else {
11885                newMountPath = PackageHelper.getSdDir(newCacheId);
11886            }
11887            if (newMountPath == null) {
11888                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11889                return false;
11890            }
11891            Log.i(TAG, "Succesfully renamed " + cid +
11892                    " to " + newCacheId +
11893                    " at new path: " + newMountPath);
11894            cid = newCacheId;
11895
11896            final File beforeCodeFile = new File(packagePath);
11897            setMountPath(newMountPath);
11898            final File afterCodeFile = new File(packagePath);
11899
11900            // Reflect the rename in scanned details
11901            pkg.codePath = afterCodeFile.getAbsolutePath();
11902            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11903                    pkg.baseCodePath);
11904            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11905                    pkg.splitCodePaths);
11906
11907            // Reflect the rename in app info
11908            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11909            pkg.applicationInfo.setCodePath(pkg.codePath);
11910            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11911            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11912            pkg.applicationInfo.setResourcePath(pkg.codePath);
11913            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11914            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11915
11916            return true;
11917        }
11918
11919        private void setMountPath(String mountPath) {
11920            final File mountFile = new File(mountPath);
11921
11922            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11923            if (monolithicFile.exists()) {
11924                packagePath = monolithicFile.getAbsolutePath();
11925                if (isFwdLocked()) {
11926                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11927                } else {
11928                    resourcePath = packagePath;
11929                }
11930            } else {
11931                packagePath = mountFile.getAbsolutePath();
11932                resourcePath = packagePath;
11933            }
11934        }
11935
11936        int doPostInstall(int status, int uid) {
11937            if (status != PackageManager.INSTALL_SUCCEEDED) {
11938                cleanUp();
11939            } else {
11940                final int groupOwner;
11941                final String protectedFile;
11942                if (isFwdLocked()) {
11943                    groupOwner = UserHandle.getSharedAppGid(uid);
11944                    protectedFile = RES_FILE_NAME;
11945                } else {
11946                    groupOwner = -1;
11947                    protectedFile = null;
11948                }
11949
11950                if (uid < Process.FIRST_APPLICATION_UID
11951                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11952                    Slog.e(TAG, "Failed to finalize " + cid);
11953                    PackageHelper.destroySdDir(cid);
11954                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11955                }
11956
11957                boolean mounted = PackageHelper.isContainerMounted(cid);
11958                if (!mounted) {
11959                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11960                }
11961            }
11962            return status;
11963        }
11964
11965        private void cleanUp() {
11966            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11967
11968            // Destroy secure container
11969            PackageHelper.destroySdDir(cid);
11970        }
11971
11972        private List<String> getAllCodePaths() {
11973            final File codeFile = new File(getCodePath());
11974            if (codeFile != null && codeFile.exists()) {
11975                try {
11976                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11977                    return pkg.getAllCodePaths();
11978                } catch (PackageParserException e) {
11979                    // Ignored; we tried our best
11980                }
11981            }
11982            return Collections.EMPTY_LIST;
11983        }
11984
11985        void cleanUpResourcesLI() {
11986            // Enumerate all code paths before deleting
11987            cleanUpResourcesLI(getAllCodePaths());
11988        }
11989
11990        private void cleanUpResourcesLI(List<String> allCodePaths) {
11991            cleanUp();
11992            removeDexFiles(allCodePaths, instructionSets);
11993        }
11994
11995        String getPackageName() {
11996            return getAsecPackageName(cid);
11997        }
11998
11999        boolean doPostDeleteLI(boolean delete) {
12000            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12001            final List<String> allCodePaths = getAllCodePaths();
12002            boolean mounted = PackageHelper.isContainerMounted(cid);
12003            if (mounted) {
12004                // Unmount first
12005                if (PackageHelper.unMountSdDir(cid)) {
12006                    mounted = false;
12007                }
12008            }
12009            if (!mounted && delete) {
12010                cleanUpResourcesLI(allCodePaths);
12011            }
12012            return !mounted;
12013        }
12014
12015        @Override
12016        int doPreCopy() {
12017            if (isFwdLocked()) {
12018                if (!PackageHelper.fixSdPermissions(cid,
12019                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12020                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12021                }
12022            }
12023
12024            return PackageManager.INSTALL_SUCCEEDED;
12025        }
12026
12027        @Override
12028        int doPostCopy(int uid) {
12029            if (isFwdLocked()) {
12030                if (uid < Process.FIRST_APPLICATION_UID
12031                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12032                                RES_FILE_NAME)) {
12033                    Slog.e(TAG, "Failed to finalize " + cid);
12034                    PackageHelper.destroySdDir(cid);
12035                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12036                }
12037            }
12038
12039            return PackageManager.INSTALL_SUCCEEDED;
12040        }
12041    }
12042
12043    /**
12044     * Logic to handle movement of existing installed applications.
12045     */
12046    class MoveInstallArgs extends InstallArgs {
12047        private File codeFile;
12048        private File resourceFile;
12049
12050        /** New install */
12051        MoveInstallArgs(InstallParams params) {
12052            super(params.origin, params.move, params.observer, params.installFlags,
12053                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
12054                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12055                    params.grantedRuntimePermissions,
12056                    params.traceMethod, params.traceCookie);
12057        }
12058
12059        int copyApk(IMediaContainerService imcs, boolean temp) {
12060            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12061                    + move.fromUuid + " to " + move.toUuid);
12062            synchronized (mInstaller) {
12063                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12064                        move.dataAppName, move.appId, move.seinfo) != 0) {
12065                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12066                }
12067            }
12068
12069            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12070            resourceFile = codeFile;
12071            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12072
12073            return PackageManager.INSTALL_SUCCEEDED;
12074        }
12075
12076        int doPreInstall(int status) {
12077            if (status != PackageManager.INSTALL_SUCCEEDED) {
12078                cleanUp(move.toUuid);
12079            }
12080            return status;
12081        }
12082
12083        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12084            if (status != PackageManager.INSTALL_SUCCEEDED) {
12085                cleanUp(move.toUuid);
12086                return false;
12087            }
12088
12089            // Reflect the move in app info
12090            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12091            pkg.applicationInfo.setCodePath(pkg.codePath);
12092            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12093            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12094            pkg.applicationInfo.setResourcePath(pkg.codePath);
12095            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12096            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12097
12098            return true;
12099        }
12100
12101        int doPostInstall(int status, int uid) {
12102            if (status == PackageManager.INSTALL_SUCCEEDED) {
12103                cleanUp(move.fromUuid);
12104            } else {
12105                cleanUp(move.toUuid);
12106            }
12107            return status;
12108        }
12109
12110        @Override
12111        String getCodePath() {
12112            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12113        }
12114
12115        @Override
12116        String getResourcePath() {
12117            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12118        }
12119
12120        private boolean cleanUp(String volumeUuid) {
12121            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12122                    move.dataAppName);
12123            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12124            synchronized (mInstallLock) {
12125                // Clean up both app data and code
12126                removeDataDirsLI(volumeUuid, move.packageName);
12127                if (codeFile.isDirectory()) {
12128                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12129                } else {
12130                    codeFile.delete();
12131                }
12132            }
12133            return true;
12134        }
12135
12136        void cleanUpResourcesLI() {
12137            throw new UnsupportedOperationException();
12138        }
12139
12140        boolean doPostDeleteLI(boolean delete) {
12141            throw new UnsupportedOperationException();
12142        }
12143    }
12144
12145    static String getAsecPackageName(String packageCid) {
12146        int idx = packageCid.lastIndexOf("-");
12147        if (idx == -1) {
12148            return packageCid;
12149        }
12150        return packageCid.substring(0, idx);
12151    }
12152
12153    // Utility method used to create code paths based on package name and available index.
12154    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12155        String idxStr = "";
12156        int idx = 1;
12157        // Fall back to default value of idx=1 if prefix is not
12158        // part of oldCodePath
12159        if (oldCodePath != null) {
12160            String subStr = oldCodePath;
12161            // Drop the suffix right away
12162            if (suffix != null && subStr.endsWith(suffix)) {
12163                subStr = subStr.substring(0, subStr.length() - suffix.length());
12164            }
12165            // If oldCodePath already contains prefix find out the
12166            // ending index to either increment or decrement.
12167            int sidx = subStr.lastIndexOf(prefix);
12168            if (sidx != -1) {
12169                subStr = subStr.substring(sidx + prefix.length());
12170                if (subStr != null) {
12171                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12172                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12173                    }
12174                    try {
12175                        idx = Integer.parseInt(subStr);
12176                        if (idx <= 1) {
12177                            idx++;
12178                        } else {
12179                            idx--;
12180                        }
12181                    } catch(NumberFormatException e) {
12182                    }
12183                }
12184            }
12185        }
12186        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12187        return prefix + idxStr;
12188    }
12189
12190    private File getNextCodePath(File targetDir, String packageName) {
12191        int suffix = 1;
12192        File result;
12193        do {
12194            result = new File(targetDir, packageName + "-" + suffix);
12195            suffix++;
12196        } while (result.exists());
12197        return result;
12198    }
12199
12200    // Utility method that returns the relative package path with respect
12201    // to the installation directory. Like say for /data/data/com.test-1.apk
12202    // string com.test-1 is returned.
12203    static String deriveCodePathName(String codePath) {
12204        if (codePath == null) {
12205            return null;
12206        }
12207        final File codeFile = new File(codePath);
12208        final String name = codeFile.getName();
12209        if (codeFile.isDirectory()) {
12210            return name;
12211        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12212            final int lastDot = name.lastIndexOf('.');
12213            return name.substring(0, lastDot);
12214        } else {
12215            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12216            return null;
12217        }
12218    }
12219
12220    static class PackageInstalledInfo {
12221        String name;
12222        int uid;
12223        // The set of users that originally had this package installed.
12224        int[] origUsers;
12225        // The set of users that now have this package installed.
12226        int[] newUsers;
12227        PackageParser.Package pkg;
12228        int returnCode;
12229        String returnMsg;
12230        PackageRemovedInfo removedInfo;
12231
12232        public void setError(int code, String msg) {
12233            returnCode = code;
12234            returnMsg = msg;
12235            Slog.w(TAG, msg);
12236        }
12237
12238        public void setError(String msg, PackageParserException e) {
12239            returnCode = e.error;
12240            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12241            Slog.w(TAG, msg, e);
12242        }
12243
12244        public void setError(String msg, PackageManagerException e) {
12245            returnCode = e.error;
12246            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12247            Slog.w(TAG, msg, e);
12248        }
12249
12250        // In some error cases we want to convey more info back to the observer
12251        String origPackage;
12252        String origPermission;
12253    }
12254
12255    /*
12256     * Install a non-existing package.
12257     */
12258    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12259            UserHandle user, String installerPackageName, String volumeUuid,
12260            PackageInstalledInfo res) {
12261        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12262
12263        // Remember this for later, in case we need to rollback this install
12264        String pkgName = pkg.packageName;
12265
12266        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12267        // TODO: b/23350563
12268        final boolean dataDirExists = Environment
12269                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12270
12271        synchronized(mPackages) {
12272            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12273                // A package with the same name is already installed, though
12274                // it has been renamed to an older name.  The package we
12275                // are trying to install should be installed as an update to
12276                // the existing one, but that has not been requested, so bail.
12277                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12278                        + " without first uninstalling package running as "
12279                        + mSettings.mRenamedPackages.get(pkgName));
12280                return;
12281            }
12282            if (mPackages.containsKey(pkgName)) {
12283                // Don't allow installation over an existing package with the same name.
12284                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12285                        + " without first uninstalling.");
12286                return;
12287            }
12288        }
12289
12290        try {
12291            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12292                    System.currentTimeMillis(), user);
12293
12294            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12295            // delete the partially installed application. the data directory will have to be
12296            // restored if it was already existing
12297            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12298                // remove package from internal structures.  Note that we want deletePackageX to
12299                // delete the package data and cache directories that it created in
12300                // scanPackageLocked, unless those directories existed before we even tried to
12301                // install.
12302                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12303                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12304                                res.removedInfo, true);
12305            }
12306
12307        } catch (PackageManagerException e) {
12308            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12309        }
12310
12311        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12312    }
12313
12314    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12315        // Can't rotate keys during boot or if sharedUser.
12316        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12317                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12318            return false;
12319        }
12320        // app is using upgradeKeySets; make sure all are valid
12321        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12322        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12323        for (int i = 0; i < upgradeKeySets.length; i++) {
12324            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12325                Slog.wtf(TAG, "Package "
12326                         + (oldPs.name != null ? oldPs.name : "<null>")
12327                         + " contains upgrade-key-set reference to unknown key-set: "
12328                         + upgradeKeySets[i]
12329                         + " reverting to signatures check.");
12330                return false;
12331            }
12332        }
12333        return true;
12334    }
12335
12336    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12337        // Upgrade keysets are being used.  Determine if new package has a superset of the
12338        // required keys.
12339        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12340        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12341        for (int i = 0; i < upgradeKeySets.length; i++) {
12342            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12343            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12344                return true;
12345            }
12346        }
12347        return false;
12348    }
12349
12350    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12351            UserHandle user, String installerPackageName, String volumeUuid,
12352            PackageInstalledInfo res) {
12353        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12354
12355        final PackageParser.Package oldPackage;
12356        final String pkgName = pkg.packageName;
12357        final int[] allUsers;
12358        final boolean[] perUserInstalled;
12359
12360        // First find the old package info and check signatures
12361        synchronized(mPackages) {
12362            oldPackage = mPackages.get(pkgName);
12363            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12364            if (isEphemeral && !oldIsEphemeral) {
12365                // can't downgrade from full to ephemeral
12366                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12367                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12368                return;
12369            }
12370            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12371            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12372            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12373                if(!checkUpgradeKeySetLP(ps, pkg)) {
12374                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12375                            "New package not signed by keys specified by upgrade-keysets: "
12376                            + pkgName);
12377                    return;
12378                }
12379            } else {
12380                // default to original signature matching
12381                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12382                    != PackageManager.SIGNATURE_MATCH) {
12383                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12384                            "New package has a different signature: " + pkgName);
12385                    return;
12386                }
12387            }
12388
12389            // In case of rollback, remember per-user/profile install state
12390            allUsers = sUserManager.getUserIds();
12391            perUserInstalled = new boolean[allUsers.length];
12392            for (int i = 0; i < allUsers.length; i++) {
12393                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12394            }
12395        }
12396
12397        boolean sysPkg = (isSystemApp(oldPackage));
12398        if (sysPkg) {
12399            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12400                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12401        } else {
12402            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12403                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12404        }
12405    }
12406
12407    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12408            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12409            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12410            String volumeUuid, PackageInstalledInfo res) {
12411        String pkgName = deletedPackage.packageName;
12412        boolean deletedPkg = true;
12413        boolean updatedSettings = false;
12414
12415        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12416                + deletedPackage);
12417        long origUpdateTime;
12418        if (pkg.mExtras != null) {
12419            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12420        } else {
12421            origUpdateTime = 0;
12422        }
12423
12424        // First delete the existing package while retaining the data directory
12425        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12426                res.removedInfo, true)) {
12427            // If the existing package wasn't successfully deleted
12428            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12429            deletedPkg = false;
12430        } else {
12431            // Successfully deleted the old package; proceed with replace.
12432
12433            // If deleted package lived in a container, give users a chance to
12434            // relinquish resources before killing.
12435            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12436                if (DEBUG_INSTALL) {
12437                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12438                }
12439                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12440                final ArrayList<String> pkgList = new ArrayList<String>(1);
12441                pkgList.add(deletedPackage.applicationInfo.packageName);
12442                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12443            }
12444
12445            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12446            try {
12447                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12448                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12449                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12450                        perUserInstalled, res, user);
12451                updatedSettings = true;
12452            } catch (PackageManagerException e) {
12453                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12454            }
12455        }
12456
12457        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12458            // remove package from internal structures.  Note that we want deletePackageX to
12459            // delete the package data and cache directories that it created in
12460            // scanPackageLocked, unless those directories existed before we even tried to
12461            // install.
12462            if(updatedSettings) {
12463                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12464                deletePackageLI(
12465                        pkgName, null, true, allUsers, perUserInstalled,
12466                        PackageManager.DELETE_KEEP_DATA,
12467                                res.removedInfo, true);
12468            }
12469            // Since we failed to install the new package we need to restore the old
12470            // package that we deleted.
12471            if (deletedPkg) {
12472                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12473                File restoreFile = new File(deletedPackage.codePath);
12474                // Parse old package
12475                boolean oldExternal = isExternal(deletedPackage);
12476                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12477                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12478                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12479                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12480                try {
12481                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12482                            null);
12483                } catch (PackageManagerException e) {
12484                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12485                            + e.getMessage());
12486                    return;
12487                }
12488                // Restore of old package succeeded. Update permissions.
12489                // writer
12490                synchronized (mPackages) {
12491                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12492                            UPDATE_PERMISSIONS_ALL);
12493                    // can downgrade to reader
12494                    mSettings.writeLPr();
12495                }
12496                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12497            }
12498        }
12499    }
12500
12501    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12502            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12503            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12504            String volumeUuid, PackageInstalledInfo res) {
12505        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12506                + ", old=" + deletedPackage);
12507        boolean disabledSystem = false;
12508        boolean updatedSettings = false;
12509        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12510        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12511                != 0) {
12512            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12513        }
12514        String packageName = deletedPackage.packageName;
12515        if (packageName == null) {
12516            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12517                    "Attempt to delete null packageName.");
12518            return;
12519        }
12520        PackageParser.Package oldPkg;
12521        PackageSetting oldPkgSetting;
12522        // reader
12523        synchronized (mPackages) {
12524            oldPkg = mPackages.get(packageName);
12525            oldPkgSetting = mSettings.mPackages.get(packageName);
12526            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12527                    (oldPkgSetting == null)) {
12528                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12529                        "Couldn't find package:" + packageName + " information");
12530                return;
12531            }
12532        }
12533
12534        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12535
12536        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12537        res.removedInfo.removedPackage = packageName;
12538        // Remove existing system package
12539        removePackageLI(oldPkgSetting, true);
12540        // writer
12541        synchronized (mPackages) {
12542            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12543            if (!disabledSystem && deletedPackage != null) {
12544                // We didn't need to disable the .apk as a current system package,
12545                // which means we are replacing another update that is already
12546                // installed.  We need to make sure to delete the older one's .apk.
12547                res.removedInfo.args = createInstallArgsForExisting(0,
12548                        deletedPackage.applicationInfo.getCodePath(),
12549                        deletedPackage.applicationInfo.getResourcePath(),
12550                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12551            } else {
12552                res.removedInfo.args = null;
12553            }
12554        }
12555
12556        // Successfully disabled the old package. Now proceed with re-installation
12557        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12558
12559        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12560        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12561
12562        PackageParser.Package newPackage = null;
12563        try {
12564            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12565            if (newPackage.mExtras != null) {
12566                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12567                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12568                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12569
12570                // is the update attempting to change shared user? that isn't going to work...
12571                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12572                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12573                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12574                            + " to " + newPkgSetting.sharedUser);
12575                    updatedSettings = true;
12576                }
12577            }
12578
12579            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12580                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12581                        perUserInstalled, res, user);
12582                updatedSettings = true;
12583            }
12584
12585        } catch (PackageManagerException e) {
12586            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12587        }
12588
12589        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12590            // Re installation failed. Restore old information
12591            // Remove new pkg information
12592            if (newPackage != null) {
12593                removeInstalledPackageLI(newPackage, true);
12594            }
12595            // Add back the old system package
12596            try {
12597                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12598            } catch (PackageManagerException e) {
12599                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12600            }
12601            // Restore the old system information in Settings
12602            synchronized (mPackages) {
12603                if (disabledSystem) {
12604                    mSettings.enableSystemPackageLPw(packageName);
12605                }
12606                if (updatedSettings) {
12607                    mSettings.setInstallerPackageName(packageName,
12608                            oldPkgSetting.installerPackageName);
12609                }
12610                mSettings.writeLPr();
12611            }
12612        }
12613    }
12614
12615    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12616        // Collect all used permissions in the UID
12617        ArraySet<String> usedPermissions = new ArraySet<>();
12618        final int packageCount = su.packages.size();
12619        for (int i = 0; i < packageCount; i++) {
12620            PackageSetting ps = su.packages.valueAt(i);
12621            if (ps.pkg == null) {
12622                continue;
12623            }
12624            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12625            for (int j = 0; j < requestedPermCount; j++) {
12626                String permission = ps.pkg.requestedPermissions.get(j);
12627                BasePermission bp = mSettings.mPermissions.get(permission);
12628                if (bp != null) {
12629                    usedPermissions.add(permission);
12630                }
12631            }
12632        }
12633
12634        PermissionsState permissionsState = su.getPermissionsState();
12635        // Prune install permissions
12636        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12637        final int installPermCount = installPermStates.size();
12638        for (int i = installPermCount - 1; i >= 0;  i--) {
12639            PermissionState permissionState = installPermStates.get(i);
12640            if (!usedPermissions.contains(permissionState.getName())) {
12641                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12642                if (bp != null) {
12643                    permissionsState.revokeInstallPermission(bp);
12644                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12645                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12646                }
12647            }
12648        }
12649
12650        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12651
12652        // Prune runtime permissions
12653        for (int userId : allUserIds) {
12654            List<PermissionState> runtimePermStates = permissionsState
12655                    .getRuntimePermissionStates(userId);
12656            final int runtimePermCount = runtimePermStates.size();
12657            for (int i = runtimePermCount - 1; i >= 0; i--) {
12658                PermissionState permissionState = runtimePermStates.get(i);
12659                if (!usedPermissions.contains(permissionState.getName())) {
12660                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12661                    if (bp != null) {
12662                        permissionsState.revokeRuntimePermission(bp, userId);
12663                        permissionsState.updatePermissionFlags(bp, userId,
12664                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12665                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12666                                runtimePermissionChangedUserIds, userId);
12667                    }
12668                }
12669            }
12670        }
12671
12672        return runtimePermissionChangedUserIds;
12673    }
12674
12675    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12676            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12677            UserHandle user) {
12678        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12679
12680        String pkgName = newPackage.packageName;
12681        synchronized (mPackages) {
12682            //write settings. the installStatus will be incomplete at this stage.
12683            //note that the new package setting would have already been
12684            //added to mPackages. It hasn't been persisted yet.
12685            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12686            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12687            mSettings.writeLPr();
12688            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12689        }
12690
12691        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12692        synchronized (mPackages) {
12693            updatePermissionsLPw(newPackage.packageName, newPackage,
12694                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12695                            ? UPDATE_PERMISSIONS_ALL : 0));
12696            // For system-bundled packages, we assume that installing an upgraded version
12697            // of the package implies that the user actually wants to run that new code,
12698            // so we enable the package.
12699            PackageSetting ps = mSettings.mPackages.get(pkgName);
12700            if (ps != null) {
12701                if (isSystemApp(newPackage)) {
12702                    // NB: implicit assumption that system package upgrades apply to all users
12703                    if (DEBUG_INSTALL) {
12704                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12705                    }
12706                    if (res.origUsers != null) {
12707                        for (int userHandle : res.origUsers) {
12708                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12709                                    userHandle, installerPackageName);
12710                        }
12711                    }
12712                    // Also convey the prior install/uninstall state
12713                    if (allUsers != null && perUserInstalled != null) {
12714                        for (int i = 0; i < allUsers.length; i++) {
12715                            if (DEBUG_INSTALL) {
12716                                Slog.d(TAG, "    user " + allUsers[i]
12717                                        + " => " + perUserInstalled[i]);
12718                            }
12719                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12720                        }
12721                        // these install state changes will be persisted in the
12722                        // upcoming call to mSettings.writeLPr().
12723                    }
12724                }
12725                // It's implied that when a user requests installation, they want the app to be
12726                // installed and enabled.
12727                int userId = user.getIdentifier();
12728                if (userId != UserHandle.USER_ALL) {
12729                    ps.setInstalled(true, userId);
12730                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12731                }
12732            }
12733            res.name = pkgName;
12734            res.uid = newPackage.applicationInfo.uid;
12735            res.pkg = newPackage;
12736            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12737            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12738            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12739            //to update install status
12740            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12741            mSettings.writeLPr();
12742            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12743        }
12744
12745        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12746    }
12747
12748    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12749        try {
12750            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12751            installPackageLI(args, res);
12752        } finally {
12753            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12754        }
12755    }
12756
12757    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12758        final int installFlags = args.installFlags;
12759        final String installerPackageName = args.installerPackageName;
12760        final String volumeUuid = args.volumeUuid;
12761        final File tmpPackageFile = new File(args.getCodePath());
12762        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12763        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12764                || (args.volumeUuid != null));
12765        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12766        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12767        boolean replace = false;
12768        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12769        if (args.move != null) {
12770            // moving a complete application; perfom an initial scan on the new install location
12771            scanFlags |= SCAN_INITIAL;
12772        }
12773        // Result object to be returned
12774        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12775
12776        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12777
12778        // Sanity check
12779        if (ephemeral && (forwardLocked || onExternal)) {
12780            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12781                    + " external=" + onExternal);
12782            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12783            return;
12784        }
12785
12786        // Retrieve PackageSettings and parse package
12787        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12788                | PackageParser.PARSE_ENFORCE_CODE
12789                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12790                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12791                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0)
12792                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12793        PackageParser pp = new PackageParser();
12794        pp.setSeparateProcesses(mSeparateProcesses);
12795        pp.setDisplayMetrics(mMetrics);
12796
12797        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12798        final PackageParser.Package pkg;
12799        try {
12800            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12801        } catch (PackageParserException e) {
12802            res.setError("Failed parse during installPackageLI", e);
12803            return;
12804        } finally {
12805            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12806        }
12807
12808        // Mark that we have an install time CPU ABI override.
12809        pkg.cpuAbiOverride = args.abiOverride;
12810
12811        String pkgName = res.name = pkg.packageName;
12812        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12813            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12814                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12815                return;
12816            }
12817        }
12818
12819        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12820        try {
12821            pp.collectCertificates(pkg, parseFlags);
12822        } catch (PackageParserException e) {
12823            res.setError("Failed collect during installPackageLI", e);
12824            return;
12825        } finally {
12826            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12827        }
12828
12829        /* If the installer passed in a manifest digest, compare it now. */
12830        if (args.manifestDigest != null) {
12831            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12832            try {
12833                pp.collectManifestDigest(pkg);
12834            } catch (PackageParserException e) {
12835                res.setError("Failed collect during installPackageLI", e);
12836                return;
12837            } finally {
12838                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12839            }
12840
12841            if (DEBUG_INSTALL) {
12842                final String parsedManifest = pkg.manifestDigest == null ? "null"
12843                        : pkg.manifestDigest.toString();
12844                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12845                        + parsedManifest);
12846            }
12847
12848            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12849                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12850                return;
12851            }
12852        } else if (DEBUG_INSTALL) {
12853            final String parsedManifest = pkg.manifestDigest == null
12854                    ? "null" : pkg.manifestDigest.toString();
12855            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12856        }
12857
12858        // Get rid of all references to package scan path via parser.
12859        pp = null;
12860        String oldCodePath = null;
12861        boolean systemApp = false;
12862        synchronized (mPackages) {
12863            // Check if installing already existing package
12864            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12865                String oldName = mSettings.mRenamedPackages.get(pkgName);
12866                if (pkg.mOriginalPackages != null
12867                        && pkg.mOriginalPackages.contains(oldName)
12868                        && mPackages.containsKey(oldName)) {
12869                    // This package is derived from an original package,
12870                    // and this device has been updating from that original
12871                    // name.  We must continue using the original name, so
12872                    // rename the new package here.
12873                    pkg.setPackageName(oldName);
12874                    pkgName = pkg.packageName;
12875                    replace = true;
12876                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12877                            + oldName + " pkgName=" + pkgName);
12878                } else if (mPackages.containsKey(pkgName)) {
12879                    // This package, under its official name, already exists
12880                    // on the device; we should replace it.
12881                    replace = true;
12882                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12883                }
12884
12885                // Prevent apps opting out from runtime permissions
12886                if (replace) {
12887                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12888                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12889                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12890                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12891                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12892                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12893                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12894                                        + " doesn't support runtime permissions but the old"
12895                                        + " target SDK " + oldTargetSdk + " does.");
12896                        return;
12897                    }
12898                }
12899            }
12900
12901            PackageSetting ps = mSettings.mPackages.get(pkgName);
12902            if (ps != null) {
12903                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12904
12905                // Quick sanity check that we're signed correctly if updating;
12906                // we'll check this again later when scanning, but we want to
12907                // bail early here before tripping over redefined permissions.
12908                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12909                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12910                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12911                                + pkg.packageName + " upgrade keys do not match the "
12912                                + "previously installed version");
12913                        return;
12914                    }
12915                } else {
12916                    try {
12917                        verifySignaturesLP(ps, pkg);
12918                    } catch (PackageManagerException e) {
12919                        res.setError(e.error, e.getMessage());
12920                        return;
12921                    }
12922                }
12923
12924                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12925                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12926                    systemApp = (ps.pkg.applicationInfo.flags &
12927                            ApplicationInfo.FLAG_SYSTEM) != 0;
12928                }
12929                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12930            }
12931
12932            // Check whether the newly-scanned package wants to define an already-defined perm
12933            int N = pkg.permissions.size();
12934            for (int i = N-1; i >= 0; i--) {
12935                PackageParser.Permission perm = pkg.permissions.get(i);
12936                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12937                if (bp != null) {
12938                    // If the defining package is signed with our cert, it's okay.  This
12939                    // also includes the "updating the same package" case, of course.
12940                    // "updating same package" could also involve key-rotation.
12941                    final boolean sigsOk;
12942                    if (bp.sourcePackage.equals(pkg.packageName)
12943                            && (bp.packageSetting instanceof PackageSetting)
12944                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12945                                    scanFlags))) {
12946                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12947                    } else {
12948                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12949                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12950                    }
12951                    if (!sigsOk) {
12952                        // If the owning package is the system itself, we log but allow
12953                        // install to proceed; we fail the install on all other permission
12954                        // redefinitions.
12955                        if (!bp.sourcePackage.equals("android")) {
12956                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12957                                    + pkg.packageName + " attempting to redeclare permission "
12958                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12959                            res.origPermission = perm.info.name;
12960                            res.origPackage = bp.sourcePackage;
12961                            return;
12962                        } else {
12963                            Slog.w(TAG, "Package " + pkg.packageName
12964                                    + " attempting to redeclare system permission "
12965                                    + perm.info.name + "; ignoring new declaration");
12966                            pkg.permissions.remove(i);
12967                        }
12968                    }
12969                }
12970            }
12971
12972        }
12973
12974        if (systemApp) {
12975            if (onExternal) {
12976                // Abort update; system app can't be replaced with app on sdcard
12977                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12978                        "Cannot install updates to system apps on sdcard");
12979                return;
12980            } else if (ephemeral) {
12981                // Abort update; system app can't be replaced with an ephemeral app
12982                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12983                        "Cannot update a system app with an ephemeral app");
12984                return;
12985            }
12986        }
12987
12988        if (args.move != null) {
12989            // We did an in-place move, so dex is ready to roll
12990            scanFlags |= SCAN_NO_DEX;
12991            scanFlags |= SCAN_MOVE;
12992
12993            synchronized (mPackages) {
12994                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12995                if (ps == null) {
12996                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12997                            "Missing settings for moved package " + pkgName);
12998                }
12999
13000                // We moved the entire application as-is, so bring over the
13001                // previously derived ABI information.
13002                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13003                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13004            }
13005
13006        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13007            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13008            scanFlags |= SCAN_NO_DEX;
13009
13010            try {
13011                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13012                        true /* extract libs */);
13013            } catch (PackageManagerException pme) {
13014                Slog.e(TAG, "Error deriving application ABI", pme);
13015                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13016                return;
13017            }
13018        }
13019
13020        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13021            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13022            return;
13023        }
13024
13025        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13026
13027        if (replace) {
13028            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13029                    installerPackageName, volumeUuid, res);
13030        } else {
13031            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13032                    args.user, installerPackageName, volumeUuid, res);
13033        }
13034        synchronized (mPackages) {
13035            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13036            if (ps != null) {
13037                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13038            }
13039        }
13040    }
13041
13042    private void startIntentFilterVerifications(int userId, boolean replacing,
13043            PackageParser.Package pkg) {
13044        if (mIntentFilterVerifierComponent == null) {
13045            Slog.w(TAG, "No IntentFilter verification will not be done as "
13046                    + "there is no IntentFilterVerifier available!");
13047            return;
13048        }
13049
13050        final int verifierUid = getPackageUid(
13051                mIntentFilterVerifierComponent.getPackageName(),
13052                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13053
13054        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13055        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13056        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13057        mHandler.sendMessage(msg);
13058    }
13059
13060    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13061            PackageParser.Package pkg) {
13062        int size = pkg.activities.size();
13063        if (size == 0) {
13064            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13065                    "No activity, so no need to verify any IntentFilter!");
13066            return;
13067        }
13068
13069        final boolean hasDomainURLs = hasDomainURLs(pkg);
13070        if (!hasDomainURLs) {
13071            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13072                    "No domain URLs, so no need to verify any IntentFilter!");
13073            return;
13074        }
13075
13076        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13077                + " if any IntentFilter from the " + size
13078                + " Activities needs verification ...");
13079
13080        int count = 0;
13081        final String packageName = pkg.packageName;
13082
13083        synchronized (mPackages) {
13084            // If this is a new install and we see that we've already run verification for this
13085            // package, we have nothing to do: it means the state was restored from backup.
13086            if (!replacing) {
13087                IntentFilterVerificationInfo ivi =
13088                        mSettings.getIntentFilterVerificationLPr(packageName);
13089                if (ivi != null) {
13090                    if (DEBUG_DOMAIN_VERIFICATION) {
13091                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13092                                + ivi.getStatusString());
13093                    }
13094                    return;
13095                }
13096            }
13097
13098            // If any filters need to be verified, then all need to be.
13099            boolean needToVerify = false;
13100            for (PackageParser.Activity a : pkg.activities) {
13101                for (ActivityIntentInfo filter : a.intents) {
13102                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13103                        if (DEBUG_DOMAIN_VERIFICATION) {
13104                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13105                        }
13106                        needToVerify = true;
13107                        break;
13108                    }
13109                }
13110            }
13111
13112            if (needToVerify) {
13113                final int verificationId = mIntentFilterVerificationToken++;
13114                for (PackageParser.Activity a : pkg.activities) {
13115                    for (ActivityIntentInfo filter : a.intents) {
13116                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13117                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13118                                    "Verification needed for IntentFilter:" + filter.toString());
13119                            mIntentFilterVerifier.addOneIntentFilterVerification(
13120                                    verifierUid, userId, verificationId, filter, packageName);
13121                            count++;
13122                        }
13123                    }
13124                }
13125            }
13126        }
13127
13128        if (count > 0) {
13129            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13130                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13131                    +  " for userId:" + userId);
13132            mIntentFilterVerifier.startVerifications(userId);
13133        } else {
13134            if (DEBUG_DOMAIN_VERIFICATION) {
13135                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13136            }
13137        }
13138    }
13139
13140    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13141        final ComponentName cn  = filter.activity.getComponentName();
13142        final String packageName = cn.getPackageName();
13143
13144        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13145                packageName);
13146        if (ivi == null) {
13147            return true;
13148        }
13149        int status = ivi.getStatus();
13150        switch (status) {
13151            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13152            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13153                return true;
13154
13155            default:
13156                // Nothing to do
13157                return false;
13158        }
13159    }
13160
13161    private static boolean isMultiArch(ApplicationInfo info) {
13162        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13163    }
13164
13165    private static boolean isExternal(PackageParser.Package pkg) {
13166        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13167    }
13168
13169    private static boolean isExternal(PackageSetting ps) {
13170        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13171    }
13172
13173    private static boolean isEphemeral(PackageParser.Package pkg) {
13174        return pkg.applicationInfo.isEphemeralApp();
13175    }
13176
13177    private static boolean isEphemeral(PackageSetting ps) {
13178        return ps.pkg != null && isEphemeral(ps.pkg);
13179    }
13180
13181    private static boolean isSystemApp(PackageParser.Package pkg) {
13182        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13183    }
13184
13185    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13186        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13187    }
13188
13189    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13190        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13191    }
13192
13193    private static boolean isSystemApp(PackageSetting ps) {
13194        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13195    }
13196
13197    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13198        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13199    }
13200
13201    private int packageFlagsToInstallFlags(PackageSetting ps) {
13202        int installFlags = 0;
13203        if (isEphemeral(ps)) {
13204            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13205        }
13206        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13207            // This existing package was an external ASEC install when we have
13208            // the external flag without a UUID
13209            installFlags |= PackageManager.INSTALL_EXTERNAL;
13210        }
13211        if (ps.isForwardLocked()) {
13212            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13213        }
13214        return installFlags;
13215    }
13216
13217    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13218        if (isExternal(pkg)) {
13219            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13220                return StorageManager.UUID_PRIMARY_PHYSICAL;
13221            } else {
13222                return pkg.volumeUuid;
13223            }
13224        } else {
13225            return StorageManager.UUID_PRIVATE_INTERNAL;
13226        }
13227    }
13228
13229    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13230        if (isExternal(pkg)) {
13231            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13232                return mSettings.getExternalVersion();
13233            } else {
13234                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13235            }
13236        } else {
13237            return mSettings.getInternalVersion();
13238        }
13239    }
13240
13241    private void deleteTempPackageFiles() {
13242        final FilenameFilter filter = new FilenameFilter() {
13243            public boolean accept(File dir, String name) {
13244                return name.startsWith("vmdl") && name.endsWith(".tmp");
13245            }
13246        };
13247        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13248            file.delete();
13249        }
13250    }
13251
13252    @Override
13253    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13254            int flags) {
13255        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13256                flags);
13257    }
13258
13259    @Override
13260    public void deletePackage(final String packageName,
13261            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13262        mContext.enforceCallingOrSelfPermission(
13263                android.Manifest.permission.DELETE_PACKAGES, null);
13264        Preconditions.checkNotNull(packageName);
13265        Preconditions.checkNotNull(observer);
13266        final int uid = Binder.getCallingUid();
13267        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13268        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13269        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13270            mContext.enforceCallingOrSelfPermission(
13271                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13272                    "deletePackage for user " + userId);
13273        }
13274
13275        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13276            try {
13277                observer.onPackageDeleted(packageName,
13278                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13279            } catch (RemoteException re) {
13280            }
13281            return;
13282        }
13283
13284        for (int currentUserId : users) {
13285            if (getBlockUninstallForUser(packageName, currentUserId)) {
13286                try {
13287                    observer.onPackageDeleted(packageName,
13288                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13289                } catch (RemoteException re) {
13290                }
13291                return;
13292            }
13293        }
13294
13295        if (DEBUG_REMOVE) {
13296            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13297        }
13298        // Queue up an async operation since the package deletion may take a little while.
13299        mHandler.post(new Runnable() {
13300            public void run() {
13301                mHandler.removeCallbacks(this);
13302                final int returnCode = deletePackageX(packageName, userId, flags);
13303                try {
13304                    observer.onPackageDeleted(packageName, returnCode, null);
13305                } catch (RemoteException e) {
13306                    Log.i(TAG, "Observer no longer exists.");
13307                } //end catch
13308            } //end run
13309        });
13310    }
13311
13312    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13313        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13314                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13315        try {
13316            if (dpm != null) {
13317                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13318                        /* callingUserOnly =*/ false);
13319                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13320                        : deviceOwnerComponentName.getPackageName();
13321                // Does the package contains the device owner?
13322                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13323                // this check is probably not needed, since DO should be registered as a device
13324                // admin on some user too. (Original bug for this: b/17657954)
13325                if (packageName.equals(deviceOwnerPackageName)) {
13326                    return true;
13327                }
13328                // Does it contain a device admin for any user?
13329                int[] users;
13330                if (userId == UserHandle.USER_ALL) {
13331                    users = sUserManager.getUserIds();
13332                } else {
13333                    users = new int[]{userId};
13334                }
13335                for (int i = 0; i < users.length; ++i) {
13336                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13337                        return true;
13338                    }
13339                }
13340            }
13341        } catch (RemoteException e) {
13342        }
13343        return false;
13344    }
13345
13346    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13347        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13348    }
13349
13350    /**
13351     *  This method is an internal method that could be get invoked either
13352     *  to delete an installed package or to clean up a failed installation.
13353     *  After deleting an installed package, a broadcast is sent to notify any
13354     *  listeners that the package has been installed. For cleaning up a failed
13355     *  installation, the broadcast is not necessary since the package's
13356     *  installation wouldn't have sent the initial broadcast either
13357     *  The key steps in deleting a package are
13358     *  deleting the package information in internal structures like mPackages,
13359     *  deleting the packages base directories through installd
13360     *  updating mSettings to reflect current status
13361     *  persisting settings for later use
13362     *  sending a broadcast if necessary
13363     */
13364    private int deletePackageX(String packageName, int userId, int flags) {
13365        final PackageRemovedInfo info = new PackageRemovedInfo();
13366        final boolean res;
13367
13368        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13369                ? UserHandle.ALL : new UserHandle(userId);
13370
13371        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13372            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13373            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13374        }
13375
13376        boolean removedForAllUsers = false;
13377        boolean systemUpdate = false;
13378
13379        PackageParser.Package uninstalledPkg;
13380
13381        // for the uninstall-updates case and restricted profiles, remember the per-
13382        // userhandle installed state
13383        int[] allUsers;
13384        boolean[] perUserInstalled;
13385        synchronized (mPackages) {
13386            uninstalledPkg = mPackages.get(packageName);
13387            PackageSetting ps = mSettings.mPackages.get(packageName);
13388            allUsers = sUserManager.getUserIds();
13389            perUserInstalled = new boolean[allUsers.length];
13390            for (int i = 0; i < allUsers.length; i++) {
13391                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13392            }
13393        }
13394
13395        synchronized (mInstallLock) {
13396            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13397            res = deletePackageLI(packageName, removeForUser,
13398                    true, allUsers, perUserInstalled,
13399                    flags | REMOVE_CHATTY, info, true);
13400            systemUpdate = info.isRemovedPackageSystemUpdate;
13401            synchronized (mPackages) {
13402                if (res) {
13403                    if (!systemUpdate && mPackages.get(packageName) == null) {
13404                        removedForAllUsers = true;
13405                    }
13406                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13407                }
13408            }
13409            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13410                    + " removedForAllUsers=" + removedForAllUsers);
13411        }
13412
13413        if (res) {
13414            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13415
13416            // If the removed package was a system update, the old system package
13417            // was re-enabled; we need to broadcast this information
13418            if (systemUpdate) {
13419                Bundle extras = new Bundle(1);
13420                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13421                        ? info.removedAppId : info.uid);
13422                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13423
13424                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13425                        extras, 0, null, null, null);
13426                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13427                        extras, 0, null, null, null);
13428                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13429                        null, 0, packageName, null, null);
13430            }
13431        }
13432        // Force a gc here.
13433        Runtime.getRuntime().gc();
13434        // Delete the resources here after sending the broadcast to let
13435        // other processes clean up before deleting resources.
13436        if (info.args != null) {
13437            synchronized (mInstallLock) {
13438                info.args.doPostDeleteLI(true);
13439            }
13440        }
13441
13442        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13443    }
13444
13445    class PackageRemovedInfo {
13446        String removedPackage;
13447        int uid = -1;
13448        int removedAppId = -1;
13449        int[] removedUsers = null;
13450        boolean isRemovedPackageSystemUpdate = false;
13451        // Clean up resources deleted packages.
13452        InstallArgs args = null;
13453
13454        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13455            Bundle extras = new Bundle(1);
13456            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13457            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13458            if (replacing) {
13459                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13460            }
13461            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13462            if (removedPackage != null) {
13463                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13464                        extras, 0, null, null, removedUsers);
13465                if (fullRemove && !replacing) {
13466                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13467                            extras, 0, null, null, removedUsers);
13468                }
13469            }
13470            if (removedAppId >= 0) {
13471                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13472                        removedUsers);
13473            }
13474        }
13475    }
13476
13477    /*
13478     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13479     * flag is not set, the data directory is removed as well.
13480     * make sure this flag is set for partially installed apps. If not its meaningless to
13481     * delete a partially installed application.
13482     */
13483    private void removePackageDataLI(PackageSetting ps,
13484            int[] allUserHandles, boolean[] perUserInstalled,
13485            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13486        String packageName = ps.name;
13487        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13488        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13489        // Retrieve object to delete permissions for shared user later on
13490        final PackageSetting deletedPs;
13491        // reader
13492        synchronized (mPackages) {
13493            deletedPs = mSettings.mPackages.get(packageName);
13494            if (outInfo != null) {
13495                outInfo.removedPackage = packageName;
13496                outInfo.removedUsers = deletedPs != null
13497                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13498                        : null;
13499            }
13500        }
13501        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13502            removeDataDirsLI(ps.volumeUuid, packageName);
13503            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13504        }
13505        // writer
13506        synchronized (mPackages) {
13507            if (deletedPs != null) {
13508                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13509                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13510                    clearDefaultBrowserIfNeeded(packageName);
13511                    if (outInfo != null) {
13512                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13513                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13514                    }
13515                    updatePermissionsLPw(deletedPs.name, null, 0);
13516                    if (deletedPs.sharedUser != null) {
13517                        // Remove permissions associated with package. Since runtime
13518                        // permissions are per user we have to kill the removed package
13519                        // or packages running under the shared user of the removed
13520                        // package if revoking the permissions requested only by the removed
13521                        // package is successful and this causes a change in gids.
13522                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13523                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13524                                    userId);
13525                            if (userIdToKill == UserHandle.USER_ALL
13526                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13527                                // If gids changed for this user, kill all affected packages.
13528                                mHandler.post(new Runnable() {
13529                                    @Override
13530                                    public void run() {
13531                                        // This has to happen with no lock held.
13532                                        killApplication(deletedPs.name, deletedPs.appId,
13533                                                KILL_APP_REASON_GIDS_CHANGED);
13534                                    }
13535                                });
13536                                break;
13537                            }
13538                        }
13539                    }
13540                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13541                }
13542                // make sure to preserve per-user disabled state if this removal was just
13543                // a downgrade of a system app to the factory package
13544                if (allUserHandles != null && perUserInstalled != null) {
13545                    if (DEBUG_REMOVE) {
13546                        Slog.d(TAG, "Propagating install state across downgrade");
13547                    }
13548                    for (int i = 0; i < allUserHandles.length; i++) {
13549                        if (DEBUG_REMOVE) {
13550                            Slog.d(TAG, "    user " + allUserHandles[i]
13551                                    + " => " + perUserInstalled[i]);
13552                        }
13553                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13554                    }
13555                }
13556            }
13557            // can downgrade to reader
13558            if (writeSettings) {
13559                // Save settings now
13560                mSettings.writeLPr();
13561            }
13562        }
13563        if (outInfo != null) {
13564            // A user ID was deleted here. Go through all users and remove it
13565            // from KeyStore.
13566            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13567        }
13568    }
13569
13570    static boolean locationIsPrivileged(File path) {
13571        try {
13572            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13573                    .getCanonicalPath();
13574            return path.getCanonicalPath().startsWith(privilegedAppDir);
13575        } catch (IOException e) {
13576            Slog.e(TAG, "Unable to access code path " + path);
13577        }
13578        return false;
13579    }
13580
13581    /*
13582     * Tries to delete system package.
13583     */
13584    private boolean deleteSystemPackageLI(PackageSetting newPs,
13585            int[] allUserHandles, boolean[] perUserInstalled,
13586            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13587        final boolean applyUserRestrictions
13588                = (allUserHandles != null) && (perUserInstalled != null);
13589        PackageSetting disabledPs = null;
13590        // Confirm if the system package has been updated
13591        // An updated system app can be deleted. This will also have to restore
13592        // the system pkg from system partition
13593        // reader
13594        synchronized (mPackages) {
13595            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13596        }
13597        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13598                + " disabledPs=" + disabledPs);
13599        if (disabledPs == null) {
13600            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13601            return false;
13602        } else if (DEBUG_REMOVE) {
13603            Slog.d(TAG, "Deleting system pkg from data partition");
13604        }
13605        if (DEBUG_REMOVE) {
13606            if (applyUserRestrictions) {
13607                Slog.d(TAG, "Remembering install states:");
13608                for (int i = 0; i < allUserHandles.length; i++) {
13609                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13610                }
13611            }
13612        }
13613        // Delete the updated package
13614        outInfo.isRemovedPackageSystemUpdate = true;
13615        if (disabledPs.versionCode < newPs.versionCode) {
13616            // Delete data for downgrades
13617            flags &= ~PackageManager.DELETE_KEEP_DATA;
13618        } else {
13619            // Preserve data by setting flag
13620            flags |= PackageManager.DELETE_KEEP_DATA;
13621        }
13622        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13623                allUserHandles, perUserInstalled, outInfo, writeSettings);
13624        if (!ret) {
13625            return false;
13626        }
13627        // writer
13628        synchronized (mPackages) {
13629            // Reinstate the old system package
13630            mSettings.enableSystemPackageLPw(newPs.name);
13631            // Remove any native libraries from the upgraded package.
13632            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13633        }
13634        // Install the system package
13635        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13636        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13637        if (locationIsPrivileged(disabledPs.codePath)) {
13638            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13639        }
13640
13641        final PackageParser.Package newPkg;
13642        try {
13643            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13644        } catch (PackageManagerException e) {
13645            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13646            return false;
13647        }
13648
13649        // writer
13650        synchronized (mPackages) {
13651            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13652
13653            // Propagate the permissions state as we do not want to drop on the floor
13654            // runtime permissions. The update permissions method below will take
13655            // care of removing obsolete permissions and grant install permissions.
13656            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13657            updatePermissionsLPw(newPkg.packageName, newPkg,
13658                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13659
13660            if (applyUserRestrictions) {
13661                if (DEBUG_REMOVE) {
13662                    Slog.d(TAG, "Propagating install state across reinstall");
13663                }
13664                for (int i = 0; i < allUserHandles.length; i++) {
13665                    if (DEBUG_REMOVE) {
13666                        Slog.d(TAG, "    user " + allUserHandles[i]
13667                                + " => " + perUserInstalled[i]);
13668                    }
13669                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13670
13671                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13672                }
13673                // Regardless of writeSettings we need to ensure that this restriction
13674                // state propagation is persisted
13675                mSettings.writeAllUsersPackageRestrictionsLPr();
13676            }
13677            // can downgrade to reader here
13678            if (writeSettings) {
13679                mSettings.writeLPr();
13680            }
13681        }
13682        return true;
13683    }
13684
13685    private boolean deleteInstalledPackageLI(PackageSetting ps,
13686            boolean deleteCodeAndResources, int flags,
13687            int[] allUserHandles, boolean[] perUserInstalled,
13688            PackageRemovedInfo outInfo, boolean writeSettings) {
13689        if (outInfo != null) {
13690            outInfo.uid = ps.appId;
13691        }
13692
13693        // Delete package data from internal structures and also remove data if flag is set
13694        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13695
13696        // Delete application code and resources
13697        if (deleteCodeAndResources && (outInfo != null)) {
13698            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13699                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13700            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13701        }
13702        return true;
13703    }
13704
13705    @Override
13706    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13707            int userId) {
13708        mContext.enforceCallingOrSelfPermission(
13709                android.Manifest.permission.DELETE_PACKAGES, null);
13710        synchronized (mPackages) {
13711            PackageSetting ps = mSettings.mPackages.get(packageName);
13712            if (ps == null) {
13713                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13714                return false;
13715            }
13716            if (!ps.getInstalled(userId)) {
13717                // Can't block uninstall for an app that is not installed or enabled.
13718                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13719                return false;
13720            }
13721            ps.setBlockUninstall(blockUninstall, userId);
13722            mSettings.writePackageRestrictionsLPr(userId);
13723        }
13724        return true;
13725    }
13726
13727    @Override
13728    public boolean getBlockUninstallForUser(String packageName, int userId) {
13729        synchronized (mPackages) {
13730            PackageSetting ps = mSettings.mPackages.get(packageName);
13731            if (ps == null) {
13732                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13733                return false;
13734            }
13735            return ps.getBlockUninstall(userId);
13736        }
13737    }
13738
13739    @Override
13740    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13741        int callingUid = Binder.getCallingUid();
13742        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13743            throw new SecurityException(
13744                    "setRequiredForSystemUser can only be run by the system or root");
13745        }
13746        synchronized (mPackages) {
13747            PackageSetting ps = mSettings.mPackages.get(packageName);
13748            if (ps == null) {
13749                Log.w(TAG, "Package doesn't exist: " + packageName);
13750                return false;
13751            }
13752            if (systemUserApp) {
13753                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13754            } else {
13755                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13756            }
13757            mSettings.writeLPr();
13758        }
13759        return true;
13760    }
13761
13762    /*
13763     * This method handles package deletion in general
13764     */
13765    private boolean deletePackageLI(String packageName, UserHandle user,
13766            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13767            int flags, PackageRemovedInfo outInfo,
13768            boolean writeSettings) {
13769        if (packageName == null) {
13770            Slog.w(TAG, "Attempt to delete null packageName.");
13771            return false;
13772        }
13773        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13774        PackageSetting ps;
13775        boolean dataOnly = false;
13776        int removeUser = -1;
13777        int appId = -1;
13778        synchronized (mPackages) {
13779            ps = mSettings.mPackages.get(packageName);
13780            if (ps == null) {
13781                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13782                return false;
13783            }
13784            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13785                    && user.getIdentifier() != UserHandle.USER_ALL) {
13786                // The caller is asking that the package only be deleted for a single
13787                // user.  To do this, we just mark its uninstalled state and delete
13788                // its data.  If this is a system app, we only allow this to happen if
13789                // they have set the special DELETE_SYSTEM_APP which requests different
13790                // semantics than normal for uninstalling system apps.
13791                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13792                final int userId = user.getIdentifier();
13793                ps.setUserState(userId,
13794                        COMPONENT_ENABLED_STATE_DEFAULT,
13795                        false, //installed
13796                        true,  //stopped
13797                        true,  //notLaunched
13798                        false, //hidden
13799                        null, null, null,
13800                        false, // blockUninstall
13801                        ps.readUserState(userId).domainVerificationStatus, 0);
13802                if (!isSystemApp(ps)) {
13803                    // Do not uninstall the APK if an app should be cached
13804                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13805                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13806                        // Other user still have this package installed, so all
13807                        // we need to do is clear this user's data and save that
13808                        // it is uninstalled.
13809                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13810                        removeUser = user.getIdentifier();
13811                        appId = ps.appId;
13812                        scheduleWritePackageRestrictionsLocked(removeUser);
13813                    } else {
13814                        // We need to set it back to 'installed' so the uninstall
13815                        // broadcasts will be sent correctly.
13816                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13817                        ps.setInstalled(true, user.getIdentifier());
13818                    }
13819                } else {
13820                    // This is a system app, so we assume that the
13821                    // other users still have this package installed, so all
13822                    // we need to do is clear this user's data and save that
13823                    // it is uninstalled.
13824                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13825                    removeUser = user.getIdentifier();
13826                    appId = ps.appId;
13827                    scheduleWritePackageRestrictionsLocked(removeUser);
13828                }
13829            }
13830        }
13831
13832        if (removeUser >= 0) {
13833            // From above, we determined that we are deleting this only
13834            // for a single user.  Continue the work here.
13835            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13836            if (outInfo != null) {
13837                outInfo.removedPackage = packageName;
13838                outInfo.removedAppId = appId;
13839                outInfo.removedUsers = new int[] {removeUser};
13840            }
13841            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13842            removeKeystoreDataIfNeeded(removeUser, appId);
13843            schedulePackageCleaning(packageName, removeUser, false);
13844            synchronized (mPackages) {
13845                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13846                    scheduleWritePackageRestrictionsLocked(removeUser);
13847                }
13848                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13849            }
13850            return true;
13851        }
13852
13853        if (dataOnly) {
13854            // Delete application data first
13855            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13856            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13857            return true;
13858        }
13859
13860        boolean ret = false;
13861        if (isSystemApp(ps)) {
13862            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13863            // When an updated system application is deleted we delete the existing resources as well and
13864            // fall back to existing code in system partition
13865            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13866                    flags, outInfo, writeSettings);
13867        } else {
13868            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13869            // Kill application pre-emptively especially for apps on sd.
13870            killApplication(packageName, ps.appId, "uninstall pkg");
13871            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13872                    allUserHandles, perUserInstalled,
13873                    outInfo, writeSettings);
13874        }
13875
13876        return ret;
13877    }
13878
13879    private final static class ClearStorageConnection implements ServiceConnection {
13880        IMediaContainerService mContainerService;
13881
13882        @Override
13883        public void onServiceConnected(ComponentName name, IBinder service) {
13884            synchronized (this) {
13885                mContainerService = IMediaContainerService.Stub.asInterface(service);
13886                notifyAll();
13887            }
13888        }
13889
13890        @Override
13891        public void onServiceDisconnected(ComponentName name) {
13892        }
13893    }
13894
13895    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13896        final boolean mounted;
13897        if (Environment.isExternalStorageEmulated()) {
13898            mounted = true;
13899        } else {
13900            final String status = Environment.getExternalStorageState();
13901
13902            mounted = status.equals(Environment.MEDIA_MOUNTED)
13903                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13904        }
13905
13906        if (!mounted) {
13907            return;
13908        }
13909
13910        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13911        int[] users;
13912        if (userId == UserHandle.USER_ALL) {
13913            users = sUserManager.getUserIds();
13914        } else {
13915            users = new int[] { userId };
13916        }
13917        final ClearStorageConnection conn = new ClearStorageConnection();
13918        if (mContext.bindServiceAsUser(
13919                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13920            try {
13921                for (int curUser : users) {
13922                    long timeout = SystemClock.uptimeMillis() + 5000;
13923                    synchronized (conn) {
13924                        long now = SystemClock.uptimeMillis();
13925                        while (conn.mContainerService == null && now < timeout) {
13926                            try {
13927                                conn.wait(timeout - now);
13928                            } catch (InterruptedException e) {
13929                            }
13930                        }
13931                    }
13932                    if (conn.mContainerService == null) {
13933                        return;
13934                    }
13935
13936                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13937                    clearDirectory(conn.mContainerService,
13938                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13939                    if (allData) {
13940                        clearDirectory(conn.mContainerService,
13941                                userEnv.buildExternalStorageAppDataDirs(packageName));
13942                        clearDirectory(conn.mContainerService,
13943                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13944                    }
13945                }
13946            } finally {
13947                mContext.unbindService(conn);
13948            }
13949        }
13950    }
13951
13952    @Override
13953    public void clearApplicationUserData(final String packageName,
13954            final IPackageDataObserver observer, final int userId) {
13955        mContext.enforceCallingOrSelfPermission(
13956                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13957        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13958        // Queue up an async operation since the package deletion may take a little while.
13959        mHandler.post(new Runnable() {
13960            public void run() {
13961                mHandler.removeCallbacks(this);
13962                final boolean succeeded;
13963                synchronized (mInstallLock) {
13964                    succeeded = clearApplicationUserDataLI(packageName, userId);
13965                }
13966                clearExternalStorageDataSync(packageName, userId, true);
13967                if (succeeded) {
13968                    // invoke DeviceStorageMonitor's update method to clear any notifications
13969                    DeviceStorageMonitorInternal
13970                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13971                    if (dsm != null) {
13972                        dsm.checkMemory();
13973                    }
13974                }
13975                if(observer != null) {
13976                    try {
13977                        observer.onRemoveCompleted(packageName, succeeded);
13978                    } catch (RemoteException e) {
13979                        Log.i(TAG, "Observer no longer exists.");
13980                    }
13981                } //end if observer
13982            } //end run
13983        });
13984    }
13985
13986    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13987        if (packageName == null) {
13988            Slog.w(TAG, "Attempt to delete null packageName.");
13989            return false;
13990        }
13991
13992        // Try finding details about the requested package
13993        PackageParser.Package pkg;
13994        synchronized (mPackages) {
13995            pkg = mPackages.get(packageName);
13996            if (pkg == null) {
13997                final PackageSetting ps = mSettings.mPackages.get(packageName);
13998                if (ps != null) {
13999                    pkg = ps.pkg;
14000                }
14001            }
14002
14003            if (pkg == null) {
14004                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14005                return false;
14006            }
14007
14008            PackageSetting ps = (PackageSetting) pkg.mExtras;
14009            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14010        }
14011
14012        // Always delete data directories for package, even if we found no other
14013        // record of app. This helps users recover from UID mismatches without
14014        // resorting to a full data wipe.
14015        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14016        if (retCode < 0) {
14017            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
14018            return false;
14019        }
14020
14021        final int appId = pkg.applicationInfo.uid;
14022        removeKeystoreDataIfNeeded(userId, appId);
14023
14024        // Create a native library symlink only if we have native libraries
14025        // and if the native libraries are 32 bit libraries. We do not provide
14026        // this symlink for 64 bit libraries.
14027        if (pkg.applicationInfo.primaryCpuAbi != null &&
14028                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14029            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14030            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14031                    nativeLibPath, userId) < 0) {
14032                Slog.w(TAG, "Failed linking native library dir");
14033                return false;
14034            }
14035        }
14036
14037        return true;
14038    }
14039
14040    /**
14041     * Reverts user permission state changes (permissions and flags) in
14042     * all packages for a given user.
14043     *
14044     * @param userId The device user for which to do a reset.
14045     */
14046    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14047        final int packageCount = mPackages.size();
14048        for (int i = 0; i < packageCount; i++) {
14049            PackageParser.Package pkg = mPackages.valueAt(i);
14050            PackageSetting ps = (PackageSetting) pkg.mExtras;
14051            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14052        }
14053    }
14054
14055    /**
14056     * Reverts user permission state changes (permissions and flags).
14057     *
14058     * @param ps The package for which to reset.
14059     * @param userId The device user for which to do a reset.
14060     */
14061    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14062            final PackageSetting ps, final int userId) {
14063        if (ps.pkg == null) {
14064            return;
14065        }
14066
14067        // These are flags that can change base on user actions.
14068        final int userSettableMask = FLAG_PERMISSION_USER_SET
14069                | FLAG_PERMISSION_USER_FIXED
14070                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14071                | FLAG_PERMISSION_REVIEW_REQUIRED;
14072
14073        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14074                | FLAG_PERMISSION_POLICY_FIXED;
14075
14076        boolean writeInstallPermissions = false;
14077        boolean writeRuntimePermissions = false;
14078
14079        final int permissionCount = ps.pkg.requestedPermissions.size();
14080        for (int i = 0; i < permissionCount; i++) {
14081            String permission = ps.pkg.requestedPermissions.get(i);
14082
14083            BasePermission bp = mSettings.mPermissions.get(permission);
14084            if (bp == null) {
14085                continue;
14086            }
14087
14088            // If shared user we just reset the state to which only this app contributed.
14089            if (ps.sharedUser != null) {
14090                boolean used = false;
14091                final int packageCount = ps.sharedUser.packages.size();
14092                for (int j = 0; j < packageCount; j++) {
14093                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14094                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14095                            && pkg.pkg.requestedPermissions.contains(permission)) {
14096                        used = true;
14097                        break;
14098                    }
14099                }
14100                if (used) {
14101                    continue;
14102                }
14103            }
14104
14105            PermissionsState permissionsState = ps.getPermissionsState();
14106
14107            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14108
14109            // Always clear the user settable flags.
14110            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14111                    bp.name) != null;
14112            // If permission review is enabled and this is a legacy app, mark the
14113            // permission as requiring a review as this is the initial state.
14114            int flags = 0;
14115            if (Build.PERMISSIONS_REVIEW_REQUIRED
14116                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14117                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14118            }
14119            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14120                if (hasInstallState) {
14121                    writeInstallPermissions = true;
14122                } else {
14123                    writeRuntimePermissions = true;
14124                }
14125            }
14126
14127            // Below is only runtime permission handling.
14128            if (!bp.isRuntime()) {
14129                continue;
14130            }
14131
14132            // Never clobber system or policy.
14133            if ((oldFlags & policyOrSystemFlags) != 0) {
14134                continue;
14135            }
14136
14137            // If this permission was granted by default, make sure it is.
14138            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14139                if (permissionsState.grantRuntimePermission(bp, userId)
14140                        != PERMISSION_OPERATION_FAILURE) {
14141                    writeRuntimePermissions = true;
14142                }
14143            // If permission review is enabled the permissions for a legacy apps
14144            // are represented as constantly granted runtime ones, so don't revoke.
14145            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14146                // Otherwise, reset the permission.
14147                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14148                switch (revokeResult) {
14149                    case PERMISSION_OPERATION_SUCCESS: {
14150                        writeRuntimePermissions = true;
14151                    } break;
14152
14153                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14154                        writeRuntimePermissions = true;
14155                        final int appId = ps.appId;
14156                        mHandler.post(new Runnable() {
14157                            @Override
14158                            public void run() {
14159                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14160                            }
14161                        });
14162                    } break;
14163                }
14164            }
14165        }
14166
14167        // Synchronously write as we are taking permissions away.
14168        if (writeRuntimePermissions) {
14169            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14170        }
14171
14172        // Synchronously write as we are taking permissions away.
14173        if (writeInstallPermissions) {
14174            mSettings.writeLPr();
14175        }
14176    }
14177
14178    /**
14179     * Remove entries from the keystore daemon. Will only remove it if the
14180     * {@code appId} is valid.
14181     */
14182    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14183        if (appId < 0) {
14184            return;
14185        }
14186
14187        final KeyStore keyStore = KeyStore.getInstance();
14188        if (keyStore != null) {
14189            if (userId == UserHandle.USER_ALL) {
14190                for (final int individual : sUserManager.getUserIds()) {
14191                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14192                }
14193            } else {
14194                keyStore.clearUid(UserHandle.getUid(userId, appId));
14195            }
14196        } else {
14197            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14198        }
14199    }
14200
14201    @Override
14202    public void deleteApplicationCacheFiles(final String packageName,
14203            final IPackageDataObserver observer) {
14204        mContext.enforceCallingOrSelfPermission(
14205                android.Manifest.permission.DELETE_CACHE_FILES, null);
14206        // Queue up an async operation since the package deletion may take a little while.
14207        final int userId = UserHandle.getCallingUserId();
14208        mHandler.post(new Runnable() {
14209            public void run() {
14210                mHandler.removeCallbacks(this);
14211                final boolean succeded;
14212                synchronized (mInstallLock) {
14213                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14214                }
14215                clearExternalStorageDataSync(packageName, userId, false);
14216                if (observer != null) {
14217                    try {
14218                        observer.onRemoveCompleted(packageName, succeded);
14219                    } catch (RemoteException e) {
14220                        Log.i(TAG, "Observer no longer exists.");
14221                    }
14222                } //end if observer
14223            } //end run
14224        });
14225    }
14226
14227    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14228        if (packageName == null) {
14229            Slog.w(TAG, "Attempt to delete null packageName.");
14230            return false;
14231        }
14232        PackageParser.Package p;
14233        synchronized (mPackages) {
14234            p = mPackages.get(packageName);
14235        }
14236        if (p == null) {
14237            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14238            return false;
14239        }
14240        final ApplicationInfo applicationInfo = p.applicationInfo;
14241        if (applicationInfo == null) {
14242            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14243            return false;
14244        }
14245        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14246        if (retCode < 0) {
14247            Slog.w(TAG, "Couldn't remove cache files for package: "
14248                       + packageName + " u" + userId);
14249            return false;
14250        }
14251        return true;
14252    }
14253
14254    @Override
14255    public void getPackageSizeInfo(final String packageName, int userHandle,
14256            final IPackageStatsObserver observer) {
14257        mContext.enforceCallingOrSelfPermission(
14258                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14259        if (packageName == null) {
14260            throw new IllegalArgumentException("Attempt to get size of null packageName");
14261        }
14262
14263        PackageStats stats = new PackageStats(packageName, userHandle);
14264
14265        /*
14266         * Queue up an async operation since the package measurement may take a
14267         * little while.
14268         */
14269        Message msg = mHandler.obtainMessage(INIT_COPY);
14270        msg.obj = new MeasureParams(stats, observer);
14271        mHandler.sendMessage(msg);
14272    }
14273
14274    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14275            PackageStats pStats) {
14276        if (packageName == null) {
14277            Slog.w(TAG, "Attempt to get size of null packageName.");
14278            return false;
14279        }
14280        PackageParser.Package p;
14281        boolean dataOnly = false;
14282        String libDirRoot = null;
14283        String asecPath = null;
14284        PackageSetting ps = null;
14285        synchronized (mPackages) {
14286            p = mPackages.get(packageName);
14287            ps = mSettings.mPackages.get(packageName);
14288            if(p == null) {
14289                dataOnly = true;
14290                if((ps == null) || (ps.pkg == null)) {
14291                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14292                    return false;
14293                }
14294                p = ps.pkg;
14295            }
14296            if (ps != null) {
14297                libDirRoot = ps.legacyNativeLibraryPathString;
14298            }
14299            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14300                final long token = Binder.clearCallingIdentity();
14301                try {
14302                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14303                    if (secureContainerId != null) {
14304                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14305                    }
14306                } finally {
14307                    Binder.restoreCallingIdentity(token);
14308                }
14309            }
14310        }
14311        String publicSrcDir = null;
14312        if(!dataOnly) {
14313            final ApplicationInfo applicationInfo = p.applicationInfo;
14314            if (applicationInfo == null) {
14315                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14316                return false;
14317            }
14318            if (p.isForwardLocked()) {
14319                publicSrcDir = applicationInfo.getBaseResourcePath();
14320            }
14321        }
14322        // TODO: extend to measure size of split APKs
14323        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14324        // not just the first level.
14325        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14326        // just the primary.
14327        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14328
14329        String apkPath;
14330        File packageDir = new File(p.codePath);
14331
14332        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14333            apkPath = packageDir.getAbsolutePath();
14334            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14335            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14336                libDirRoot = null;
14337            }
14338        } else {
14339            apkPath = p.baseCodePath;
14340        }
14341
14342        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14343                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14344        if (res < 0) {
14345            return false;
14346        }
14347
14348        // Fix-up for forward-locked applications in ASEC containers.
14349        if (!isExternal(p)) {
14350            pStats.codeSize += pStats.externalCodeSize;
14351            pStats.externalCodeSize = 0L;
14352        }
14353
14354        return true;
14355    }
14356
14357
14358    @Override
14359    public void addPackageToPreferred(String packageName) {
14360        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14361    }
14362
14363    @Override
14364    public void removePackageFromPreferred(String packageName) {
14365        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14366    }
14367
14368    @Override
14369    public List<PackageInfo> getPreferredPackages(int flags) {
14370        return new ArrayList<PackageInfo>();
14371    }
14372
14373    private int getUidTargetSdkVersionLockedLPr(int uid) {
14374        Object obj = mSettings.getUserIdLPr(uid);
14375        if (obj instanceof SharedUserSetting) {
14376            final SharedUserSetting sus = (SharedUserSetting) obj;
14377            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14378            final Iterator<PackageSetting> it = sus.packages.iterator();
14379            while (it.hasNext()) {
14380                final PackageSetting ps = it.next();
14381                if (ps.pkg != null) {
14382                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14383                    if (v < vers) vers = v;
14384                }
14385            }
14386            return vers;
14387        } else if (obj instanceof PackageSetting) {
14388            final PackageSetting ps = (PackageSetting) obj;
14389            if (ps.pkg != null) {
14390                return ps.pkg.applicationInfo.targetSdkVersion;
14391            }
14392        }
14393        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14394    }
14395
14396    @Override
14397    public void addPreferredActivity(IntentFilter filter, int match,
14398            ComponentName[] set, ComponentName activity, int userId) {
14399        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14400                "Adding preferred");
14401    }
14402
14403    private void addPreferredActivityInternal(IntentFilter filter, int match,
14404            ComponentName[] set, ComponentName activity, boolean always, int userId,
14405            String opname) {
14406        // writer
14407        int callingUid = Binder.getCallingUid();
14408        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14409        if (filter.countActions() == 0) {
14410            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14411            return;
14412        }
14413        synchronized (mPackages) {
14414            if (mContext.checkCallingOrSelfPermission(
14415                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14416                    != PackageManager.PERMISSION_GRANTED) {
14417                if (getUidTargetSdkVersionLockedLPr(callingUid)
14418                        < Build.VERSION_CODES.FROYO) {
14419                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14420                            + callingUid);
14421                    return;
14422                }
14423                mContext.enforceCallingOrSelfPermission(
14424                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14425            }
14426
14427            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14428            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14429                    + userId + ":");
14430            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14431            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14432            scheduleWritePackageRestrictionsLocked(userId);
14433        }
14434    }
14435
14436    @Override
14437    public void replacePreferredActivity(IntentFilter filter, int match,
14438            ComponentName[] set, ComponentName activity, int userId) {
14439        if (filter.countActions() != 1) {
14440            throw new IllegalArgumentException(
14441                    "replacePreferredActivity expects filter to have only 1 action.");
14442        }
14443        if (filter.countDataAuthorities() != 0
14444                || filter.countDataPaths() != 0
14445                || filter.countDataSchemes() > 1
14446                || filter.countDataTypes() != 0) {
14447            throw new IllegalArgumentException(
14448                    "replacePreferredActivity expects filter to have no data authorities, " +
14449                    "paths, or types; and at most one scheme.");
14450        }
14451
14452        final int callingUid = Binder.getCallingUid();
14453        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14454        synchronized (mPackages) {
14455            if (mContext.checkCallingOrSelfPermission(
14456                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14457                    != PackageManager.PERMISSION_GRANTED) {
14458                if (getUidTargetSdkVersionLockedLPr(callingUid)
14459                        < Build.VERSION_CODES.FROYO) {
14460                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14461                            + Binder.getCallingUid());
14462                    return;
14463                }
14464                mContext.enforceCallingOrSelfPermission(
14465                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14466            }
14467
14468            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14469            if (pir != null) {
14470                // Get all of the existing entries that exactly match this filter.
14471                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14472                if (existing != null && existing.size() == 1) {
14473                    PreferredActivity cur = existing.get(0);
14474                    if (DEBUG_PREFERRED) {
14475                        Slog.i(TAG, "Checking replace of preferred:");
14476                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14477                        if (!cur.mPref.mAlways) {
14478                            Slog.i(TAG, "  -- CUR; not mAlways!");
14479                        } else {
14480                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14481                            Slog.i(TAG, "  -- CUR: mSet="
14482                                    + Arrays.toString(cur.mPref.mSetComponents));
14483                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14484                            Slog.i(TAG, "  -- NEW: mMatch="
14485                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14486                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14487                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14488                        }
14489                    }
14490                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14491                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14492                            && cur.mPref.sameSet(set)) {
14493                        // Setting the preferred activity to what it happens to be already
14494                        if (DEBUG_PREFERRED) {
14495                            Slog.i(TAG, "Replacing with same preferred activity "
14496                                    + cur.mPref.mShortComponent + " for user "
14497                                    + userId + ":");
14498                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14499                        }
14500                        return;
14501                    }
14502                }
14503
14504                if (existing != null) {
14505                    if (DEBUG_PREFERRED) {
14506                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14507                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14508                    }
14509                    for (int i = 0; i < existing.size(); i++) {
14510                        PreferredActivity pa = existing.get(i);
14511                        if (DEBUG_PREFERRED) {
14512                            Slog.i(TAG, "Removing existing preferred activity "
14513                                    + pa.mPref.mComponent + ":");
14514                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14515                        }
14516                        pir.removeFilter(pa);
14517                    }
14518                }
14519            }
14520            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14521                    "Replacing preferred");
14522        }
14523    }
14524
14525    @Override
14526    public void clearPackagePreferredActivities(String packageName) {
14527        final int uid = Binder.getCallingUid();
14528        // writer
14529        synchronized (mPackages) {
14530            PackageParser.Package pkg = mPackages.get(packageName);
14531            if (pkg == null || pkg.applicationInfo.uid != uid) {
14532                if (mContext.checkCallingOrSelfPermission(
14533                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14534                        != PackageManager.PERMISSION_GRANTED) {
14535                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14536                            < Build.VERSION_CODES.FROYO) {
14537                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14538                                + Binder.getCallingUid());
14539                        return;
14540                    }
14541                    mContext.enforceCallingOrSelfPermission(
14542                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14543                }
14544            }
14545
14546            int user = UserHandle.getCallingUserId();
14547            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14548                scheduleWritePackageRestrictionsLocked(user);
14549            }
14550        }
14551    }
14552
14553    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14554    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14555        ArrayList<PreferredActivity> removed = null;
14556        boolean changed = false;
14557        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14558            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14559            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14560            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14561                continue;
14562            }
14563            Iterator<PreferredActivity> it = pir.filterIterator();
14564            while (it.hasNext()) {
14565                PreferredActivity pa = it.next();
14566                // Mark entry for removal only if it matches the package name
14567                // and the entry is of type "always".
14568                if (packageName == null ||
14569                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14570                                && pa.mPref.mAlways)) {
14571                    if (removed == null) {
14572                        removed = new ArrayList<PreferredActivity>();
14573                    }
14574                    removed.add(pa);
14575                }
14576            }
14577            if (removed != null) {
14578                for (int j=0; j<removed.size(); j++) {
14579                    PreferredActivity pa = removed.get(j);
14580                    pir.removeFilter(pa);
14581                }
14582                changed = true;
14583            }
14584        }
14585        return changed;
14586    }
14587
14588    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14589    private void clearIntentFilterVerificationsLPw(int userId) {
14590        final int packageCount = mPackages.size();
14591        for (int i = 0; i < packageCount; i++) {
14592            PackageParser.Package pkg = mPackages.valueAt(i);
14593            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14594        }
14595    }
14596
14597    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14598    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14599        if (userId == UserHandle.USER_ALL) {
14600            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14601                    sUserManager.getUserIds())) {
14602                for (int oneUserId : sUserManager.getUserIds()) {
14603                    scheduleWritePackageRestrictionsLocked(oneUserId);
14604                }
14605            }
14606        } else {
14607            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14608                scheduleWritePackageRestrictionsLocked(userId);
14609            }
14610        }
14611    }
14612
14613    void clearDefaultBrowserIfNeeded(String packageName) {
14614        for (int oneUserId : sUserManager.getUserIds()) {
14615            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14616            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14617            if (packageName.equals(defaultBrowserPackageName)) {
14618                setDefaultBrowserPackageName(null, oneUserId);
14619            }
14620        }
14621    }
14622
14623    @Override
14624    public void resetApplicationPreferences(int userId) {
14625        mContext.enforceCallingOrSelfPermission(
14626                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14627        // writer
14628        synchronized (mPackages) {
14629            final long identity = Binder.clearCallingIdentity();
14630            try {
14631                clearPackagePreferredActivitiesLPw(null, userId);
14632                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14633                // TODO: We have to reset the default SMS and Phone. This requires
14634                // significant refactoring to keep all default apps in the package
14635                // manager (cleaner but more work) or have the services provide
14636                // callbacks to the package manager to request a default app reset.
14637                applyFactoryDefaultBrowserLPw(userId);
14638                clearIntentFilterVerificationsLPw(userId);
14639                primeDomainVerificationsLPw(userId);
14640                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14641                scheduleWritePackageRestrictionsLocked(userId);
14642            } finally {
14643                Binder.restoreCallingIdentity(identity);
14644            }
14645        }
14646    }
14647
14648    @Override
14649    public int getPreferredActivities(List<IntentFilter> outFilters,
14650            List<ComponentName> outActivities, String packageName) {
14651
14652        int num = 0;
14653        final int userId = UserHandle.getCallingUserId();
14654        // reader
14655        synchronized (mPackages) {
14656            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14657            if (pir != null) {
14658                final Iterator<PreferredActivity> it = pir.filterIterator();
14659                while (it.hasNext()) {
14660                    final PreferredActivity pa = it.next();
14661                    if (packageName == null
14662                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14663                                    && pa.mPref.mAlways)) {
14664                        if (outFilters != null) {
14665                            outFilters.add(new IntentFilter(pa));
14666                        }
14667                        if (outActivities != null) {
14668                            outActivities.add(pa.mPref.mComponent);
14669                        }
14670                    }
14671                }
14672            }
14673        }
14674
14675        return num;
14676    }
14677
14678    @Override
14679    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14680            int userId) {
14681        int callingUid = Binder.getCallingUid();
14682        if (callingUid != Process.SYSTEM_UID) {
14683            throw new SecurityException(
14684                    "addPersistentPreferredActivity can only be run by the system");
14685        }
14686        if (filter.countActions() == 0) {
14687            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14688            return;
14689        }
14690        synchronized (mPackages) {
14691            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14692                    " :");
14693            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14694            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14695                    new PersistentPreferredActivity(filter, activity));
14696            scheduleWritePackageRestrictionsLocked(userId);
14697        }
14698    }
14699
14700    @Override
14701    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14702        int callingUid = Binder.getCallingUid();
14703        if (callingUid != Process.SYSTEM_UID) {
14704            throw new SecurityException(
14705                    "clearPackagePersistentPreferredActivities can only be run by the system");
14706        }
14707        ArrayList<PersistentPreferredActivity> removed = null;
14708        boolean changed = false;
14709        synchronized (mPackages) {
14710            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14711                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14712                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14713                        .valueAt(i);
14714                if (userId != thisUserId) {
14715                    continue;
14716                }
14717                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14718                while (it.hasNext()) {
14719                    PersistentPreferredActivity ppa = it.next();
14720                    // Mark entry for removal only if it matches the package name.
14721                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14722                        if (removed == null) {
14723                            removed = new ArrayList<PersistentPreferredActivity>();
14724                        }
14725                        removed.add(ppa);
14726                    }
14727                }
14728                if (removed != null) {
14729                    for (int j=0; j<removed.size(); j++) {
14730                        PersistentPreferredActivity ppa = removed.get(j);
14731                        ppir.removeFilter(ppa);
14732                    }
14733                    changed = true;
14734                }
14735            }
14736
14737            if (changed) {
14738                scheduleWritePackageRestrictionsLocked(userId);
14739            }
14740        }
14741    }
14742
14743    /**
14744     * Common machinery for picking apart a restored XML blob and passing
14745     * it to a caller-supplied functor to be applied to the running system.
14746     */
14747    private void restoreFromXml(XmlPullParser parser, int userId,
14748            String expectedStartTag, BlobXmlRestorer functor)
14749            throws IOException, XmlPullParserException {
14750        int type;
14751        while ((type = parser.next()) != XmlPullParser.START_TAG
14752                && type != XmlPullParser.END_DOCUMENT) {
14753        }
14754        if (type != XmlPullParser.START_TAG) {
14755            // oops didn't find a start tag?!
14756            if (DEBUG_BACKUP) {
14757                Slog.e(TAG, "Didn't find start tag during restore");
14758            }
14759            return;
14760        }
14761
14762        // this is supposed to be TAG_PREFERRED_BACKUP
14763        if (!expectedStartTag.equals(parser.getName())) {
14764            if (DEBUG_BACKUP) {
14765                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14766            }
14767            return;
14768        }
14769
14770        // skip interfering stuff, then we're aligned with the backing implementation
14771        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14772        functor.apply(parser, userId);
14773    }
14774
14775    private interface BlobXmlRestorer {
14776        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14777    }
14778
14779    /**
14780     * Non-Binder method, support for the backup/restore mechanism: write the
14781     * full set of preferred activities in its canonical XML format.  Returns the
14782     * XML output as a byte array, or null if there is none.
14783     */
14784    @Override
14785    public byte[] getPreferredActivityBackup(int userId) {
14786        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14787            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14788        }
14789
14790        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14791        try {
14792            final XmlSerializer serializer = new FastXmlSerializer();
14793            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14794            serializer.startDocument(null, true);
14795            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14796
14797            synchronized (mPackages) {
14798                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14799            }
14800
14801            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14802            serializer.endDocument();
14803            serializer.flush();
14804        } catch (Exception e) {
14805            if (DEBUG_BACKUP) {
14806                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14807            }
14808            return null;
14809        }
14810
14811        return dataStream.toByteArray();
14812    }
14813
14814    @Override
14815    public void restorePreferredActivities(byte[] backup, int userId) {
14816        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14817            throw new SecurityException("Only the system may call restorePreferredActivities()");
14818        }
14819
14820        try {
14821            final XmlPullParser parser = Xml.newPullParser();
14822            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14823            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14824                    new BlobXmlRestorer() {
14825                        @Override
14826                        public void apply(XmlPullParser parser, int userId)
14827                                throws XmlPullParserException, IOException {
14828                            synchronized (mPackages) {
14829                                mSettings.readPreferredActivitiesLPw(parser, userId);
14830                            }
14831                        }
14832                    } );
14833        } catch (Exception e) {
14834            if (DEBUG_BACKUP) {
14835                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14836            }
14837        }
14838    }
14839
14840    /**
14841     * Non-Binder method, support for the backup/restore mechanism: write the
14842     * default browser (etc) settings in its canonical XML format.  Returns the default
14843     * browser XML representation as a byte array, or null if there is none.
14844     */
14845    @Override
14846    public byte[] getDefaultAppsBackup(int userId) {
14847        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14848            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14849        }
14850
14851        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14852        try {
14853            final XmlSerializer serializer = new FastXmlSerializer();
14854            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14855            serializer.startDocument(null, true);
14856            serializer.startTag(null, TAG_DEFAULT_APPS);
14857
14858            synchronized (mPackages) {
14859                mSettings.writeDefaultAppsLPr(serializer, userId);
14860            }
14861
14862            serializer.endTag(null, TAG_DEFAULT_APPS);
14863            serializer.endDocument();
14864            serializer.flush();
14865        } catch (Exception e) {
14866            if (DEBUG_BACKUP) {
14867                Slog.e(TAG, "Unable to write default apps for backup", e);
14868            }
14869            return null;
14870        }
14871
14872        return dataStream.toByteArray();
14873    }
14874
14875    @Override
14876    public void restoreDefaultApps(byte[] backup, int userId) {
14877        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14878            throw new SecurityException("Only the system may call restoreDefaultApps()");
14879        }
14880
14881        try {
14882            final XmlPullParser parser = Xml.newPullParser();
14883            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14884            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14885                    new BlobXmlRestorer() {
14886                        @Override
14887                        public void apply(XmlPullParser parser, int userId)
14888                                throws XmlPullParserException, IOException {
14889                            synchronized (mPackages) {
14890                                mSettings.readDefaultAppsLPw(parser, userId);
14891                            }
14892                        }
14893                    } );
14894        } catch (Exception e) {
14895            if (DEBUG_BACKUP) {
14896                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14897            }
14898        }
14899    }
14900
14901    @Override
14902    public byte[] getIntentFilterVerificationBackup(int userId) {
14903        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14904            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14905        }
14906
14907        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14908        try {
14909            final XmlSerializer serializer = new FastXmlSerializer();
14910            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14911            serializer.startDocument(null, true);
14912            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14913
14914            synchronized (mPackages) {
14915                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14916            }
14917
14918            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14919            serializer.endDocument();
14920            serializer.flush();
14921        } catch (Exception e) {
14922            if (DEBUG_BACKUP) {
14923                Slog.e(TAG, "Unable to write default apps for backup", e);
14924            }
14925            return null;
14926        }
14927
14928        return dataStream.toByteArray();
14929    }
14930
14931    @Override
14932    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14933        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14934            throw new SecurityException("Only the system may call restorePreferredActivities()");
14935        }
14936
14937        try {
14938            final XmlPullParser parser = Xml.newPullParser();
14939            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14940            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14941                    new BlobXmlRestorer() {
14942                        @Override
14943                        public void apply(XmlPullParser parser, int userId)
14944                                throws XmlPullParserException, IOException {
14945                            synchronized (mPackages) {
14946                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14947                                mSettings.writeLPr();
14948                            }
14949                        }
14950                    } );
14951        } catch (Exception e) {
14952            if (DEBUG_BACKUP) {
14953                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14954            }
14955        }
14956    }
14957
14958    @Override
14959    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14960            int sourceUserId, int targetUserId, int flags) {
14961        mContext.enforceCallingOrSelfPermission(
14962                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14963        int callingUid = Binder.getCallingUid();
14964        enforceOwnerRights(ownerPackage, callingUid);
14965        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14966        if (intentFilter.countActions() == 0) {
14967            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14968            return;
14969        }
14970        synchronized (mPackages) {
14971            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14972                    ownerPackage, targetUserId, flags);
14973            CrossProfileIntentResolver resolver =
14974                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14975            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14976            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14977            if (existing != null) {
14978                int size = existing.size();
14979                for (int i = 0; i < size; i++) {
14980                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14981                        return;
14982                    }
14983                }
14984            }
14985            resolver.addFilter(newFilter);
14986            scheduleWritePackageRestrictionsLocked(sourceUserId);
14987        }
14988    }
14989
14990    @Override
14991    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14992        mContext.enforceCallingOrSelfPermission(
14993                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14994        int callingUid = Binder.getCallingUid();
14995        enforceOwnerRights(ownerPackage, callingUid);
14996        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14997        synchronized (mPackages) {
14998            CrossProfileIntentResolver resolver =
14999                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15000            ArraySet<CrossProfileIntentFilter> set =
15001                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15002            for (CrossProfileIntentFilter filter : set) {
15003                if (filter.getOwnerPackage().equals(ownerPackage)) {
15004                    resolver.removeFilter(filter);
15005                }
15006            }
15007            scheduleWritePackageRestrictionsLocked(sourceUserId);
15008        }
15009    }
15010
15011    // Enforcing that callingUid is owning pkg on userId
15012    private void enforceOwnerRights(String pkg, int callingUid) {
15013        // The system owns everything.
15014        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15015            return;
15016        }
15017        int callingUserId = UserHandle.getUserId(callingUid);
15018        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15019        if (pi == null) {
15020            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15021                    + callingUserId);
15022        }
15023        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15024            throw new SecurityException("Calling uid " + callingUid
15025                    + " does not own package " + pkg);
15026        }
15027    }
15028
15029    @Override
15030    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15031        Intent intent = new Intent(Intent.ACTION_MAIN);
15032        intent.addCategory(Intent.CATEGORY_HOME);
15033
15034        final int callingUserId = UserHandle.getCallingUserId();
15035        List<ResolveInfo> list = queryIntentActivities(intent, null,
15036                PackageManager.GET_META_DATA, callingUserId);
15037        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15038                true, false, false, callingUserId);
15039
15040        allHomeCandidates.clear();
15041        if (list != null) {
15042            for (ResolveInfo ri : list) {
15043                allHomeCandidates.add(ri);
15044            }
15045        }
15046        return (preferred == null || preferred.activityInfo == null)
15047                ? null
15048                : new ComponentName(preferred.activityInfo.packageName,
15049                        preferred.activityInfo.name);
15050    }
15051
15052    @Override
15053    public void setApplicationEnabledSetting(String appPackageName,
15054            int newState, int flags, int userId, String callingPackage) {
15055        if (!sUserManager.exists(userId)) return;
15056        if (callingPackage == null) {
15057            callingPackage = Integer.toString(Binder.getCallingUid());
15058        }
15059        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15060    }
15061
15062    @Override
15063    public void setComponentEnabledSetting(ComponentName componentName,
15064            int newState, int flags, int userId) {
15065        if (!sUserManager.exists(userId)) return;
15066        setEnabledSetting(componentName.getPackageName(),
15067                componentName.getClassName(), newState, flags, userId, null);
15068    }
15069
15070    private void setEnabledSetting(final String packageName, String className, int newState,
15071            final int flags, int userId, String callingPackage) {
15072        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15073              || newState == COMPONENT_ENABLED_STATE_ENABLED
15074              || newState == COMPONENT_ENABLED_STATE_DISABLED
15075              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15076              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15077            throw new IllegalArgumentException("Invalid new component state: "
15078                    + newState);
15079        }
15080        PackageSetting pkgSetting;
15081        final int uid = Binder.getCallingUid();
15082        final int permission = mContext.checkCallingOrSelfPermission(
15083                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15084        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15085        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15086        boolean sendNow = false;
15087        boolean isApp = (className == null);
15088        String componentName = isApp ? packageName : className;
15089        int packageUid = -1;
15090        ArrayList<String> components;
15091
15092        // writer
15093        synchronized (mPackages) {
15094            pkgSetting = mSettings.mPackages.get(packageName);
15095            if (pkgSetting == null) {
15096                if (className == null) {
15097                    throw new IllegalArgumentException(
15098                            "Unknown package: " + packageName);
15099                }
15100                throw new IllegalArgumentException(
15101                        "Unknown component: " + packageName
15102                        + "/" + className);
15103            }
15104            // Allow root and verify that userId is not being specified by a different user
15105            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15106                throw new SecurityException(
15107                        "Permission Denial: attempt to change component state from pid="
15108                        + Binder.getCallingPid()
15109                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15110            }
15111            if (className == null) {
15112                // We're dealing with an application/package level state change
15113                if (pkgSetting.getEnabled(userId) == newState) {
15114                    // Nothing to do
15115                    return;
15116                }
15117                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15118                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15119                    // Don't care about who enables an app.
15120                    callingPackage = null;
15121                }
15122                pkgSetting.setEnabled(newState, userId, callingPackage);
15123                // pkgSetting.pkg.mSetEnabled = newState;
15124            } else {
15125                // We're dealing with a component level state change
15126                // First, verify that this is a valid class name.
15127                PackageParser.Package pkg = pkgSetting.pkg;
15128                if (pkg == null || !pkg.hasComponentClassName(className)) {
15129                    if (pkg != null &&
15130                            pkg.applicationInfo.targetSdkVersion >=
15131                                    Build.VERSION_CODES.JELLY_BEAN) {
15132                        throw new IllegalArgumentException("Component class " + className
15133                                + " does not exist in " + packageName);
15134                    } else {
15135                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15136                                + className + " does not exist in " + packageName);
15137                    }
15138                }
15139                switch (newState) {
15140                case COMPONENT_ENABLED_STATE_ENABLED:
15141                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15142                        return;
15143                    }
15144                    break;
15145                case COMPONENT_ENABLED_STATE_DISABLED:
15146                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15147                        return;
15148                    }
15149                    break;
15150                case COMPONENT_ENABLED_STATE_DEFAULT:
15151                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15152                        return;
15153                    }
15154                    break;
15155                default:
15156                    Slog.e(TAG, "Invalid new component state: " + newState);
15157                    return;
15158                }
15159            }
15160            scheduleWritePackageRestrictionsLocked(userId);
15161            components = mPendingBroadcasts.get(userId, packageName);
15162            final boolean newPackage = components == null;
15163            if (newPackage) {
15164                components = new ArrayList<String>();
15165            }
15166            if (!components.contains(componentName)) {
15167                components.add(componentName);
15168            }
15169            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15170                sendNow = true;
15171                // Purge entry from pending broadcast list if another one exists already
15172                // since we are sending one right away.
15173                mPendingBroadcasts.remove(userId, packageName);
15174            } else {
15175                if (newPackage) {
15176                    mPendingBroadcasts.put(userId, packageName, components);
15177                }
15178                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15179                    // Schedule a message
15180                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15181                }
15182            }
15183        }
15184
15185        long callingId = Binder.clearCallingIdentity();
15186        try {
15187            if (sendNow) {
15188                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15189                sendPackageChangedBroadcast(packageName,
15190                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15191            }
15192        } finally {
15193            Binder.restoreCallingIdentity(callingId);
15194        }
15195    }
15196
15197    private void sendPackageChangedBroadcast(String packageName,
15198            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15199        if (DEBUG_INSTALL)
15200            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15201                    + componentNames);
15202        Bundle extras = new Bundle(4);
15203        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15204        String nameList[] = new String[componentNames.size()];
15205        componentNames.toArray(nameList);
15206        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15207        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15208        extras.putInt(Intent.EXTRA_UID, packageUid);
15209        // If this is not reporting a change of the overall package, then only send it
15210        // to registered receivers.  We don't want to launch a swath of apps for every
15211        // little component state change.
15212        final int flags = !componentNames.contains(packageName)
15213                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15214        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15215                new int[] {UserHandle.getUserId(packageUid)});
15216    }
15217
15218    @Override
15219    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15220        if (!sUserManager.exists(userId)) return;
15221        final int uid = Binder.getCallingUid();
15222        final int permission = mContext.checkCallingOrSelfPermission(
15223                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15224        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15225        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15226        // writer
15227        synchronized (mPackages) {
15228            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15229                    allowedByPermission, uid, userId)) {
15230                scheduleWritePackageRestrictionsLocked(userId);
15231            }
15232        }
15233    }
15234
15235    @Override
15236    public String getInstallerPackageName(String packageName) {
15237        // reader
15238        synchronized (mPackages) {
15239            return mSettings.getInstallerPackageNameLPr(packageName);
15240        }
15241    }
15242
15243    @Override
15244    public int getApplicationEnabledSetting(String packageName, int userId) {
15245        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15246        int uid = Binder.getCallingUid();
15247        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15248        // reader
15249        synchronized (mPackages) {
15250            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15251        }
15252    }
15253
15254    @Override
15255    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15256        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15257        int uid = Binder.getCallingUid();
15258        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15259        // reader
15260        synchronized (mPackages) {
15261            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15262        }
15263    }
15264
15265    @Override
15266    public void enterSafeMode() {
15267        enforceSystemOrRoot("Only the system can request entering safe mode");
15268
15269        if (!mSystemReady) {
15270            mSafeMode = true;
15271        }
15272    }
15273
15274    @Override
15275    public void systemReady() {
15276        mSystemReady = true;
15277
15278        // Read the compatibilty setting when the system is ready.
15279        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15280                mContext.getContentResolver(),
15281                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15282        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15283        if (DEBUG_SETTINGS) {
15284            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15285        }
15286
15287        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15288
15289        synchronized (mPackages) {
15290            // Verify that all of the preferred activity components actually
15291            // exist.  It is possible for applications to be updated and at
15292            // that point remove a previously declared activity component that
15293            // had been set as a preferred activity.  We try to clean this up
15294            // the next time we encounter that preferred activity, but it is
15295            // possible for the user flow to never be able to return to that
15296            // situation so here we do a sanity check to make sure we haven't
15297            // left any junk around.
15298            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15299            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15300                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15301                removed.clear();
15302                for (PreferredActivity pa : pir.filterSet()) {
15303                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15304                        removed.add(pa);
15305                    }
15306                }
15307                if (removed.size() > 0) {
15308                    for (int r=0; r<removed.size(); r++) {
15309                        PreferredActivity pa = removed.get(r);
15310                        Slog.w(TAG, "Removing dangling preferred activity: "
15311                                + pa.mPref.mComponent);
15312                        pir.removeFilter(pa);
15313                    }
15314                    mSettings.writePackageRestrictionsLPr(
15315                            mSettings.mPreferredActivities.keyAt(i));
15316                }
15317            }
15318
15319            for (int userId : UserManagerService.getInstance().getUserIds()) {
15320                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15321                    grantPermissionsUserIds = ArrayUtils.appendInt(
15322                            grantPermissionsUserIds, userId);
15323                }
15324            }
15325        }
15326        sUserManager.systemReady();
15327
15328        // If we upgraded grant all default permissions before kicking off.
15329        for (int userId : grantPermissionsUserIds) {
15330            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15331        }
15332
15333        // Kick off any messages waiting for system ready
15334        if (mPostSystemReadyMessages != null) {
15335            for (Message msg : mPostSystemReadyMessages) {
15336                msg.sendToTarget();
15337            }
15338            mPostSystemReadyMessages = null;
15339        }
15340
15341        // Watch for external volumes that come and go over time
15342        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15343        storage.registerListener(mStorageListener);
15344
15345        mInstallerService.systemReady();
15346        mPackageDexOptimizer.systemReady();
15347
15348        MountServiceInternal mountServiceInternal = LocalServices.getService(
15349                MountServiceInternal.class);
15350        mountServiceInternal.addExternalStoragePolicy(
15351                new MountServiceInternal.ExternalStorageMountPolicy() {
15352            @Override
15353            public int getMountMode(int uid, String packageName) {
15354                if (Process.isIsolated(uid)) {
15355                    return Zygote.MOUNT_EXTERNAL_NONE;
15356                }
15357                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15358                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15359                }
15360                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15361                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15362                }
15363                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15364                    return Zygote.MOUNT_EXTERNAL_READ;
15365                }
15366                return Zygote.MOUNT_EXTERNAL_WRITE;
15367            }
15368
15369            @Override
15370            public boolean hasExternalStorage(int uid, String packageName) {
15371                return true;
15372            }
15373        });
15374    }
15375
15376    @Override
15377    public boolean isSafeMode() {
15378        return mSafeMode;
15379    }
15380
15381    @Override
15382    public boolean hasSystemUidErrors() {
15383        return mHasSystemUidErrors;
15384    }
15385
15386    static String arrayToString(int[] array) {
15387        StringBuffer buf = new StringBuffer(128);
15388        buf.append('[');
15389        if (array != null) {
15390            for (int i=0; i<array.length; i++) {
15391                if (i > 0) buf.append(", ");
15392                buf.append(array[i]);
15393            }
15394        }
15395        buf.append(']');
15396        return buf.toString();
15397    }
15398
15399    static class DumpState {
15400        public static final int DUMP_LIBS = 1 << 0;
15401        public static final int DUMP_FEATURES = 1 << 1;
15402        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15403        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15404        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15405        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15406        public static final int DUMP_PERMISSIONS = 1 << 6;
15407        public static final int DUMP_PACKAGES = 1 << 7;
15408        public static final int DUMP_SHARED_USERS = 1 << 8;
15409        public static final int DUMP_MESSAGES = 1 << 9;
15410        public static final int DUMP_PROVIDERS = 1 << 10;
15411        public static final int DUMP_VERIFIERS = 1 << 11;
15412        public static final int DUMP_PREFERRED = 1 << 12;
15413        public static final int DUMP_PREFERRED_XML = 1 << 13;
15414        public static final int DUMP_KEYSETS = 1 << 14;
15415        public static final int DUMP_VERSION = 1 << 15;
15416        public static final int DUMP_INSTALLS = 1 << 16;
15417        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15418        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15419
15420        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15421
15422        private int mTypes;
15423
15424        private int mOptions;
15425
15426        private boolean mTitlePrinted;
15427
15428        private SharedUserSetting mSharedUser;
15429
15430        public boolean isDumping(int type) {
15431            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15432                return true;
15433            }
15434
15435            return (mTypes & type) != 0;
15436        }
15437
15438        public void setDump(int type) {
15439            mTypes |= type;
15440        }
15441
15442        public boolean isOptionEnabled(int option) {
15443            return (mOptions & option) != 0;
15444        }
15445
15446        public void setOptionEnabled(int option) {
15447            mOptions |= option;
15448        }
15449
15450        public boolean onTitlePrinted() {
15451            final boolean printed = mTitlePrinted;
15452            mTitlePrinted = true;
15453            return printed;
15454        }
15455
15456        public boolean getTitlePrinted() {
15457            return mTitlePrinted;
15458        }
15459
15460        public void setTitlePrinted(boolean enabled) {
15461            mTitlePrinted = enabled;
15462        }
15463
15464        public SharedUserSetting getSharedUser() {
15465            return mSharedUser;
15466        }
15467
15468        public void setSharedUser(SharedUserSetting user) {
15469            mSharedUser = user;
15470        }
15471    }
15472
15473    @Override
15474    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15475            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15476        (new PackageManagerShellCommand(this)).exec(
15477                this, in, out, err, args, resultReceiver);
15478    }
15479
15480    @Override
15481    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15482        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15483                != PackageManager.PERMISSION_GRANTED) {
15484            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15485                    + Binder.getCallingPid()
15486                    + ", uid=" + Binder.getCallingUid()
15487                    + " without permission "
15488                    + android.Manifest.permission.DUMP);
15489            return;
15490        }
15491
15492        DumpState dumpState = new DumpState();
15493        boolean fullPreferred = false;
15494        boolean checkin = false;
15495
15496        String packageName = null;
15497        ArraySet<String> permissionNames = null;
15498
15499        int opti = 0;
15500        while (opti < args.length) {
15501            String opt = args[opti];
15502            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15503                break;
15504            }
15505            opti++;
15506
15507            if ("-a".equals(opt)) {
15508                // Right now we only know how to print all.
15509            } else if ("-h".equals(opt)) {
15510                pw.println("Package manager dump options:");
15511                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15512                pw.println("    --checkin: dump for a checkin");
15513                pw.println("    -f: print details of intent filters");
15514                pw.println("    -h: print this help");
15515                pw.println("  cmd may be one of:");
15516                pw.println("    l[ibraries]: list known shared libraries");
15517                pw.println("    f[eatures]: list device features");
15518                pw.println("    k[eysets]: print known keysets");
15519                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15520                pw.println("    perm[issions]: dump permissions");
15521                pw.println("    permission [name ...]: dump declaration and use of given permission");
15522                pw.println("    pref[erred]: print preferred package settings");
15523                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15524                pw.println("    prov[iders]: dump content providers");
15525                pw.println("    p[ackages]: dump installed packages");
15526                pw.println("    s[hared-users]: dump shared user IDs");
15527                pw.println("    m[essages]: print collected runtime messages");
15528                pw.println("    v[erifiers]: print package verifier info");
15529                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15530                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15531                pw.println("    version: print database version info");
15532                pw.println("    write: write current settings now");
15533                pw.println("    installs: details about install sessions");
15534                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15535                pw.println("    <package.name>: info about given package");
15536                return;
15537            } else if ("--checkin".equals(opt)) {
15538                checkin = true;
15539            } else if ("-f".equals(opt)) {
15540                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15541            } else {
15542                pw.println("Unknown argument: " + opt + "; use -h for help");
15543            }
15544        }
15545
15546        // Is the caller requesting to dump a particular piece of data?
15547        if (opti < args.length) {
15548            String cmd = args[opti];
15549            opti++;
15550            // Is this a package name?
15551            if ("android".equals(cmd) || cmd.contains(".")) {
15552                packageName = cmd;
15553                // When dumping a single package, we always dump all of its
15554                // filter information since the amount of data will be reasonable.
15555                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15556            } else if ("check-permission".equals(cmd)) {
15557                if (opti >= args.length) {
15558                    pw.println("Error: check-permission missing permission argument");
15559                    return;
15560                }
15561                String perm = args[opti];
15562                opti++;
15563                if (opti >= args.length) {
15564                    pw.println("Error: check-permission missing package argument");
15565                    return;
15566                }
15567                String pkg = args[opti];
15568                opti++;
15569                int user = UserHandle.getUserId(Binder.getCallingUid());
15570                if (opti < args.length) {
15571                    try {
15572                        user = Integer.parseInt(args[opti]);
15573                    } catch (NumberFormatException e) {
15574                        pw.println("Error: check-permission user argument is not a number: "
15575                                + args[opti]);
15576                        return;
15577                    }
15578                }
15579                pw.println(checkPermission(perm, pkg, user));
15580                return;
15581            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15582                dumpState.setDump(DumpState.DUMP_LIBS);
15583            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15584                dumpState.setDump(DumpState.DUMP_FEATURES);
15585            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15586                if (opti >= args.length) {
15587                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15588                            | DumpState.DUMP_SERVICE_RESOLVERS
15589                            | DumpState.DUMP_RECEIVER_RESOLVERS
15590                            | DumpState.DUMP_CONTENT_RESOLVERS);
15591                } else {
15592                    while (opti < args.length) {
15593                        String name = args[opti];
15594                        if ("a".equals(name) || "activity".equals(name)) {
15595                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15596                        } else if ("s".equals(name) || "service".equals(name)) {
15597                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15598                        } else if ("r".equals(name) || "receiver".equals(name)) {
15599                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15600                        } else if ("c".equals(name) || "content".equals(name)) {
15601                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15602                        } else {
15603                            pw.println("Error: unknown resolver table type: " + name);
15604                            return;
15605                        }
15606                        opti++;
15607                    }
15608                }
15609            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15610                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15611            } else if ("permission".equals(cmd)) {
15612                if (opti >= args.length) {
15613                    pw.println("Error: permission requires permission name");
15614                    return;
15615                }
15616                permissionNames = new ArraySet<>();
15617                while (opti < args.length) {
15618                    permissionNames.add(args[opti]);
15619                    opti++;
15620                }
15621                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15622                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15623            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15624                dumpState.setDump(DumpState.DUMP_PREFERRED);
15625            } else if ("preferred-xml".equals(cmd)) {
15626                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15627                if (opti < args.length && "--full".equals(args[opti])) {
15628                    fullPreferred = true;
15629                    opti++;
15630                }
15631            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15632                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15633            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15634                dumpState.setDump(DumpState.DUMP_PACKAGES);
15635            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15636                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15637            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15638                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15639            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15640                dumpState.setDump(DumpState.DUMP_MESSAGES);
15641            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15642                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15643            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15644                    || "intent-filter-verifiers".equals(cmd)) {
15645                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15646            } else if ("version".equals(cmd)) {
15647                dumpState.setDump(DumpState.DUMP_VERSION);
15648            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15649                dumpState.setDump(DumpState.DUMP_KEYSETS);
15650            } else if ("installs".equals(cmd)) {
15651                dumpState.setDump(DumpState.DUMP_INSTALLS);
15652            } else if ("write".equals(cmd)) {
15653                synchronized (mPackages) {
15654                    mSettings.writeLPr();
15655                    pw.println("Settings written.");
15656                    return;
15657                }
15658            }
15659        }
15660
15661        if (checkin) {
15662            pw.println("vers,1");
15663        }
15664
15665        // reader
15666        synchronized (mPackages) {
15667            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15668                if (!checkin) {
15669                    if (dumpState.onTitlePrinted())
15670                        pw.println();
15671                    pw.println("Database versions:");
15672                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15673                }
15674            }
15675
15676            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15677                if (!checkin) {
15678                    if (dumpState.onTitlePrinted())
15679                        pw.println();
15680                    pw.println("Verifiers:");
15681                    pw.print("  Required: ");
15682                    pw.print(mRequiredVerifierPackage);
15683                    pw.print(" (uid=");
15684                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15685                    pw.println(")");
15686                } else if (mRequiredVerifierPackage != null) {
15687                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15688                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15689                }
15690            }
15691
15692            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15693                    packageName == null) {
15694                if (mIntentFilterVerifierComponent != null) {
15695                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15696                    if (!checkin) {
15697                        if (dumpState.onTitlePrinted())
15698                            pw.println();
15699                        pw.println("Intent Filter Verifier:");
15700                        pw.print("  Using: ");
15701                        pw.print(verifierPackageName);
15702                        pw.print(" (uid=");
15703                        pw.print(getPackageUid(verifierPackageName, 0));
15704                        pw.println(")");
15705                    } else if (verifierPackageName != null) {
15706                        pw.print("ifv,"); pw.print(verifierPackageName);
15707                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15708                    }
15709                } else {
15710                    pw.println();
15711                    pw.println("No Intent Filter Verifier available!");
15712                }
15713            }
15714
15715            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15716                boolean printedHeader = false;
15717                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15718                while (it.hasNext()) {
15719                    String name = it.next();
15720                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15721                    if (!checkin) {
15722                        if (!printedHeader) {
15723                            if (dumpState.onTitlePrinted())
15724                                pw.println();
15725                            pw.println("Libraries:");
15726                            printedHeader = true;
15727                        }
15728                        pw.print("  ");
15729                    } else {
15730                        pw.print("lib,");
15731                    }
15732                    pw.print(name);
15733                    if (!checkin) {
15734                        pw.print(" -> ");
15735                    }
15736                    if (ent.path != null) {
15737                        if (!checkin) {
15738                            pw.print("(jar) ");
15739                            pw.print(ent.path);
15740                        } else {
15741                            pw.print(",jar,");
15742                            pw.print(ent.path);
15743                        }
15744                    } else {
15745                        if (!checkin) {
15746                            pw.print("(apk) ");
15747                            pw.print(ent.apk);
15748                        } else {
15749                            pw.print(",apk,");
15750                            pw.print(ent.apk);
15751                        }
15752                    }
15753                    pw.println();
15754                }
15755            }
15756
15757            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15758                if (dumpState.onTitlePrinted())
15759                    pw.println();
15760                if (!checkin) {
15761                    pw.println("Features:");
15762                }
15763                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15764                while (it.hasNext()) {
15765                    String name = it.next();
15766                    if (!checkin) {
15767                        pw.print("  ");
15768                    } else {
15769                        pw.print("feat,");
15770                    }
15771                    pw.println(name);
15772                }
15773            }
15774
15775            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15776                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15777                        : "Activity Resolver Table:", "  ", packageName,
15778                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15779                    dumpState.setTitlePrinted(true);
15780                }
15781            }
15782            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15783                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15784                        : "Receiver Resolver Table:", "  ", packageName,
15785                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15786                    dumpState.setTitlePrinted(true);
15787                }
15788            }
15789            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15790                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15791                        : "Service Resolver Table:", "  ", packageName,
15792                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15793                    dumpState.setTitlePrinted(true);
15794                }
15795            }
15796            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15797                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15798                        : "Provider Resolver Table:", "  ", packageName,
15799                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15800                    dumpState.setTitlePrinted(true);
15801                }
15802            }
15803
15804            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15805                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15806                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15807                    int user = mSettings.mPreferredActivities.keyAt(i);
15808                    if (pir.dump(pw,
15809                            dumpState.getTitlePrinted()
15810                                ? "\nPreferred Activities User " + user + ":"
15811                                : "Preferred Activities User " + user + ":", "  ",
15812                            packageName, true, false)) {
15813                        dumpState.setTitlePrinted(true);
15814                    }
15815                }
15816            }
15817
15818            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15819                pw.flush();
15820                FileOutputStream fout = new FileOutputStream(fd);
15821                BufferedOutputStream str = new BufferedOutputStream(fout);
15822                XmlSerializer serializer = new FastXmlSerializer();
15823                try {
15824                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15825                    serializer.startDocument(null, true);
15826                    serializer.setFeature(
15827                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15828                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15829                    serializer.endDocument();
15830                    serializer.flush();
15831                } catch (IllegalArgumentException e) {
15832                    pw.println("Failed writing: " + e);
15833                } catch (IllegalStateException e) {
15834                    pw.println("Failed writing: " + e);
15835                } catch (IOException e) {
15836                    pw.println("Failed writing: " + e);
15837                }
15838            }
15839
15840            if (!checkin
15841                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15842                    && packageName == null) {
15843                pw.println();
15844                int count = mSettings.mPackages.size();
15845                if (count == 0) {
15846                    pw.println("No applications!");
15847                    pw.println();
15848                } else {
15849                    final String prefix = "  ";
15850                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15851                    if (allPackageSettings.size() == 0) {
15852                        pw.println("No domain preferred apps!");
15853                        pw.println();
15854                    } else {
15855                        pw.println("App verification status:");
15856                        pw.println();
15857                        count = 0;
15858                        for (PackageSetting ps : allPackageSettings) {
15859                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15860                            if (ivi == null || ivi.getPackageName() == null) continue;
15861                            pw.println(prefix + "Package: " + ivi.getPackageName());
15862                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15863                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15864                            pw.println();
15865                            count++;
15866                        }
15867                        if (count == 0) {
15868                            pw.println(prefix + "No app verification established.");
15869                            pw.println();
15870                        }
15871                        for (int userId : sUserManager.getUserIds()) {
15872                            pw.println("App linkages for user " + userId + ":");
15873                            pw.println();
15874                            count = 0;
15875                            for (PackageSetting ps : allPackageSettings) {
15876                                final long status = ps.getDomainVerificationStatusForUser(userId);
15877                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15878                                    continue;
15879                                }
15880                                pw.println(prefix + "Package: " + ps.name);
15881                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15882                                String statusStr = IntentFilterVerificationInfo.
15883                                        getStatusStringFromValue(status);
15884                                pw.println(prefix + "Status:  " + statusStr);
15885                                pw.println();
15886                                count++;
15887                            }
15888                            if (count == 0) {
15889                                pw.println(prefix + "No configured app linkages.");
15890                                pw.println();
15891                            }
15892                        }
15893                    }
15894                }
15895            }
15896
15897            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15898                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15899                if (packageName == null && permissionNames == null) {
15900                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15901                        if (iperm == 0) {
15902                            if (dumpState.onTitlePrinted())
15903                                pw.println();
15904                            pw.println("AppOp Permissions:");
15905                        }
15906                        pw.print("  AppOp Permission ");
15907                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15908                        pw.println(":");
15909                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15910                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15911                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15912                        }
15913                    }
15914                }
15915            }
15916
15917            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15918                boolean printedSomething = false;
15919                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15920                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15921                        continue;
15922                    }
15923                    if (!printedSomething) {
15924                        if (dumpState.onTitlePrinted())
15925                            pw.println();
15926                        pw.println("Registered ContentProviders:");
15927                        printedSomething = true;
15928                    }
15929                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15930                    pw.print("    "); pw.println(p.toString());
15931                }
15932                printedSomething = false;
15933                for (Map.Entry<String, PackageParser.Provider> entry :
15934                        mProvidersByAuthority.entrySet()) {
15935                    PackageParser.Provider p = entry.getValue();
15936                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15937                        continue;
15938                    }
15939                    if (!printedSomething) {
15940                        if (dumpState.onTitlePrinted())
15941                            pw.println();
15942                        pw.println("ContentProvider Authorities:");
15943                        printedSomething = true;
15944                    }
15945                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15946                    pw.print("    "); pw.println(p.toString());
15947                    if (p.info != null && p.info.applicationInfo != null) {
15948                        final String appInfo = p.info.applicationInfo.toString();
15949                        pw.print("      applicationInfo="); pw.println(appInfo);
15950                    }
15951                }
15952            }
15953
15954            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15955                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15956            }
15957
15958            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15959                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15960            }
15961
15962            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15963                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15964            }
15965
15966            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15967                // XXX should handle packageName != null by dumping only install data that
15968                // the given package is involved with.
15969                if (dumpState.onTitlePrinted()) pw.println();
15970                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15971            }
15972
15973            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15974                if (dumpState.onTitlePrinted()) pw.println();
15975                mSettings.dumpReadMessagesLPr(pw, dumpState);
15976
15977                pw.println();
15978                pw.println("Package warning messages:");
15979                BufferedReader in = null;
15980                String line = null;
15981                try {
15982                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15983                    while ((line = in.readLine()) != null) {
15984                        if (line.contains("ignored: updated version")) continue;
15985                        pw.println(line);
15986                    }
15987                } catch (IOException ignored) {
15988                } finally {
15989                    IoUtils.closeQuietly(in);
15990                }
15991            }
15992
15993            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15994                BufferedReader in = null;
15995                String line = null;
15996                try {
15997                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15998                    while ((line = in.readLine()) != null) {
15999                        if (line.contains("ignored: updated version")) continue;
16000                        pw.print("msg,");
16001                        pw.println(line);
16002                    }
16003                } catch (IOException ignored) {
16004                } finally {
16005                    IoUtils.closeQuietly(in);
16006                }
16007            }
16008        }
16009    }
16010
16011    private String dumpDomainString(String packageName) {
16012        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16013        List<IntentFilter> filters = getAllIntentFilters(packageName);
16014
16015        ArraySet<String> result = new ArraySet<>();
16016        if (iviList.size() > 0) {
16017            for (IntentFilterVerificationInfo ivi : iviList) {
16018                for (String host : ivi.getDomains()) {
16019                    result.add(host);
16020                }
16021            }
16022        }
16023        if (filters != null && filters.size() > 0) {
16024            for (IntentFilter filter : filters) {
16025                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16026                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16027                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16028                    result.addAll(filter.getHostsList());
16029                }
16030            }
16031        }
16032
16033        StringBuilder sb = new StringBuilder(result.size() * 16);
16034        for (String domain : result) {
16035            if (sb.length() > 0) sb.append(" ");
16036            sb.append(domain);
16037        }
16038        return sb.toString();
16039    }
16040
16041    // ------- apps on sdcard specific code -------
16042    static final boolean DEBUG_SD_INSTALL = false;
16043
16044    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16045
16046    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16047
16048    private boolean mMediaMounted = false;
16049
16050    static String getEncryptKey() {
16051        try {
16052            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16053                    SD_ENCRYPTION_KEYSTORE_NAME);
16054            if (sdEncKey == null) {
16055                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16056                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16057                if (sdEncKey == null) {
16058                    Slog.e(TAG, "Failed to create encryption keys");
16059                    return null;
16060                }
16061            }
16062            return sdEncKey;
16063        } catch (NoSuchAlgorithmException nsae) {
16064            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16065            return null;
16066        } catch (IOException ioe) {
16067            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16068            return null;
16069        }
16070    }
16071
16072    /*
16073     * Update media status on PackageManager.
16074     */
16075    @Override
16076    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16077        int callingUid = Binder.getCallingUid();
16078        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16079            throw new SecurityException("Media status can only be updated by the system");
16080        }
16081        // reader; this apparently protects mMediaMounted, but should probably
16082        // be a different lock in that case.
16083        synchronized (mPackages) {
16084            Log.i(TAG, "Updating external media status from "
16085                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16086                    + (mediaStatus ? "mounted" : "unmounted"));
16087            if (DEBUG_SD_INSTALL)
16088                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16089                        + ", mMediaMounted=" + mMediaMounted);
16090            if (mediaStatus == mMediaMounted) {
16091                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16092                        : 0, -1);
16093                mHandler.sendMessage(msg);
16094                return;
16095            }
16096            mMediaMounted = mediaStatus;
16097        }
16098        // Queue up an async operation since the package installation may take a
16099        // little while.
16100        mHandler.post(new Runnable() {
16101            public void run() {
16102                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16103            }
16104        });
16105    }
16106
16107    /**
16108     * Called by MountService when the initial ASECs to scan are available.
16109     * Should block until all the ASEC containers are finished being scanned.
16110     */
16111    public void scanAvailableAsecs() {
16112        updateExternalMediaStatusInner(true, false, false);
16113        if (mShouldRestoreconData) {
16114            SELinuxMMAC.setRestoreconDone();
16115            mShouldRestoreconData = false;
16116        }
16117    }
16118
16119    /*
16120     * Collect information of applications on external media, map them against
16121     * existing containers and update information based on current mount status.
16122     * Please note that we always have to report status if reportStatus has been
16123     * set to true especially when unloading packages.
16124     */
16125    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16126            boolean externalStorage) {
16127        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16128        int[] uidArr = EmptyArray.INT;
16129
16130        final String[] list = PackageHelper.getSecureContainerList();
16131        if (ArrayUtils.isEmpty(list)) {
16132            Log.i(TAG, "No secure containers found");
16133        } else {
16134            // Process list of secure containers and categorize them
16135            // as active or stale based on their package internal state.
16136
16137            // reader
16138            synchronized (mPackages) {
16139                for (String cid : list) {
16140                    // Leave stages untouched for now; installer service owns them
16141                    if (PackageInstallerService.isStageName(cid)) continue;
16142
16143                    if (DEBUG_SD_INSTALL)
16144                        Log.i(TAG, "Processing container " + cid);
16145                    String pkgName = getAsecPackageName(cid);
16146                    if (pkgName == null) {
16147                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16148                        continue;
16149                    }
16150                    if (DEBUG_SD_INSTALL)
16151                        Log.i(TAG, "Looking for pkg : " + pkgName);
16152
16153                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16154                    if (ps == null) {
16155                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16156                        continue;
16157                    }
16158
16159                    /*
16160                     * Skip packages that are not external if we're unmounting
16161                     * external storage.
16162                     */
16163                    if (externalStorage && !isMounted && !isExternal(ps)) {
16164                        continue;
16165                    }
16166
16167                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16168                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16169                    // The package status is changed only if the code path
16170                    // matches between settings and the container id.
16171                    if (ps.codePathString != null
16172                            && ps.codePathString.startsWith(args.getCodePath())) {
16173                        if (DEBUG_SD_INSTALL) {
16174                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16175                                    + " at code path: " + ps.codePathString);
16176                        }
16177
16178                        // We do have a valid package installed on sdcard
16179                        processCids.put(args, ps.codePathString);
16180                        final int uid = ps.appId;
16181                        if (uid != -1) {
16182                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16183                        }
16184                    } else {
16185                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16186                                + ps.codePathString);
16187                    }
16188                }
16189            }
16190
16191            Arrays.sort(uidArr);
16192        }
16193
16194        // Process packages with valid entries.
16195        if (isMounted) {
16196            if (DEBUG_SD_INSTALL)
16197                Log.i(TAG, "Loading packages");
16198            loadMediaPackages(processCids, uidArr, externalStorage);
16199            startCleaningPackages();
16200            mInstallerService.onSecureContainersAvailable();
16201        } else {
16202            if (DEBUG_SD_INSTALL)
16203                Log.i(TAG, "Unloading packages");
16204            unloadMediaPackages(processCids, uidArr, reportStatus);
16205        }
16206    }
16207
16208    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16209            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16210        final int size = infos.size();
16211        final String[] packageNames = new String[size];
16212        final int[] packageUids = new int[size];
16213        for (int i = 0; i < size; i++) {
16214            final ApplicationInfo info = infos.get(i);
16215            packageNames[i] = info.packageName;
16216            packageUids[i] = info.uid;
16217        }
16218        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16219                finishedReceiver);
16220    }
16221
16222    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16223            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16224        sendResourcesChangedBroadcast(mediaStatus, replacing,
16225                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16226    }
16227
16228    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16229            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16230        int size = pkgList.length;
16231        if (size > 0) {
16232            // Send broadcasts here
16233            Bundle extras = new Bundle();
16234            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16235            if (uidArr != null) {
16236                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16237            }
16238            if (replacing) {
16239                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16240            }
16241            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16242                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16243            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16244        }
16245    }
16246
16247   /*
16248     * Look at potentially valid container ids from processCids If package
16249     * information doesn't match the one on record or package scanning fails,
16250     * the cid is added to list of removeCids. We currently don't delete stale
16251     * containers.
16252     */
16253    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16254            boolean externalStorage) {
16255        ArrayList<String> pkgList = new ArrayList<String>();
16256        Set<AsecInstallArgs> keys = processCids.keySet();
16257
16258        for (AsecInstallArgs args : keys) {
16259            String codePath = processCids.get(args);
16260            if (DEBUG_SD_INSTALL)
16261                Log.i(TAG, "Loading container : " + args.cid);
16262            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16263            try {
16264                // Make sure there are no container errors first.
16265                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16266                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16267                            + " when installing from sdcard");
16268                    continue;
16269                }
16270                // Check code path here.
16271                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16272                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16273                            + " does not match one in settings " + codePath);
16274                    continue;
16275                }
16276                // Parse package
16277                int parseFlags = mDefParseFlags;
16278                if (args.isExternalAsec()) {
16279                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16280                }
16281                if (args.isFwdLocked()) {
16282                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16283                }
16284
16285                synchronized (mInstallLock) {
16286                    PackageParser.Package pkg = null;
16287                    try {
16288                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16289                    } catch (PackageManagerException e) {
16290                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16291                    }
16292                    // Scan the package
16293                    if (pkg != null) {
16294                        /*
16295                         * TODO why is the lock being held? doPostInstall is
16296                         * called in other places without the lock. This needs
16297                         * to be straightened out.
16298                         */
16299                        // writer
16300                        synchronized (mPackages) {
16301                            retCode = PackageManager.INSTALL_SUCCEEDED;
16302                            pkgList.add(pkg.packageName);
16303                            // Post process args
16304                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16305                                    pkg.applicationInfo.uid);
16306                        }
16307                    } else {
16308                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16309                    }
16310                }
16311
16312            } finally {
16313                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16314                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16315                }
16316            }
16317        }
16318        // writer
16319        synchronized (mPackages) {
16320            // If the platform SDK has changed since the last time we booted,
16321            // we need to re-grant app permission to catch any new ones that
16322            // appear. This is really a hack, and means that apps can in some
16323            // cases get permissions that the user didn't initially explicitly
16324            // allow... it would be nice to have some better way to handle
16325            // this situation.
16326            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16327                    : mSettings.getInternalVersion();
16328            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16329                    : StorageManager.UUID_PRIVATE_INTERNAL;
16330
16331            int updateFlags = UPDATE_PERMISSIONS_ALL;
16332            if (ver.sdkVersion != mSdkVersion) {
16333                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16334                        + mSdkVersion + "; regranting permissions for external");
16335                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16336            }
16337            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16338
16339            // Yay, everything is now upgraded
16340            ver.forceCurrent();
16341
16342            // can downgrade to reader
16343            // Persist settings
16344            mSettings.writeLPr();
16345        }
16346        // Send a broadcast to let everyone know we are done processing
16347        if (pkgList.size() > 0) {
16348            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16349        }
16350    }
16351
16352   /*
16353     * Utility method to unload a list of specified containers
16354     */
16355    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16356        // Just unmount all valid containers.
16357        for (AsecInstallArgs arg : cidArgs) {
16358            synchronized (mInstallLock) {
16359                arg.doPostDeleteLI(false);
16360           }
16361       }
16362   }
16363
16364    /*
16365     * Unload packages mounted on external media. This involves deleting package
16366     * data from internal structures, sending broadcasts about diabled packages,
16367     * gc'ing to free up references, unmounting all secure containers
16368     * corresponding to packages on external media, and posting a
16369     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16370     * that we always have to post this message if status has been requested no
16371     * matter what.
16372     */
16373    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16374            final boolean reportStatus) {
16375        if (DEBUG_SD_INSTALL)
16376            Log.i(TAG, "unloading media packages");
16377        ArrayList<String> pkgList = new ArrayList<String>();
16378        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16379        final Set<AsecInstallArgs> keys = processCids.keySet();
16380        for (AsecInstallArgs args : keys) {
16381            String pkgName = args.getPackageName();
16382            if (DEBUG_SD_INSTALL)
16383                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16384            // Delete package internally
16385            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16386            synchronized (mInstallLock) {
16387                boolean res = deletePackageLI(pkgName, null, false, null, null,
16388                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16389                if (res) {
16390                    pkgList.add(pkgName);
16391                } else {
16392                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16393                    failedList.add(args);
16394                }
16395            }
16396        }
16397
16398        // reader
16399        synchronized (mPackages) {
16400            // We didn't update the settings after removing each package;
16401            // write them now for all packages.
16402            mSettings.writeLPr();
16403        }
16404
16405        // We have to absolutely send UPDATED_MEDIA_STATUS only
16406        // after confirming that all the receivers processed the ordered
16407        // broadcast when packages get disabled, force a gc to clean things up.
16408        // and unload all the containers.
16409        if (pkgList.size() > 0) {
16410            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16411                    new IIntentReceiver.Stub() {
16412                public void performReceive(Intent intent, int resultCode, String data,
16413                        Bundle extras, boolean ordered, boolean sticky,
16414                        int sendingUser) throws RemoteException {
16415                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16416                            reportStatus ? 1 : 0, 1, keys);
16417                    mHandler.sendMessage(msg);
16418                }
16419            });
16420        } else {
16421            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16422                    keys);
16423            mHandler.sendMessage(msg);
16424        }
16425    }
16426
16427    private void loadPrivatePackages(final VolumeInfo vol) {
16428        mHandler.post(new Runnable() {
16429            @Override
16430            public void run() {
16431                loadPrivatePackagesInner(vol);
16432            }
16433        });
16434    }
16435
16436    private void loadPrivatePackagesInner(VolumeInfo vol) {
16437        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16438        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16439
16440        final VersionInfo ver;
16441        final List<PackageSetting> packages;
16442        synchronized (mPackages) {
16443            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16444            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16445        }
16446
16447        for (PackageSetting ps : packages) {
16448            synchronized (mInstallLock) {
16449                final PackageParser.Package pkg;
16450                try {
16451                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16452                    loaded.add(pkg.applicationInfo);
16453                } catch (PackageManagerException e) {
16454                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16455                }
16456
16457                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16458                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16459                }
16460            }
16461        }
16462
16463        synchronized (mPackages) {
16464            int updateFlags = UPDATE_PERMISSIONS_ALL;
16465            if (ver.sdkVersion != mSdkVersion) {
16466                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16467                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16468                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16469            }
16470            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16471
16472            // Yay, everything is now upgraded
16473            ver.forceCurrent();
16474
16475            mSettings.writeLPr();
16476        }
16477
16478        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16479        sendResourcesChangedBroadcast(true, false, loaded, null);
16480    }
16481
16482    private void unloadPrivatePackages(final VolumeInfo vol) {
16483        mHandler.post(new Runnable() {
16484            @Override
16485            public void run() {
16486                unloadPrivatePackagesInner(vol);
16487            }
16488        });
16489    }
16490
16491    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16492        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16493        synchronized (mInstallLock) {
16494        synchronized (mPackages) {
16495            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16496            for (PackageSetting ps : packages) {
16497                if (ps.pkg == null) continue;
16498
16499                final ApplicationInfo info = ps.pkg.applicationInfo;
16500                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16501                if (deletePackageLI(ps.name, null, false, null, null,
16502                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16503                    unloaded.add(info);
16504                } else {
16505                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16506                }
16507            }
16508
16509            mSettings.writeLPr();
16510        }
16511        }
16512
16513        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16514        sendResourcesChangedBroadcast(false, false, unloaded, null);
16515    }
16516
16517    /**
16518     * Examine all users present on given mounted volume, and destroy data
16519     * belonging to users that are no longer valid, or whose user ID has been
16520     * recycled.
16521     */
16522    private void reconcileUsers(String volumeUuid) {
16523        final File[] files = FileUtils
16524                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16525        for (File file : files) {
16526            if (!file.isDirectory()) continue;
16527
16528            final int userId;
16529            final UserInfo info;
16530            try {
16531                userId = Integer.parseInt(file.getName());
16532                info = sUserManager.getUserInfo(userId);
16533            } catch (NumberFormatException e) {
16534                Slog.w(TAG, "Invalid user directory " + file);
16535                continue;
16536            }
16537
16538            boolean destroyUser = false;
16539            if (info == null) {
16540                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16541                        + " because no matching user was found");
16542                destroyUser = true;
16543            } else {
16544                try {
16545                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16546                } catch (IOException e) {
16547                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16548                            + " because we failed to enforce serial number: " + e);
16549                    destroyUser = true;
16550                }
16551            }
16552
16553            if (destroyUser) {
16554                synchronized (mInstallLock) {
16555                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16556                }
16557            }
16558        }
16559
16560        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16561        final UserManager um = mContext.getSystemService(UserManager.class);
16562        for (UserInfo user : um.getUsers()) {
16563            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16564            if (userDir.exists()) continue;
16565
16566            try {
16567                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16568                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16569            } catch (IOException e) {
16570                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16571            }
16572        }
16573    }
16574
16575    /**
16576     * Examine all apps present on given mounted volume, and destroy apps that
16577     * aren't expected, either due to uninstallation or reinstallation on
16578     * another volume.
16579     */
16580    private void reconcileApps(String volumeUuid) {
16581        final File[] files = FileUtils
16582                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16583        for (File file : files) {
16584            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16585                    && !PackageInstallerService.isStageName(file.getName());
16586            if (!isPackage) {
16587                // Ignore entries which are not packages
16588                continue;
16589            }
16590
16591            boolean destroyApp = false;
16592            String packageName = null;
16593            try {
16594                final PackageLite pkg = PackageParser.parsePackageLite(file,
16595                        PackageParser.PARSE_MUST_BE_APK);
16596                packageName = pkg.packageName;
16597
16598                synchronized (mPackages) {
16599                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16600                    if (ps == null) {
16601                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16602                                + volumeUuid + " because we found no install record");
16603                        destroyApp = true;
16604                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16605                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16606                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16607                        destroyApp = true;
16608                    }
16609                }
16610
16611            } catch (PackageParserException e) {
16612                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16613                destroyApp = true;
16614            }
16615
16616            if (destroyApp) {
16617                synchronized (mInstallLock) {
16618                    if (packageName != null) {
16619                        removeDataDirsLI(volumeUuid, packageName);
16620                    }
16621                    if (file.isDirectory()) {
16622                        mInstaller.rmPackageDir(file.getAbsolutePath());
16623                    } else {
16624                        file.delete();
16625                    }
16626                }
16627            }
16628        }
16629    }
16630
16631    private void unfreezePackage(String packageName) {
16632        synchronized (mPackages) {
16633            final PackageSetting ps = mSettings.mPackages.get(packageName);
16634            if (ps != null) {
16635                ps.frozen = false;
16636            }
16637        }
16638    }
16639
16640    @Override
16641    public int movePackage(final String packageName, final String volumeUuid) {
16642        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16643
16644        final int moveId = mNextMoveId.getAndIncrement();
16645        mHandler.post(new Runnable() {
16646            @Override
16647            public void run() {
16648                try {
16649                    movePackageInternal(packageName, volumeUuid, moveId);
16650                } catch (PackageManagerException e) {
16651                    Slog.w(TAG, "Failed to move " + packageName, e);
16652                    mMoveCallbacks.notifyStatusChanged(moveId,
16653                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16654                }
16655            }
16656        });
16657        return moveId;
16658    }
16659
16660    private void movePackageInternal(final String packageName, final String volumeUuid,
16661            final int moveId) throws PackageManagerException {
16662        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16663        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16664        final PackageManager pm = mContext.getPackageManager();
16665
16666        final boolean currentAsec;
16667        final String currentVolumeUuid;
16668        final File codeFile;
16669        final String installerPackageName;
16670        final String packageAbiOverride;
16671        final int appId;
16672        final String seinfo;
16673        final String label;
16674
16675        // reader
16676        synchronized (mPackages) {
16677            final PackageParser.Package pkg = mPackages.get(packageName);
16678            final PackageSetting ps = mSettings.mPackages.get(packageName);
16679            if (pkg == null || ps == null) {
16680                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16681            }
16682
16683            if (pkg.applicationInfo.isSystemApp()) {
16684                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16685                        "Cannot move system application");
16686            }
16687
16688            if (pkg.applicationInfo.isExternalAsec()) {
16689                currentAsec = true;
16690                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16691            } else if (pkg.applicationInfo.isForwardLocked()) {
16692                currentAsec = true;
16693                currentVolumeUuid = "forward_locked";
16694            } else {
16695                currentAsec = false;
16696                currentVolumeUuid = ps.volumeUuid;
16697
16698                final File probe = new File(pkg.codePath);
16699                final File probeOat = new File(probe, "oat");
16700                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16701                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16702                            "Move only supported for modern cluster style installs");
16703                }
16704            }
16705
16706            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16707                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16708                        "Package already moved to " + volumeUuid);
16709            }
16710
16711            if (ps.frozen) {
16712                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16713                        "Failed to move already frozen package");
16714            }
16715            ps.frozen = true;
16716
16717            codeFile = new File(pkg.codePath);
16718            installerPackageName = ps.installerPackageName;
16719            packageAbiOverride = ps.cpuAbiOverrideString;
16720            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16721            seinfo = pkg.applicationInfo.seinfo;
16722            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16723        }
16724
16725        // Now that we're guarded by frozen state, kill app during move
16726        final long token = Binder.clearCallingIdentity();
16727        try {
16728            killApplication(packageName, appId, "move pkg");
16729        } finally {
16730            Binder.restoreCallingIdentity(token);
16731        }
16732
16733        final Bundle extras = new Bundle();
16734        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16735        extras.putString(Intent.EXTRA_TITLE, label);
16736        mMoveCallbacks.notifyCreated(moveId, extras);
16737
16738        int installFlags;
16739        final boolean moveCompleteApp;
16740        final File measurePath;
16741
16742        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16743            installFlags = INSTALL_INTERNAL;
16744            moveCompleteApp = !currentAsec;
16745            measurePath = Environment.getDataAppDirectory(volumeUuid);
16746        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16747            installFlags = INSTALL_EXTERNAL;
16748            moveCompleteApp = false;
16749            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16750        } else {
16751            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16752            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16753                    || !volume.isMountedWritable()) {
16754                unfreezePackage(packageName);
16755                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16756                        "Move location not mounted private volume");
16757            }
16758
16759            Preconditions.checkState(!currentAsec);
16760
16761            installFlags = INSTALL_INTERNAL;
16762            moveCompleteApp = true;
16763            measurePath = Environment.getDataAppDirectory(volumeUuid);
16764        }
16765
16766        final PackageStats stats = new PackageStats(null, -1);
16767        synchronized (mInstaller) {
16768            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16769                unfreezePackage(packageName);
16770                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16771                        "Failed to measure package size");
16772            }
16773        }
16774
16775        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16776                + stats.dataSize);
16777
16778        final long startFreeBytes = measurePath.getFreeSpace();
16779        final long sizeBytes;
16780        if (moveCompleteApp) {
16781            sizeBytes = stats.codeSize + stats.dataSize;
16782        } else {
16783            sizeBytes = stats.codeSize;
16784        }
16785
16786        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16787            unfreezePackage(packageName);
16788            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16789                    "Not enough free space to move");
16790        }
16791
16792        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16793
16794        final CountDownLatch installedLatch = new CountDownLatch(1);
16795        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16796            @Override
16797            public void onUserActionRequired(Intent intent) throws RemoteException {
16798                throw new IllegalStateException();
16799            }
16800
16801            @Override
16802            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16803                    Bundle extras) throws RemoteException {
16804                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16805                        + PackageManager.installStatusToString(returnCode, msg));
16806
16807                installedLatch.countDown();
16808
16809                // Regardless of success or failure of the move operation,
16810                // always unfreeze the package
16811                unfreezePackage(packageName);
16812
16813                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16814                switch (status) {
16815                    case PackageInstaller.STATUS_SUCCESS:
16816                        mMoveCallbacks.notifyStatusChanged(moveId,
16817                                PackageManager.MOVE_SUCCEEDED);
16818                        break;
16819                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16820                        mMoveCallbacks.notifyStatusChanged(moveId,
16821                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16822                        break;
16823                    default:
16824                        mMoveCallbacks.notifyStatusChanged(moveId,
16825                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16826                        break;
16827                }
16828            }
16829        };
16830
16831        final MoveInfo move;
16832        if (moveCompleteApp) {
16833            // Kick off a thread to report progress estimates
16834            new Thread() {
16835                @Override
16836                public void run() {
16837                    while (true) {
16838                        try {
16839                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16840                                break;
16841                            }
16842                        } catch (InterruptedException ignored) {
16843                        }
16844
16845                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16846                        final int progress = 10 + (int) MathUtils.constrain(
16847                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16848                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16849                    }
16850                }
16851            }.start();
16852
16853            final String dataAppName = codeFile.getName();
16854            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16855                    dataAppName, appId, seinfo);
16856        } else {
16857            move = null;
16858        }
16859
16860        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16861
16862        final Message msg = mHandler.obtainMessage(INIT_COPY);
16863        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16864        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16865                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16866        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16867        msg.obj = params;
16868
16869        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16870                System.identityHashCode(msg.obj));
16871        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16872                System.identityHashCode(msg.obj));
16873
16874        mHandler.sendMessage(msg);
16875    }
16876
16877    @Override
16878    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16879        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16880
16881        final int realMoveId = mNextMoveId.getAndIncrement();
16882        final Bundle extras = new Bundle();
16883        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16884        mMoveCallbacks.notifyCreated(realMoveId, extras);
16885
16886        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16887            @Override
16888            public void onCreated(int moveId, Bundle extras) {
16889                // Ignored
16890            }
16891
16892            @Override
16893            public void onStatusChanged(int moveId, int status, long estMillis) {
16894                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16895            }
16896        };
16897
16898        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16899        storage.setPrimaryStorageUuid(volumeUuid, callback);
16900        return realMoveId;
16901    }
16902
16903    @Override
16904    public int getMoveStatus(int moveId) {
16905        mContext.enforceCallingOrSelfPermission(
16906                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16907        return mMoveCallbacks.mLastStatus.get(moveId);
16908    }
16909
16910    @Override
16911    public void registerMoveCallback(IPackageMoveObserver callback) {
16912        mContext.enforceCallingOrSelfPermission(
16913                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16914        mMoveCallbacks.register(callback);
16915    }
16916
16917    @Override
16918    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16919        mContext.enforceCallingOrSelfPermission(
16920                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16921        mMoveCallbacks.unregister(callback);
16922    }
16923
16924    @Override
16925    public boolean setInstallLocation(int loc) {
16926        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16927                null);
16928        if (getInstallLocation() == loc) {
16929            return true;
16930        }
16931        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16932                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16933            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16934                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16935            return true;
16936        }
16937        return false;
16938   }
16939
16940    @Override
16941    public int getInstallLocation() {
16942        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16943                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16944                PackageHelper.APP_INSTALL_AUTO);
16945    }
16946
16947    /** Called by UserManagerService */
16948    void cleanUpUser(UserManagerService userManager, int userHandle) {
16949        synchronized (mPackages) {
16950            mDirtyUsers.remove(userHandle);
16951            mUserNeedsBadging.delete(userHandle);
16952            mSettings.removeUserLPw(userHandle);
16953            mPendingBroadcasts.remove(userHandle);
16954            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16955        }
16956        synchronized (mInstallLock) {
16957            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16958            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16959                final String volumeUuid = vol.getFsUuid();
16960                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16961                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16962            }
16963            synchronized (mPackages) {
16964                removeUnusedPackagesLILPw(userManager, userHandle);
16965            }
16966        }
16967    }
16968
16969    /**
16970     * We're removing userHandle and would like to remove any downloaded packages
16971     * that are no longer in use by any other user.
16972     * @param userHandle the user being removed
16973     */
16974    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16975        final boolean DEBUG_CLEAN_APKS = false;
16976        int [] users = userManager.getUserIds();
16977        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16978        while (psit.hasNext()) {
16979            PackageSetting ps = psit.next();
16980            if (ps.pkg == null) {
16981                continue;
16982            }
16983            final String packageName = ps.pkg.packageName;
16984            // Skip over if system app
16985            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16986                continue;
16987            }
16988            if (DEBUG_CLEAN_APKS) {
16989                Slog.i(TAG, "Checking package " + packageName);
16990            }
16991            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
16992            if (keep) {
16993                if (DEBUG_CLEAN_APKS) {
16994                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
16995                }
16996            } else {
16997                for (int i = 0; i < users.length; i++) {
16998                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
16999                        keep = true;
17000                        if (DEBUG_CLEAN_APKS) {
17001                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17002                                    + users[i]);
17003                        }
17004                        break;
17005                    }
17006                }
17007            }
17008            if (!keep) {
17009                if (DEBUG_CLEAN_APKS) {
17010                    Slog.i(TAG, "  Removing package " + packageName);
17011                }
17012                mHandler.post(new Runnable() {
17013                    public void run() {
17014                        deletePackageX(packageName, userHandle, 0);
17015                    } //end run
17016                });
17017            }
17018        }
17019    }
17020
17021    /** Called by UserManagerService */
17022    void createNewUser(int userHandle) {
17023        synchronized (mInstallLock) {
17024            mInstaller.createUserConfig(userHandle);
17025            mSettings.createNewUserLI(this, mInstaller, userHandle);
17026        }
17027        synchronized (mPackages) {
17028            applyFactoryDefaultBrowserLPw(userHandle);
17029            primeDomainVerificationsLPw(userHandle);
17030        }
17031    }
17032
17033    void newUserCreated(final int userHandle) {
17034        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17035        // If permission review for legacy apps is required, we represent
17036        // dagerous permissions for such apps as always granted runtime
17037        // permissions to keep per user flag state whether review is needed.
17038        // Hence, if a new user is added we have to propagate dangerous
17039        // permission grants for these legacy apps.
17040        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17041            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17042                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17043        }
17044    }
17045
17046    @Override
17047    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17048        mContext.enforceCallingOrSelfPermission(
17049                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17050                "Only package verification agents can read the verifier device identity");
17051
17052        synchronized (mPackages) {
17053            return mSettings.getVerifierDeviceIdentityLPw();
17054        }
17055    }
17056
17057    @Override
17058    public void setPermissionEnforced(String permission, boolean enforced) {
17059        // TODO: Now that we no longer change GID for storage, this should to away.
17060        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17061                "setPermissionEnforced");
17062        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17063            synchronized (mPackages) {
17064                if (mSettings.mReadExternalStorageEnforced == null
17065                        || mSettings.mReadExternalStorageEnforced != enforced) {
17066                    mSettings.mReadExternalStorageEnforced = enforced;
17067                    mSettings.writeLPr();
17068                }
17069            }
17070            // kill any non-foreground processes so we restart them and
17071            // grant/revoke the GID.
17072            final IActivityManager am = ActivityManagerNative.getDefault();
17073            if (am != null) {
17074                final long token = Binder.clearCallingIdentity();
17075                try {
17076                    am.killProcessesBelowForeground("setPermissionEnforcement");
17077                } catch (RemoteException e) {
17078                } finally {
17079                    Binder.restoreCallingIdentity(token);
17080                }
17081            }
17082        } else {
17083            throw new IllegalArgumentException("No selective enforcement for " + permission);
17084        }
17085    }
17086
17087    @Override
17088    @Deprecated
17089    public boolean isPermissionEnforced(String permission) {
17090        return true;
17091    }
17092
17093    @Override
17094    public boolean isStorageLow() {
17095        final long token = Binder.clearCallingIdentity();
17096        try {
17097            final DeviceStorageMonitorInternal
17098                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17099            if (dsm != null) {
17100                return dsm.isMemoryLow();
17101            } else {
17102                return false;
17103            }
17104        } finally {
17105            Binder.restoreCallingIdentity(token);
17106        }
17107    }
17108
17109    @Override
17110    public IPackageInstaller getPackageInstaller() {
17111        return mInstallerService;
17112    }
17113
17114    private boolean userNeedsBadging(int userId) {
17115        int index = mUserNeedsBadging.indexOfKey(userId);
17116        if (index < 0) {
17117            final UserInfo userInfo;
17118            final long token = Binder.clearCallingIdentity();
17119            try {
17120                userInfo = sUserManager.getUserInfo(userId);
17121            } finally {
17122                Binder.restoreCallingIdentity(token);
17123            }
17124            final boolean b;
17125            if (userInfo != null && userInfo.isManagedProfile()) {
17126                b = true;
17127            } else {
17128                b = false;
17129            }
17130            mUserNeedsBadging.put(userId, b);
17131            return b;
17132        }
17133        return mUserNeedsBadging.valueAt(index);
17134    }
17135
17136    @Override
17137    public KeySet getKeySetByAlias(String packageName, String alias) {
17138        if (packageName == null || alias == null) {
17139            return null;
17140        }
17141        synchronized(mPackages) {
17142            final PackageParser.Package pkg = mPackages.get(packageName);
17143            if (pkg == null) {
17144                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17145                throw new IllegalArgumentException("Unknown package: " + packageName);
17146            }
17147            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17148            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17149        }
17150    }
17151
17152    @Override
17153    public KeySet getSigningKeySet(String packageName) {
17154        if (packageName == null) {
17155            return null;
17156        }
17157        synchronized(mPackages) {
17158            final PackageParser.Package pkg = mPackages.get(packageName);
17159            if (pkg == null) {
17160                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17161                throw new IllegalArgumentException("Unknown package: " + packageName);
17162            }
17163            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17164                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17165                throw new SecurityException("May not access signing KeySet of other apps.");
17166            }
17167            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17168            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17169        }
17170    }
17171
17172    @Override
17173    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17174        if (packageName == null || ks == null) {
17175            return false;
17176        }
17177        synchronized(mPackages) {
17178            final PackageParser.Package pkg = mPackages.get(packageName);
17179            if (pkg == null) {
17180                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17181                throw new IllegalArgumentException("Unknown package: " + packageName);
17182            }
17183            IBinder ksh = ks.getToken();
17184            if (ksh instanceof KeySetHandle) {
17185                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17186                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17187            }
17188            return false;
17189        }
17190    }
17191
17192    @Override
17193    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17194        if (packageName == null || ks == null) {
17195            return false;
17196        }
17197        synchronized(mPackages) {
17198            final PackageParser.Package pkg = mPackages.get(packageName);
17199            if (pkg == null) {
17200                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17201                throw new IllegalArgumentException("Unknown package: " + packageName);
17202            }
17203            IBinder ksh = ks.getToken();
17204            if (ksh instanceof KeySetHandle) {
17205                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17206                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17207            }
17208            return false;
17209        }
17210    }
17211
17212    private void deletePackageIfUnusedLPr(final String packageName) {
17213        PackageSetting ps = mSettings.mPackages.get(packageName);
17214        if (ps == null) {
17215            return;
17216        }
17217        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17218            // TODO Implement atomic delete if package is unused
17219            // It is currently possible that the package will be deleted even if it is installed
17220            // after this method returns.
17221            mHandler.post(new Runnable() {
17222                public void run() {
17223                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17224                }
17225            });
17226        }
17227    }
17228
17229    /**
17230     * Check and throw if the given before/after packages would be considered a
17231     * downgrade.
17232     */
17233    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17234            throws PackageManagerException {
17235        if (after.versionCode < before.mVersionCode) {
17236            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17237                    "Update version code " + after.versionCode + " is older than current "
17238                    + before.mVersionCode);
17239        } else if (after.versionCode == before.mVersionCode) {
17240            if (after.baseRevisionCode < before.baseRevisionCode) {
17241                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17242                        "Update base revision code " + after.baseRevisionCode
17243                        + " is older than current " + before.baseRevisionCode);
17244            }
17245
17246            if (!ArrayUtils.isEmpty(after.splitNames)) {
17247                for (int i = 0; i < after.splitNames.length; i++) {
17248                    final String splitName = after.splitNames[i];
17249                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17250                    if (j != -1) {
17251                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17252                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17253                                    "Update split " + splitName + " revision code "
17254                                    + after.splitRevisionCodes[i] + " is older than current "
17255                                    + before.splitRevisionCodes[j]);
17256                        }
17257                    }
17258                }
17259            }
17260        }
17261    }
17262
17263    private static class MoveCallbacks extends Handler {
17264        private static final int MSG_CREATED = 1;
17265        private static final int MSG_STATUS_CHANGED = 2;
17266
17267        private final RemoteCallbackList<IPackageMoveObserver>
17268                mCallbacks = new RemoteCallbackList<>();
17269
17270        private final SparseIntArray mLastStatus = new SparseIntArray();
17271
17272        public MoveCallbacks(Looper looper) {
17273            super(looper);
17274        }
17275
17276        public void register(IPackageMoveObserver callback) {
17277            mCallbacks.register(callback);
17278        }
17279
17280        public void unregister(IPackageMoveObserver callback) {
17281            mCallbacks.unregister(callback);
17282        }
17283
17284        @Override
17285        public void handleMessage(Message msg) {
17286            final SomeArgs args = (SomeArgs) msg.obj;
17287            final int n = mCallbacks.beginBroadcast();
17288            for (int i = 0; i < n; i++) {
17289                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17290                try {
17291                    invokeCallback(callback, msg.what, args);
17292                } catch (RemoteException ignored) {
17293                }
17294            }
17295            mCallbacks.finishBroadcast();
17296            args.recycle();
17297        }
17298
17299        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17300                throws RemoteException {
17301            switch (what) {
17302                case MSG_CREATED: {
17303                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17304                    break;
17305                }
17306                case MSG_STATUS_CHANGED: {
17307                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17308                    break;
17309                }
17310            }
17311        }
17312
17313        private void notifyCreated(int moveId, Bundle extras) {
17314            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17315
17316            final SomeArgs args = SomeArgs.obtain();
17317            args.argi1 = moveId;
17318            args.arg2 = extras;
17319            obtainMessage(MSG_CREATED, args).sendToTarget();
17320        }
17321
17322        private void notifyStatusChanged(int moveId, int status) {
17323            notifyStatusChanged(moveId, status, -1);
17324        }
17325
17326        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17327            Slog.v(TAG, "Move " + moveId + " status " + status);
17328
17329            final SomeArgs args = SomeArgs.obtain();
17330            args.argi1 = moveId;
17331            args.argi2 = status;
17332            args.arg3 = estMillis;
17333            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17334
17335            synchronized (mLastStatus) {
17336                mLastStatus.put(moveId, status);
17337            }
17338        }
17339    }
17340
17341    private final static class OnPermissionChangeListeners extends Handler {
17342        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17343
17344        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17345                new RemoteCallbackList<>();
17346
17347        public OnPermissionChangeListeners(Looper looper) {
17348            super(looper);
17349        }
17350
17351        @Override
17352        public void handleMessage(Message msg) {
17353            switch (msg.what) {
17354                case MSG_ON_PERMISSIONS_CHANGED: {
17355                    final int uid = msg.arg1;
17356                    handleOnPermissionsChanged(uid);
17357                } break;
17358            }
17359        }
17360
17361        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17362            mPermissionListeners.register(listener);
17363
17364        }
17365
17366        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17367            mPermissionListeners.unregister(listener);
17368        }
17369
17370        public void onPermissionsChanged(int uid) {
17371            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17372                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17373            }
17374        }
17375
17376        private void handleOnPermissionsChanged(int uid) {
17377            final int count = mPermissionListeners.beginBroadcast();
17378            try {
17379                for (int i = 0; i < count; i++) {
17380                    IOnPermissionsChangeListener callback = mPermissionListeners
17381                            .getBroadcastItem(i);
17382                    try {
17383                        callback.onPermissionsChanged(uid);
17384                    } catch (RemoteException e) {
17385                        Log.e(TAG, "Permission listener is dead", e);
17386                    }
17387                }
17388            } finally {
17389                mPermissionListeners.finishBroadcast();
17390            }
17391        }
17392    }
17393
17394    private class PackageManagerInternalImpl extends PackageManagerInternal {
17395        @Override
17396        public void setLocationPackagesProvider(PackagesProvider provider) {
17397            synchronized (mPackages) {
17398                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17399            }
17400        }
17401
17402        @Override
17403        public void setImePackagesProvider(PackagesProvider provider) {
17404            synchronized (mPackages) {
17405                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17406            }
17407        }
17408
17409        @Override
17410        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17411            synchronized (mPackages) {
17412                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17413            }
17414        }
17415
17416        @Override
17417        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17418            synchronized (mPackages) {
17419                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17420            }
17421        }
17422
17423        @Override
17424        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17425            synchronized (mPackages) {
17426                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17427            }
17428        }
17429
17430        @Override
17431        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17432            synchronized (mPackages) {
17433                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17434            }
17435        }
17436
17437        @Override
17438        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17439            synchronized (mPackages) {
17440                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17441            }
17442        }
17443
17444        @Override
17445        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17446            synchronized (mPackages) {
17447                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17448                        packageName, userId);
17449            }
17450        }
17451
17452        @Override
17453        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17454            synchronized (mPackages) {
17455                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17456                        packageName, userId);
17457            }
17458        }
17459
17460        @Override
17461        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17462            synchronized (mPackages) {
17463                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17464                        packageName, userId);
17465            }
17466        }
17467
17468        @Override
17469        public void setKeepUninstalledPackages(final List<String> packageList) {
17470            Preconditions.checkNotNull(packageList);
17471            List<String> removedFromList = null;
17472            synchronized (mPackages) {
17473                if (mKeepUninstalledPackages != null) {
17474                    final int packagesCount = mKeepUninstalledPackages.size();
17475                    for (int i = 0; i < packagesCount; i++) {
17476                        String oldPackage = mKeepUninstalledPackages.get(i);
17477                        if (packageList != null && packageList.contains(oldPackage)) {
17478                            continue;
17479                        }
17480                        if (removedFromList == null) {
17481                            removedFromList = new ArrayList<>();
17482                        }
17483                        removedFromList.add(oldPackage);
17484                    }
17485                }
17486                mKeepUninstalledPackages = new ArrayList<>(packageList);
17487                if (removedFromList != null) {
17488                    final int removedCount = removedFromList.size();
17489                    for (int i = 0; i < removedCount; i++) {
17490                        deletePackageIfUnusedLPr(removedFromList.get(i));
17491                    }
17492                }
17493            }
17494        }
17495
17496        @Override
17497        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17498            synchronized (mPackages) {
17499                // If we do not support permission review, done.
17500                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17501                    return false;
17502                }
17503
17504                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17505                if (packageSetting == null) {
17506                    return false;
17507                }
17508
17509                // Permission review applies only to apps not supporting the new permission model.
17510                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17511                    return false;
17512                }
17513
17514                // Legacy apps have the permission and get user consent on launch.
17515                PermissionsState permissionsState = packageSetting.getPermissionsState();
17516                return permissionsState.isPermissionReviewRequired(userId);
17517            }
17518        }
17519    }
17520
17521    @Override
17522    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17523        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17524        synchronized (mPackages) {
17525            final long identity = Binder.clearCallingIdentity();
17526            try {
17527                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17528                        packageNames, userId);
17529            } finally {
17530                Binder.restoreCallingIdentity(identity);
17531            }
17532        }
17533    }
17534
17535    private static void enforceSystemOrPhoneCaller(String tag) {
17536        int callingUid = Binder.getCallingUid();
17537        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17538            throw new SecurityException(
17539                    "Cannot call " + tag + " from UID " + callingUid);
17540        }
17541    }
17542}
17543