PackageManagerService.java revision 4f6d400b0fa4c94e0f785a7b15ffb30126e6759d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
21import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
37import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
39import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.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;
74
75import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
76import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
77import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
78import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
79import static com.android.internal.util.ArrayUtils.appendInt;
80import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
81import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
82import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
83import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
84import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
85import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
87import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
88import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
89
90import android.Manifest;
91import android.app.ActivityManager;
92import android.app.ActivityManagerNative;
93import android.app.AppGlobals;
94import android.app.IActivityManager;
95import android.app.admin.IDevicePolicyManager;
96import android.app.backup.IBackupManager;
97import android.content.BroadcastReceiver;
98import android.content.ComponentName;
99import android.content.Context;
100import android.content.IIntentReceiver;
101import android.content.Intent;
102import android.content.IntentFilter;
103import android.content.IntentSender;
104import android.content.IntentSender.SendIntentException;
105import android.content.ServiceConnection;
106import android.content.pm.ActivityInfo;
107import android.content.pm.ApplicationInfo;
108import android.content.pm.AppsQueryHelper;
109import android.content.pm.ComponentInfo;
110import android.content.pm.EphemeralApplicationInfo;
111import android.content.pm.EphemeralResolveInfo;
112import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
113import android.content.pm.FeatureInfo;
114import android.content.pm.IOnPermissionsChangeListener;
115import android.content.pm.IPackageDataObserver;
116import android.content.pm.IPackageDeleteObserver;
117import android.content.pm.IPackageDeleteObserver2;
118import android.content.pm.IPackageInstallObserver2;
119import android.content.pm.IPackageInstaller;
120import android.content.pm.IPackageManager;
121import android.content.pm.IPackageMoveObserver;
122import android.content.pm.IPackageStatsObserver;
123import android.content.pm.InstrumentationInfo;
124import android.content.pm.IntentFilterVerificationInfo;
125import android.content.pm.KeySet;
126import android.content.pm.PackageCleanItem;
127import android.content.pm.PackageInfo;
128import android.content.pm.PackageInfoLite;
129import android.content.pm.PackageInstaller;
130import android.content.pm.PackageManager;
131import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
132import android.content.pm.PackageManagerInternal;
133import android.content.pm.PackageParser;
134import android.content.pm.PackageParser.ActivityIntentInfo;
135import android.content.pm.PackageParser.PackageLite;
136import android.content.pm.PackageParser.PackageParserException;
137import android.content.pm.PackageStats;
138import android.content.pm.PackageUserState;
139import android.content.pm.ParceledListSlice;
140import android.content.pm.PermissionGroupInfo;
141import android.content.pm.PermissionInfo;
142import android.content.pm.ProviderInfo;
143import android.content.pm.ResolveInfo;
144import android.content.pm.ServiceInfo;
145import android.content.pm.Signature;
146import android.content.pm.UserInfo;
147import android.content.pm.VerificationParams;
148import android.content.pm.VerifierDeviceIdentity;
149import android.content.pm.VerifierInfo;
150import android.content.res.Resources;
151import android.graphics.Bitmap;
152import android.hardware.display.DisplayManager;
153import android.net.Uri;
154import android.os.Binder;
155import android.os.Build;
156import android.os.Bundle;
157import android.os.Debug;
158import android.os.Environment;
159import android.os.Environment.UserEnvironment;
160import android.os.FileUtils;
161import android.os.Handler;
162import android.os.IBinder;
163import android.os.Looper;
164import android.os.Message;
165import android.os.Parcel;
166import android.os.ParcelFileDescriptor;
167import android.os.Process;
168import android.os.RemoteCallbackList;
169import android.os.RemoteException;
170import android.os.ResultReceiver;
171import android.os.SELinux;
172import android.os.ServiceManager;
173import android.os.SystemClock;
174import android.os.SystemProperties;
175import android.os.Trace;
176import android.os.UserHandle;
177import android.os.UserManager;
178import android.os.storage.IMountService;
179import android.os.storage.MountServiceInternal;
180import android.os.storage.StorageEventListener;
181import android.os.storage.StorageManager;
182import android.os.storage.VolumeInfo;
183import android.os.storage.VolumeRecord;
184import android.security.KeyStore;
185import android.security.SystemKeyStore;
186import android.system.ErrnoException;
187import android.system.Os;
188import android.system.StructStat;
189import android.text.TextUtils;
190import android.text.format.DateUtils;
191import android.util.ArrayMap;
192import android.util.ArraySet;
193import android.util.AtomicFile;
194import android.util.DisplayMetrics;
195import android.util.EventLog;
196import android.util.ExceptionUtils;
197import android.util.Log;
198import android.util.LogPrinter;
199import android.util.MathUtils;
200import android.util.PrintStreamPrinter;
201import android.util.Slog;
202import android.util.SparseArray;
203import android.util.SparseBooleanArray;
204import android.util.SparseIntArray;
205import android.util.Xml;
206import android.view.Display;
207
208import com.android.internal.R;
209import com.android.internal.annotations.GuardedBy;
210import com.android.internal.app.IMediaContainerService;
211import com.android.internal.app.ResolverActivity;
212import com.android.internal.content.NativeLibraryHelper;
213import com.android.internal.content.PackageHelper;
214import com.android.internal.os.IParcelFileDescriptorFactory;
215import com.android.internal.os.SomeArgs;
216import com.android.internal.os.Zygote;
217import com.android.internal.util.ArrayUtils;
218import com.android.internal.util.FastPrintWriter;
219import com.android.internal.util.FastXmlSerializer;
220import com.android.internal.util.IndentingPrintWriter;
221import com.android.internal.util.Preconditions;
222import com.android.server.EventLogTags;
223import com.android.server.FgThread;
224import com.android.server.IntentResolver;
225import com.android.server.LocalServices;
226import com.android.server.ServiceThread;
227import com.android.server.SystemConfig;
228import com.android.server.Watchdog;
229import com.android.server.pm.PermissionsState.PermissionState;
230import com.android.server.pm.Settings.DatabaseVersion;
231import com.android.server.pm.Settings.VersionInfo;
232import com.android.server.storage.DeviceStorageMonitorInternal;
233
234import dalvik.system.DexFile;
235import dalvik.system.VMRuntime;
236
237import libcore.io.IoUtils;
238import libcore.util.EmptyArray;
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    private static final boolean DEBUG_TRIAGED_MISSING = false;
311
312    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
313
314    private static final int RADIO_UID = Process.PHONE_UID;
315    private static final int LOG_UID = Process.LOG_UID;
316    private static final int NFC_UID = Process.NFC_UID;
317    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
318    private static final int SHELL_UID = Process.SHELL_UID;
319
320    // Cap the size of permission trees that 3rd party apps can define
321    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
322
323    // Suffix used during package installation when copying/moving
324    // package apks to install directory.
325    private static final String INSTALL_PACKAGE_SUFFIX = "-";
326
327    static final int SCAN_NO_DEX = 1<<1;
328    static final int SCAN_FORCE_DEX = 1<<2;
329    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
330    static final int SCAN_NEW_INSTALL = 1<<4;
331    static final int SCAN_NO_PATHS = 1<<5;
332    static final int SCAN_UPDATE_TIME = 1<<6;
333    static final int SCAN_DEFER_DEX = 1<<7;
334    static final int SCAN_BOOTING = 1<<8;
335    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
336    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
337    static final int SCAN_REPLACING = 1<<11;
338    static final int SCAN_REQUIRE_KNOWN = 1<<12;
339    static final int SCAN_MOVE = 1<<13;
340    static final int SCAN_INITIAL = 1<<14;
341
342    static final int REMOVE_CHATTY = 1<<16;
343
344    private static final int[] EMPTY_INT_ARRAY = new int[0];
345
346    /**
347     * Timeout (in milliseconds) after which the watchdog should declare that
348     * our handler thread is wedged.  The usual default for such things is one
349     * minute but we sometimes do very lengthy I/O operations on this thread,
350     * such as installing multi-gigabyte applications, so ours needs to be longer.
351     */
352    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
353
354    /**
355     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
356     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
357     * settings entry if available, otherwise we use the hardcoded default.  If it's been
358     * more than this long since the last fstrim, we force one during the boot sequence.
359     *
360     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
361     * one gets run at the next available charging+idle time.  This final mandatory
362     * no-fstrim check kicks in only of the other scheduling criteria is never met.
363     */
364    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
365
366    /**
367     * Whether verification is enabled by default.
368     */
369    private static final boolean DEFAULT_VERIFY_ENABLE = true;
370
371    /**
372     * The default maximum time to wait for the verification agent to return in
373     * milliseconds.
374     */
375    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
376
377    /**
378     * The default response for package verification timeout.
379     *
380     * This can be either PackageManager.VERIFICATION_ALLOW or
381     * PackageManager.VERIFICATION_REJECT.
382     */
383    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
384
385    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
386
387    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
388            DEFAULT_CONTAINER_PACKAGE,
389            "com.android.defcontainer.DefaultContainerService");
390
391    private static final String KILL_APP_REASON_GIDS_CHANGED =
392            "permission grant or revoke changed gids";
393
394    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
395            "permissions revoked";
396
397    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
398
399    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
400
401    /** Permission grant: not grant the permission. */
402    private static final int GRANT_DENIED = 1;
403
404    /** Permission grant: grant the permission as an install permission. */
405    private static final int GRANT_INSTALL = 2;
406
407    /** Permission grant: grant the permission as a runtime one. */
408    private static final int GRANT_RUNTIME = 3;
409
410    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
411    private static final int GRANT_UPGRADE = 4;
412
413    /** Canonical intent used to identify what counts as a "web browser" app */
414    private static final Intent sBrowserIntent;
415    static {
416        sBrowserIntent = new Intent();
417        sBrowserIntent.setAction(Intent.ACTION_VIEW);
418        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
419        sBrowserIntent.setData(Uri.parse("http:"));
420    }
421
422    final ServiceThread mHandlerThread;
423
424    final PackageHandler mHandler;
425
426    /**
427     * Messages for {@link #mHandler} that need to wait for system ready before
428     * being dispatched.
429     */
430    private ArrayList<Message> mPostSystemReadyMessages;
431
432    final int mSdkVersion = Build.VERSION.SDK_INT;
433
434    final Context mContext;
435    final boolean mFactoryTest;
436    final boolean mOnlyCore;
437    final DisplayMetrics mMetrics;
438    final int mDefParseFlags;
439    final String[] mSeparateProcesses;
440    final boolean mIsUpgrade;
441
442    /** The location for ASEC container files on internal storage. */
443    final String mAsecInternalPath;
444
445    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
446    // LOCK HELD.  Can be called with mInstallLock held.
447    @GuardedBy("mInstallLock")
448    final Installer mInstaller;
449
450    /** Directory where installed third-party apps stored */
451    final File mAppInstallDir;
452    final File mEphemeralInstallDir;
453
454    /**
455     * Directory to which applications installed internally have their
456     * 32 bit native libraries copied.
457     */
458    private File mAppLib32InstallDir;
459
460    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
461    // apps.
462    final File mDrmAppPrivateInstallDir;
463
464    // ----------------------------------------------------------------
465
466    // Lock for state used when installing and doing other long running
467    // operations.  Methods that must be called with this lock held have
468    // the suffix "LI".
469    final Object mInstallLock = new Object();
470
471    // ----------------------------------------------------------------
472
473    // Keys are String (package name), values are Package.  This also serves
474    // as the lock for the global state.  Methods that must be called with
475    // this lock held have the prefix "LP".
476    @GuardedBy("mPackages")
477    final ArrayMap<String, PackageParser.Package> mPackages =
478            new ArrayMap<String, PackageParser.Package>();
479
480    // Tracks available target package names -> overlay package paths.
481    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
482        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
483
484    /**
485     * Tracks new system packages [received in an OTA] that we expect to
486     * find updated user-installed versions. Keys are package name, values
487     * are package location.
488     */
489    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
490
491    /**
492     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
493     */
494    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
495    /**
496     * Whether or not system app permissions should be promoted from install to runtime.
497     */
498    boolean mPromoteSystemApps;
499
500    final Settings mSettings;
501    boolean mRestoredSettings;
502
503    // System configuration read by SystemConfig.
504    final int[] mGlobalGids;
505    final SparseArray<ArraySet<String>> mSystemPermissions;
506    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
507
508    // If mac_permissions.xml was found for seinfo labeling.
509    boolean mFoundPolicyFile;
510
511    // If a recursive restorecon of /data/data/<pkg> is needed.
512    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
513
514    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
515
516    public static final class SharedLibraryEntry {
517        public final String path;
518        public final String apk;
519
520        SharedLibraryEntry(String _path, String _apk) {
521            path = _path;
522            apk = _apk;
523        }
524    }
525
526    // Currently known shared libraries.
527    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
528            new ArrayMap<String, SharedLibraryEntry>();
529
530    // All available activities, for your resolving pleasure.
531    final ActivityIntentResolver mActivities =
532            new ActivityIntentResolver();
533
534    // All available receivers, for your resolving pleasure.
535    final ActivityIntentResolver mReceivers =
536            new ActivityIntentResolver();
537
538    // All available services, for your resolving pleasure.
539    final ServiceIntentResolver mServices = new ServiceIntentResolver();
540
541    // All available providers, for your resolving pleasure.
542    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
543
544    // Mapping from provider base names (first directory in content URI codePath)
545    // to the provider information.
546    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
547            new ArrayMap<String, PackageParser.Provider>();
548
549    // Mapping from instrumentation class names to info about them.
550    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
551            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
552
553    // Mapping from permission names to info about them.
554    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
555            new ArrayMap<String, PackageParser.PermissionGroup>();
556
557    // Packages whose data we have transfered into another package, thus
558    // should no longer exist.
559    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
560
561    // Broadcast actions that are only available to the system.
562    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
563
564    /** List of packages waiting for verification. */
565    final SparseArray<PackageVerificationState> mPendingVerification
566            = new SparseArray<PackageVerificationState>();
567
568    /** Set of packages associated with each app op permission. */
569    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
570
571    final PackageInstallerService mInstallerService;
572
573    private final PackageDexOptimizer mPackageDexOptimizer;
574
575    private AtomicInteger mNextMoveId = new AtomicInteger();
576    private final MoveCallbacks mMoveCallbacks;
577
578    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
579
580    // Cache of users who need badging.
581    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
582
583    /** Token for keys in mPendingVerification. */
584    private int mPendingVerificationToken = 0;
585
586    volatile boolean mSystemReady;
587    volatile boolean mSafeMode;
588    volatile boolean mHasSystemUidErrors;
589
590    ApplicationInfo mAndroidApplication;
591    final ActivityInfo mResolveActivity = new ActivityInfo();
592    final ResolveInfo mResolveInfo = new ResolveInfo();
593    ComponentName mResolveComponentName;
594    PackageParser.Package mPlatformPackage;
595    ComponentName mCustomResolverComponentName;
596
597    boolean mResolverReplaced = false;
598
599    private final ComponentName mIntentFilterVerifierComponent;
600    private int mIntentFilterVerificationToken = 0;
601
602    /** Component that knows whether or not an ephemeral application exists */
603    final ComponentName mEphemeralResolverComponent;
604    /** The service connection to the ephemeral resolver */
605    final EphemeralResolverConnection mEphemeralResolverConnection;
606
607    /** Component used to install ephemeral applications */
608    final ComponentName mEphemeralInstallerComponent;
609    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
610    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
611
612    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
613            = new SparseArray<IntentFilterVerificationState>();
614
615    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
616            new DefaultPermissionGrantPolicy(this);
617
618    // List of packages names to keep cached, even if they are uninstalled for all users
619    private List<String> mKeepUninstalledPackages;
620
621    private static class IFVerificationParams {
622        PackageParser.Package pkg;
623        boolean replacing;
624        int userId;
625        int verifierUid;
626
627        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
628                int _userId, int _verifierUid) {
629            pkg = _pkg;
630            replacing = _replacing;
631            userId = _userId;
632            replacing = _replacing;
633            verifierUid = _verifierUid;
634        }
635    }
636
637    private interface IntentFilterVerifier<T extends IntentFilter> {
638        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
639                                               T filter, String packageName);
640        void startVerifications(int userId);
641        void receiveVerificationResponse(int verificationId);
642    }
643
644    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
645        private Context mContext;
646        private ComponentName mIntentFilterVerifierComponent;
647        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
648
649        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
650            mContext = context;
651            mIntentFilterVerifierComponent = verifierComponent;
652        }
653
654        private String getDefaultScheme() {
655            return IntentFilter.SCHEME_HTTPS;
656        }
657
658        @Override
659        public void startVerifications(int userId) {
660            // Launch verifications requests
661            int count = mCurrentIntentFilterVerifications.size();
662            for (int n=0; n<count; n++) {
663                int verificationId = mCurrentIntentFilterVerifications.get(n);
664                final IntentFilterVerificationState ivs =
665                        mIntentFilterVerificationStates.get(verificationId);
666
667                String packageName = ivs.getPackageName();
668
669                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
670                final int filterCount = filters.size();
671                ArraySet<String> domainsSet = new ArraySet<>();
672                for (int m=0; m<filterCount; m++) {
673                    PackageParser.ActivityIntentInfo filter = filters.get(m);
674                    domainsSet.addAll(filter.getHostsList());
675                }
676                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
677                synchronized (mPackages) {
678                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
679                            packageName, domainsList) != null) {
680                        scheduleWriteSettingsLocked();
681                    }
682                }
683                sendVerificationRequest(userId, verificationId, ivs);
684            }
685            mCurrentIntentFilterVerifications.clear();
686        }
687
688        private void sendVerificationRequest(int userId, int verificationId,
689                IntentFilterVerificationState ivs) {
690
691            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
692            verificationIntent.putExtra(
693                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
694                    verificationId);
695            verificationIntent.putExtra(
696                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
697                    getDefaultScheme());
698            verificationIntent.putExtra(
699                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
700                    ivs.getHostsString());
701            verificationIntent.putExtra(
702                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
703                    ivs.getPackageName());
704            verificationIntent.setComponent(mIntentFilterVerifierComponent);
705            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
706
707            UserHandle user = new UserHandle(userId);
708            mContext.sendBroadcastAsUser(verificationIntent, user);
709            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
710                    "Sending IntentFilter verification broadcast");
711        }
712
713        public void receiveVerificationResponse(int verificationId) {
714            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
715
716            final boolean verified = ivs.isVerified();
717
718            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
719            final int count = filters.size();
720            if (DEBUG_DOMAIN_VERIFICATION) {
721                Slog.i(TAG, "Received verification response " + verificationId
722                        + " for " + count + " filters, verified=" + verified);
723            }
724            for (int n=0; n<count; n++) {
725                PackageParser.ActivityIntentInfo filter = filters.get(n);
726                filter.setVerified(verified);
727
728                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
729                        + " verified with result:" + verified + " and hosts:"
730                        + ivs.getHostsString());
731            }
732
733            mIntentFilterVerificationStates.remove(verificationId);
734
735            final String packageName = ivs.getPackageName();
736            IntentFilterVerificationInfo ivi = null;
737
738            synchronized (mPackages) {
739                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
740            }
741            if (ivi == null) {
742                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
743                        + verificationId + " packageName:" + packageName);
744                return;
745            }
746            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
747                    "Updating IntentFilterVerificationInfo for package " + packageName
748                            +" verificationId:" + verificationId);
749
750            synchronized (mPackages) {
751                if (verified) {
752                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
753                } else {
754                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
755                }
756                scheduleWriteSettingsLocked();
757
758                final int userId = ivs.getUserId();
759                if (userId != UserHandle.USER_ALL) {
760                    final int userStatus =
761                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
762
763                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
764                    boolean needUpdate = false;
765
766                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
767                    // already been set by the User thru the Disambiguation dialog
768                    switch (userStatus) {
769                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
770                            if (verified) {
771                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
772                            } else {
773                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
774                            }
775                            needUpdate = true;
776                            break;
777
778                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
779                            if (verified) {
780                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
781                                needUpdate = true;
782                            }
783                            break;
784
785                        default:
786                            // Nothing to do
787                    }
788
789                    if (needUpdate) {
790                        mSettings.updateIntentFilterVerificationStatusLPw(
791                                packageName, updatedStatus, userId);
792                        scheduleWritePackageRestrictionsLocked(userId);
793                    }
794                }
795            }
796        }
797
798        @Override
799        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
800                    ActivityIntentInfo filter, String packageName) {
801            if (!hasValidDomains(filter)) {
802                return false;
803            }
804            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
805            if (ivs == null) {
806                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
807                        packageName);
808            }
809            if (DEBUG_DOMAIN_VERIFICATION) {
810                Slog.d(TAG, "Adding verification filter for " + packageName + " : " + filter);
811            }
812            ivs.addFilter(filter);
813            return true;
814        }
815
816        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
817                int userId, int verificationId, String packageName) {
818            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
819                    verifierUid, userId, packageName);
820            ivs.setPendingState();
821            synchronized (mPackages) {
822                mIntentFilterVerificationStates.append(verificationId, ivs);
823                mCurrentIntentFilterVerifications.add(verificationId);
824            }
825            return ivs;
826        }
827    }
828
829    private static boolean hasValidDomains(ActivityIntentInfo filter) {
830        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
831                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
832                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
833    }
834
835    private IntentFilterVerifier mIntentFilterVerifier;
836
837    // Set of pending broadcasts for aggregating enable/disable of components.
838    static class PendingPackageBroadcasts {
839        // for each user id, a map of <package name -> components within that package>
840        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
841
842        public PendingPackageBroadcasts() {
843            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
844        }
845
846        public ArrayList<String> get(int userId, String packageName) {
847            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
848            return packages.get(packageName);
849        }
850
851        public void put(int userId, String packageName, ArrayList<String> components) {
852            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
853            packages.put(packageName, components);
854        }
855
856        public void remove(int userId, String packageName) {
857            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
858            if (packages != null) {
859                packages.remove(packageName);
860            }
861        }
862
863        public void remove(int userId) {
864            mUidMap.remove(userId);
865        }
866
867        public int userIdCount() {
868            return mUidMap.size();
869        }
870
871        public int userIdAt(int n) {
872            return mUidMap.keyAt(n);
873        }
874
875        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
876            return mUidMap.get(userId);
877        }
878
879        public int size() {
880            // total number of pending broadcast entries across all userIds
881            int num = 0;
882            for (int i = 0; i< mUidMap.size(); i++) {
883                num += mUidMap.valueAt(i).size();
884            }
885            return num;
886        }
887
888        public void clear() {
889            mUidMap.clear();
890        }
891
892        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
893            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
894            if (map == null) {
895                map = new ArrayMap<String, ArrayList<String>>();
896                mUidMap.put(userId, map);
897            }
898            return map;
899        }
900    }
901    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
902
903    // Service Connection to remote media container service to copy
904    // package uri's from external media onto secure containers
905    // or internal storage.
906    private IMediaContainerService mContainerService = null;
907
908    static final int SEND_PENDING_BROADCAST = 1;
909    static final int MCS_BOUND = 3;
910    static final int END_COPY = 4;
911    static final int INIT_COPY = 5;
912    static final int MCS_UNBIND = 6;
913    static final int START_CLEANING_PACKAGE = 7;
914    static final int FIND_INSTALL_LOC = 8;
915    static final int POST_INSTALL = 9;
916    static final int MCS_RECONNECT = 10;
917    static final int MCS_GIVE_UP = 11;
918    static final int UPDATED_MEDIA_STATUS = 12;
919    static final int WRITE_SETTINGS = 13;
920    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
921    static final int PACKAGE_VERIFIED = 15;
922    static final int CHECK_PENDING_VERIFICATION = 16;
923    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
924    static final int INTENT_FILTER_VERIFIED = 18;
925
926    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
927
928    // Delay time in millisecs
929    static final int BROADCAST_DELAY = 10 * 1000;
930
931    static UserManagerService sUserManager;
932
933    // Stores a list of users whose package restrictions file needs to be updated
934    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
935
936    final private DefaultContainerConnection mDefContainerConn =
937            new DefaultContainerConnection();
938    class DefaultContainerConnection implements ServiceConnection {
939        public void onServiceConnected(ComponentName name, IBinder service) {
940            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
941            IMediaContainerService imcs =
942                IMediaContainerService.Stub.asInterface(service);
943            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
944        }
945
946        public void onServiceDisconnected(ComponentName name) {
947            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
948        }
949    }
950
951    // Recordkeeping of restore-after-install operations that are currently in flight
952    // between the Package Manager and the Backup Manager
953    static class PostInstallData {
954        public InstallArgs args;
955        public PackageInstalledInfo res;
956
957        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
958            args = _a;
959            res = _r;
960        }
961    }
962
963    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
964    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
965
966    // XML tags for backup/restore of various bits of state
967    private static final String TAG_PREFERRED_BACKUP = "pa";
968    private static final String TAG_DEFAULT_APPS = "da";
969    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
970
971    final String mRequiredVerifierPackage;
972    final String mRequiredInstallerPackage;
973
974    private final PackageUsage mPackageUsage = new PackageUsage();
975
976    private class PackageUsage {
977        private static final int WRITE_INTERVAL
978            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
979
980        private final Object mFileLock = new Object();
981        private final AtomicLong mLastWritten = new AtomicLong(0);
982        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
983
984        private boolean mIsHistoricalPackageUsageAvailable = true;
985
986        boolean isHistoricalPackageUsageAvailable() {
987            return mIsHistoricalPackageUsageAvailable;
988        }
989
990        void write(boolean force) {
991            if (force) {
992                writeInternal();
993                return;
994            }
995            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
996                && !DEBUG_DEXOPT) {
997                return;
998            }
999            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1000                new Thread("PackageUsage_DiskWriter") {
1001                    @Override
1002                    public void run() {
1003                        try {
1004                            writeInternal();
1005                        } finally {
1006                            mBackgroundWriteRunning.set(false);
1007                        }
1008                    }
1009                }.start();
1010            }
1011        }
1012
1013        private void writeInternal() {
1014            synchronized (mPackages) {
1015                synchronized (mFileLock) {
1016                    AtomicFile file = getFile();
1017                    FileOutputStream f = null;
1018                    try {
1019                        f = file.startWrite();
1020                        BufferedOutputStream out = new BufferedOutputStream(f);
1021                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1022                        StringBuilder sb = new StringBuilder();
1023                        for (PackageParser.Package pkg : mPackages.values()) {
1024                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1025                                continue;
1026                            }
1027                            sb.setLength(0);
1028                            sb.append(pkg.packageName);
1029                            sb.append(' ');
1030                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1031                            sb.append('\n');
1032                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1033                        }
1034                        out.flush();
1035                        file.finishWrite(f);
1036                    } catch (IOException e) {
1037                        if (f != null) {
1038                            file.failWrite(f);
1039                        }
1040                        Log.e(TAG, "Failed to write package usage times", e);
1041                    }
1042                }
1043            }
1044            mLastWritten.set(SystemClock.elapsedRealtime());
1045        }
1046
1047        void readLP() {
1048            synchronized (mFileLock) {
1049                AtomicFile file = getFile();
1050                BufferedInputStream in = null;
1051                try {
1052                    in = new BufferedInputStream(file.openRead());
1053                    StringBuffer sb = new StringBuffer();
1054                    while (true) {
1055                        String packageName = readToken(in, sb, ' ');
1056                        if (packageName == null) {
1057                            break;
1058                        }
1059                        String timeInMillisString = readToken(in, sb, '\n');
1060                        if (timeInMillisString == null) {
1061                            throw new IOException("Failed to find last usage time for package "
1062                                                  + packageName);
1063                        }
1064                        PackageParser.Package pkg = mPackages.get(packageName);
1065                        if (pkg == null) {
1066                            continue;
1067                        }
1068                        long timeInMillis;
1069                        try {
1070                            timeInMillis = Long.parseLong(timeInMillisString);
1071                        } catch (NumberFormatException e) {
1072                            throw new IOException("Failed to parse " + timeInMillisString
1073                                                  + " as a long.", e);
1074                        }
1075                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1076                    }
1077                } catch (FileNotFoundException expected) {
1078                    mIsHistoricalPackageUsageAvailable = false;
1079                } catch (IOException e) {
1080                    Log.w(TAG, "Failed to read package usage times", e);
1081                } finally {
1082                    IoUtils.closeQuietly(in);
1083                }
1084            }
1085            mLastWritten.set(SystemClock.elapsedRealtime());
1086        }
1087
1088        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1089                throws IOException {
1090            sb.setLength(0);
1091            while (true) {
1092                int ch = in.read();
1093                if (ch == -1) {
1094                    if (sb.length() == 0) {
1095                        return null;
1096                    }
1097                    throw new IOException("Unexpected EOF");
1098                }
1099                if (ch == endOfToken) {
1100                    return sb.toString();
1101                }
1102                sb.append((char)ch);
1103            }
1104        }
1105
1106        private AtomicFile getFile() {
1107            File dataDir = Environment.getDataDirectory();
1108            File systemDir = new File(dataDir, "system");
1109            File fname = new File(systemDir, "package-usage.list");
1110            return new AtomicFile(fname);
1111        }
1112    }
1113
1114    class PackageHandler extends Handler {
1115        private boolean mBound = false;
1116        final ArrayList<HandlerParams> mPendingInstalls =
1117            new ArrayList<HandlerParams>();
1118
1119        private boolean connectToService() {
1120            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1121                    " DefaultContainerService");
1122            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1123            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1124            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1125                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1126                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1127                mBound = true;
1128                return true;
1129            }
1130            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1131            return false;
1132        }
1133
1134        private void disconnectService() {
1135            mContainerService = null;
1136            mBound = false;
1137            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1138            mContext.unbindService(mDefContainerConn);
1139            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1140        }
1141
1142        PackageHandler(Looper looper) {
1143            super(looper);
1144        }
1145
1146        public void handleMessage(Message msg) {
1147            try {
1148                doHandleMessage(msg);
1149            } finally {
1150                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1151            }
1152        }
1153
1154        void doHandleMessage(Message msg) {
1155            switch (msg.what) {
1156                case INIT_COPY: {
1157                    HandlerParams params = (HandlerParams) msg.obj;
1158                    int idx = mPendingInstalls.size();
1159                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1160                    // If a bind was already initiated we dont really
1161                    // need to do anything. The pending install
1162                    // will be processed later on.
1163                    if (!mBound) {
1164                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1165                                System.identityHashCode(mHandler));
1166                        // If this is the only one pending we might
1167                        // have to bind to the service again.
1168                        if (!connectToService()) {
1169                            Slog.e(TAG, "Failed to bind to media container service");
1170                            params.serviceError();
1171                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1172                                    System.identityHashCode(mHandler));
1173                            if (params.traceMethod != null) {
1174                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1175                                        params.traceCookie);
1176                            }
1177                            return;
1178                        } else {
1179                            // Once we bind to the service, the first
1180                            // pending request will be processed.
1181                            mPendingInstalls.add(idx, params);
1182                        }
1183                    } else {
1184                        mPendingInstalls.add(idx, params);
1185                        // Already bound to the service. Just make
1186                        // sure we trigger off processing the first request.
1187                        if (idx == 0) {
1188                            mHandler.sendEmptyMessage(MCS_BOUND);
1189                        }
1190                    }
1191                    break;
1192                }
1193                case MCS_BOUND: {
1194                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1195                    if (msg.obj != null) {
1196                        mContainerService = (IMediaContainerService) msg.obj;
1197                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1198                                System.identityHashCode(mHandler));
1199                    }
1200                    if (mContainerService == null) {
1201                        if (!mBound) {
1202                            // Something seriously wrong since we are not bound and we are not
1203                            // waiting for connection. Bail out.
1204                            Slog.e(TAG, "Cannot bind to media container service");
1205                            for (HandlerParams params : mPendingInstalls) {
1206                                // Indicate service bind error
1207                                params.serviceError();
1208                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1209                                        System.identityHashCode(params));
1210                                if (params.traceMethod != null) {
1211                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1212                                            params.traceMethod, params.traceCookie);
1213                                }
1214                                return;
1215                            }
1216                            mPendingInstalls.clear();
1217                        } else {
1218                            Slog.w(TAG, "Waiting to connect to media container service");
1219                        }
1220                    } else if (mPendingInstalls.size() > 0) {
1221                        HandlerParams params = mPendingInstalls.get(0);
1222                        if (params != null) {
1223                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1224                                    System.identityHashCode(params));
1225                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1226                            if (params.startCopy()) {
1227                                // We are done...  look for more work or to
1228                                // go idle.
1229                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1230                                        "Checking for more work or unbind...");
1231                                // Delete pending install
1232                                if (mPendingInstalls.size() > 0) {
1233                                    mPendingInstalls.remove(0);
1234                                }
1235                                if (mPendingInstalls.size() == 0) {
1236                                    if (mBound) {
1237                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1238                                                "Posting delayed MCS_UNBIND");
1239                                        removeMessages(MCS_UNBIND);
1240                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1241                                        // Unbind after a little delay, to avoid
1242                                        // continual thrashing.
1243                                        sendMessageDelayed(ubmsg, 10000);
1244                                    }
1245                                } else {
1246                                    // There are more pending requests in queue.
1247                                    // Just post MCS_BOUND message to trigger processing
1248                                    // of next pending install.
1249                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1250                                            "Posting MCS_BOUND for next work");
1251                                    mHandler.sendEmptyMessage(MCS_BOUND);
1252                                }
1253                            }
1254                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1255                        }
1256                    } else {
1257                        // Should never happen ideally.
1258                        Slog.w(TAG, "Empty queue");
1259                    }
1260                    break;
1261                }
1262                case MCS_RECONNECT: {
1263                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1264                    if (mPendingInstalls.size() > 0) {
1265                        if (mBound) {
1266                            disconnectService();
1267                        }
1268                        if (!connectToService()) {
1269                            Slog.e(TAG, "Failed to bind to media container service");
1270                            for (HandlerParams params : mPendingInstalls) {
1271                                // Indicate service bind error
1272                                params.serviceError();
1273                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1274                                        System.identityHashCode(params));
1275                            }
1276                            mPendingInstalls.clear();
1277                        }
1278                    }
1279                    break;
1280                }
1281                case MCS_UNBIND: {
1282                    // If there is no actual work left, then time to unbind.
1283                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1284
1285                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1286                        if (mBound) {
1287                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1288
1289                            disconnectService();
1290                        }
1291                    } else if (mPendingInstalls.size() > 0) {
1292                        // There are more pending requests in queue.
1293                        // Just post MCS_BOUND message to trigger processing
1294                        // of next pending install.
1295                        mHandler.sendEmptyMessage(MCS_BOUND);
1296                    }
1297
1298                    break;
1299                }
1300                case MCS_GIVE_UP: {
1301                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1302                    HandlerParams params = mPendingInstalls.remove(0);
1303                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1304                            System.identityHashCode(params));
1305                    break;
1306                }
1307                case SEND_PENDING_BROADCAST: {
1308                    String packages[];
1309                    ArrayList<String> components[];
1310                    int size = 0;
1311                    int uids[];
1312                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1313                    synchronized (mPackages) {
1314                        if (mPendingBroadcasts == null) {
1315                            return;
1316                        }
1317                        size = mPendingBroadcasts.size();
1318                        if (size <= 0) {
1319                            // Nothing to be done. Just return
1320                            return;
1321                        }
1322                        packages = new String[size];
1323                        components = new ArrayList[size];
1324                        uids = new int[size];
1325                        int i = 0;  // filling out the above arrays
1326
1327                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1328                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1329                            Iterator<Map.Entry<String, ArrayList<String>>> it
1330                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1331                                            .entrySet().iterator();
1332                            while (it.hasNext() && i < size) {
1333                                Map.Entry<String, ArrayList<String>> ent = it.next();
1334                                packages[i] = ent.getKey();
1335                                components[i] = ent.getValue();
1336                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1337                                uids[i] = (ps != null)
1338                                        ? UserHandle.getUid(packageUserId, ps.appId)
1339                                        : -1;
1340                                i++;
1341                            }
1342                        }
1343                        size = i;
1344                        mPendingBroadcasts.clear();
1345                    }
1346                    // Send broadcasts
1347                    for (int i = 0; i < size; i++) {
1348                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1349                    }
1350                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1351                    break;
1352                }
1353                case START_CLEANING_PACKAGE: {
1354                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1355                    final String packageName = (String)msg.obj;
1356                    final int userId = msg.arg1;
1357                    final boolean andCode = msg.arg2 != 0;
1358                    synchronized (mPackages) {
1359                        if (userId == UserHandle.USER_ALL) {
1360                            int[] users = sUserManager.getUserIds();
1361                            for (int user : users) {
1362                                mSettings.addPackageToCleanLPw(
1363                                        new PackageCleanItem(user, packageName, andCode));
1364                            }
1365                        } else {
1366                            mSettings.addPackageToCleanLPw(
1367                                    new PackageCleanItem(userId, packageName, andCode));
1368                        }
1369                    }
1370                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1371                    startCleaningPackages();
1372                } break;
1373                case POST_INSTALL: {
1374                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1375
1376                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1377                    mRunningInstalls.delete(msg.arg1);
1378                    boolean deleteOld = false;
1379
1380                    if (data != null) {
1381                        InstallArgs args = data.args;
1382                        PackageInstalledInfo res = data.res;
1383
1384                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1385                            final String packageName = res.pkg.applicationInfo.packageName;
1386                            res.removedInfo.sendBroadcast(false, true, false);
1387                            Bundle extras = new Bundle(1);
1388                            extras.putInt(Intent.EXTRA_UID, res.uid);
1389
1390                            // Now that we successfully installed the package, grant runtime
1391                            // permissions if requested before broadcasting the install.
1392                            if ((args.installFlags
1393                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1394                                    && res.pkg.applicationInfo.targetSdkVersion
1395                                            >= Build.VERSION_CODES.M) {
1396                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1397                                        args.installGrantPermissions);
1398                            }
1399
1400                            synchronized (mPackages) {
1401                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1402                            }
1403
1404                            // Determine the set of users who are adding this
1405                            // package for the first time vs. those who are seeing
1406                            // an update.
1407                            int[] firstUsers;
1408                            int[] updateUsers = new int[0];
1409                            if (res.origUsers == null || res.origUsers.length == 0) {
1410                                firstUsers = res.newUsers;
1411                            } else {
1412                                firstUsers = new int[0];
1413                                for (int i=0; i<res.newUsers.length; i++) {
1414                                    int user = res.newUsers[i];
1415                                    boolean isNew = true;
1416                                    for (int j=0; j<res.origUsers.length; j++) {
1417                                        if (res.origUsers[j] == user) {
1418                                            isNew = false;
1419                                            break;
1420                                        }
1421                                    }
1422                                    if (isNew) {
1423                                        int[] newFirst = new int[firstUsers.length+1];
1424                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1425                                                firstUsers.length);
1426                                        newFirst[firstUsers.length] = user;
1427                                        firstUsers = newFirst;
1428                                    } else {
1429                                        int[] newUpdate = new int[updateUsers.length+1];
1430                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1431                                                updateUsers.length);
1432                                        newUpdate[updateUsers.length] = user;
1433                                        updateUsers = newUpdate;
1434                                    }
1435                                }
1436                            }
1437                            // don't broadcast for ephemeral installs/updates
1438                            final boolean isEphemeral = isEphemeral(res.pkg);
1439                            if (!isEphemeral) {
1440                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1441                                        extras, 0 /*flags*/, null /*targetPackage*/,
1442                                        null /*finishedReceiver*/, firstUsers);
1443                            }
1444                            final boolean update = res.removedInfo.removedPackage != null;
1445                            if (update) {
1446                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1447                            }
1448                            if (!isEphemeral) {
1449                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1450                                        extras, 0 /*flags*/, null /*targetPackage*/,
1451                                        null /*finishedReceiver*/, updateUsers);
1452                            }
1453                            if (update) {
1454                                if (!isEphemeral) {
1455                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1456                                            packageName, extras, 0 /*flags*/,
1457                                            null /*targetPackage*/, null /*finishedReceiver*/,
1458                                            updateUsers);
1459                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1460                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1461                                            packageName /*targetPackage*/,
1462                                            null /*finishedReceiver*/, updateUsers);
1463                                }
1464
1465                                // treat asec-hosted packages like removable media on upgrade
1466                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1467                                    if (DEBUG_INSTALL) {
1468                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1469                                                + " is ASEC-hosted -> AVAILABLE");
1470                                    }
1471                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1472                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1473                                    pkgList.add(packageName);
1474                                    sendResourcesChangedBroadcast(true, true,
1475                                            pkgList,uidArray, null);
1476                                }
1477                            }
1478                            if (res.removedInfo.args != null) {
1479                                // Remove the replaced package's older resources safely now
1480                                deleteOld = true;
1481                            }
1482
1483                            // If this app is a browser and it's newly-installed for some
1484                            // users, clear any default-browser state in those users
1485                            if (firstUsers.length > 0) {
1486                                // the app's nature doesn't depend on the user, so we can just
1487                                // check its browser nature in any user and generalize.
1488                                if (packageIsBrowser(packageName, firstUsers[0])) {
1489                                    synchronized (mPackages) {
1490                                        for (int userId : firstUsers) {
1491                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1492                                        }
1493                                    }
1494                                }
1495                            }
1496                            // Log current value of "unknown sources" setting
1497                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1498                                getUnknownSourcesSettings());
1499                        }
1500                        // Force a gc to clear up things
1501                        Runtime.getRuntime().gc();
1502                        // We delete after a gc for applications  on sdcard.
1503                        if (deleteOld) {
1504                            synchronized (mInstallLock) {
1505                                res.removedInfo.args.doPostDeleteLI(true);
1506                            }
1507                        }
1508                        if (args.observer != null) {
1509                            try {
1510                                Bundle extras = extrasForInstallResult(res);
1511                                args.observer.onPackageInstalled(res.name, res.returnCode,
1512                                        res.returnMsg, extras);
1513                            } catch (RemoteException e) {
1514                                Slog.i(TAG, "Observer no longer exists.");
1515                            }
1516                        }
1517                        if (args.traceMethod != null) {
1518                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1519                                    args.traceCookie);
1520                        }
1521                        return;
1522                    } else {
1523                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1524                    }
1525
1526                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1527                } break;
1528                case UPDATED_MEDIA_STATUS: {
1529                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1530                    boolean reportStatus = msg.arg1 == 1;
1531                    boolean doGc = msg.arg2 == 1;
1532                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1533                    if (doGc) {
1534                        // Force a gc to clear up stale containers.
1535                        Runtime.getRuntime().gc();
1536                    }
1537                    if (msg.obj != null) {
1538                        @SuppressWarnings("unchecked")
1539                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1540                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1541                        // Unload containers
1542                        unloadAllContainers(args);
1543                    }
1544                    if (reportStatus) {
1545                        try {
1546                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1547                            PackageHelper.getMountService().finishMediaUpdate();
1548                        } catch (RemoteException e) {
1549                            Log.e(TAG, "MountService not running?");
1550                        }
1551                    }
1552                } break;
1553                case WRITE_SETTINGS: {
1554                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1555                    synchronized (mPackages) {
1556                        removeMessages(WRITE_SETTINGS);
1557                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1558                        mSettings.writeLPr();
1559                        mDirtyUsers.clear();
1560                    }
1561                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1562                } break;
1563                case WRITE_PACKAGE_RESTRICTIONS: {
1564                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1565                    synchronized (mPackages) {
1566                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1567                        for (int userId : mDirtyUsers) {
1568                            mSettings.writePackageRestrictionsLPr(userId);
1569                        }
1570                        mDirtyUsers.clear();
1571                    }
1572                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1573                } break;
1574                case CHECK_PENDING_VERIFICATION: {
1575                    final int verificationId = msg.arg1;
1576                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1577
1578                    if ((state != null) && !state.timeoutExtended()) {
1579                        final InstallArgs args = state.getInstallArgs();
1580                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1581
1582                        Slog.i(TAG, "Verification timed out for " + originUri);
1583                        mPendingVerification.remove(verificationId);
1584
1585                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1586
1587                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1588                            Slog.i(TAG, "Continuing with installation of " + originUri);
1589                            state.setVerifierResponse(Binder.getCallingUid(),
1590                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1591                            broadcastPackageVerified(verificationId, originUri,
1592                                    PackageManager.VERIFICATION_ALLOW,
1593                                    state.getInstallArgs().getUser());
1594                            try {
1595                                ret = args.copyApk(mContainerService, true);
1596                            } catch (RemoteException e) {
1597                                Slog.e(TAG, "Could not contact the ContainerService");
1598                            }
1599                        } else {
1600                            broadcastPackageVerified(verificationId, originUri,
1601                                    PackageManager.VERIFICATION_REJECT,
1602                                    state.getInstallArgs().getUser());
1603                        }
1604
1605                        Trace.asyncTraceEnd(
1606                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1607
1608                        processPendingInstall(args, ret);
1609                        mHandler.sendEmptyMessage(MCS_UNBIND);
1610                    }
1611                    break;
1612                }
1613                case PACKAGE_VERIFIED: {
1614                    final int verificationId = msg.arg1;
1615
1616                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1617                    if (state == null) {
1618                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1619                        break;
1620                    }
1621
1622                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1623
1624                    state.setVerifierResponse(response.callerUid, response.code);
1625
1626                    if (state.isVerificationComplete()) {
1627                        mPendingVerification.remove(verificationId);
1628
1629                        final InstallArgs args = state.getInstallArgs();
1630                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1631
1632                        int ret;
1633                        if (state.isInstallAllowed()) {
1634                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1635                            broadcastPackageVerified(verificationId, originUri,
1636                                    response.code, state.getInstallArgs().getUser());
1637                            try {
1638                                ret = args.copyApk(mContainerService, true);
1639                            } catch (RemoteException e) {
1640                                Slog.e(TAG, "Could not contact the ContainerService");
1641                            }
1642                        } else {
1643                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1644                        }
1645
1646                        Trace.asyncTraceEnd(
1647                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1648
1649                        processPendingInstall(args, ret);
1650                        mHandler.sendEmptyMessage(MCS_UNBIND);
1651                    }
1652
1653                    break;
1654                }
1655                case START_INTENT_FILTER_VERIFICATIONS: {
1656                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1657                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1658                            params.replacing, params.pkg);
1659                    break;
1660                }
1661                case INTENT_FILTER_VERIFIED: {
1662                    final int verificationId = msg.arg1;
1663
1664                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1665                            verificationId);
1666                    if (state == null) {
1667                        Slog.w(TAG, "Invalid IntentFilter verification token "
1668                                + verificationId + " received");
1669                        break;
1670                    }
1671
1672                    final int userId = state.getUserId();
1673
1674                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1675                            "Processing IntentFilter verification with token:"
1676                            + verificationId + " and userId:" + userId);
1677
1678                    final IntentFilterVerificationResponse response =
1679                            (IntentFilterVerificationResponse) msg.obj;
1680
1681                    state.setVerifierResponse(response.callerUid, response.code);
1682
1683                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1684                            "IntentFilter verification with token:" + verificationId
1685                            + " and userId:" + userId
1686                            + " is settings verifier response with response code:"
1687                            + response.code);
1688
1689                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1690                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1691                                + response.getFailedDomainsString());
1692                    }
1693
1694                    if (state.isVerificationComplete()) {
1695                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1696                    } else {
1697                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1698                                "IntentFilter verification with token:" + verificationId
1699                                + " was not said to be complete");
1700                    }
1701
1702                    break;
1703                }
1704            }
1705        }
1706    }
1707
1708    private StorageEventListener mStorageListener = new StorageEventListener() {
1709        @Override
1710        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1711            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1712                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1713                    final String volumeUuid = vol.getFsUuid();
1714
1715                    // Clean up any users or apps that were removed or recreated
1716                    // while this volume was missing
1717                    reconcileUsers(volumeUuid);
1718                    reconcileApps(volumeUuid);
1719
1720                    // Clean up any install sessions that expired or were
1721                    // cancelled while this volume was missing
1722                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1723
1724                    loadPrivatePackages(vol);
1725
1726                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1727                    unloadPrivatePackages(vol);
1728                }
1729            }
1730
1731            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1732                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1733                    updateExternalMediaStatus(true, false);
1734                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1735                    updateExternalMediaStatus(false, false);
1736                }
1737            }
1738        }
1739
1740        @Override
1741        public void onVolumeForgotten(String fsUuid) {
1742            if (TextUtils.isEmpty(fsUuid)) {
1743                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1744                return;
1745            }
1746
1747            // Remove any apps installed on the forgotten volume
1748            synchronized (mPackages) {
1749                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1750                for (PackageSetting ps : packages) {
1751                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1752                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1753                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1754                }
1755
1756                mSettings.onVolumeForgotten(fsUuid);
1757                mSettings.writeLPr();
1758            }
1759        }
1760    };
1761
1762    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1763            String[] grantedPermissions) {
1764        if (userId >= UserHandle.USER_SYSTEM) {
1765            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1766        } else if (userId == UserHandle.USER_ALL) {
1767            final int[] userIds;
1768            synchronized (mPackages) {
1769                userIds = UserManagerService.getInstance().getUserIds();
1770            }
1771            for (int someUserId : userIds) {
1772                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1773            }
1774        }
1775
1776        // We could have touched GID membership, so flush out packages.list
1777        synchronized (mPackages) {
1778            mSettings.writePackageListLPr();
1779        }
1780    }
1781
1782    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1783            String[] grantedPermissions) {
1784        SettingBase sb = (SettingBase) pkg.mExtras;
1785        if (sb == null) {
1786            return;
1787        }
1788
1789        PermissionsState permissionsState = sb.getPermissionsState();
1790
1791        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1792                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1793
1794        synchronized (mPackages) {
1795            for (String permission : pkg.requestedPermissions) {
1796                BasePermission bp = mSettings.mPermissions.get(permission);
1797                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1798                        && (grantedPermissions == null
1799                               || ArrayUtils.contains(grantedPermissions, permission))) {
1800                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1801                    // Installer cannot change immutable permissions.
1802                    if ((flags & immutableFlags) == 0) {
1803                        grantRuntimePermission(pkg.packageName, permission, userId);
1804                    }
1805                }
1806            }
1807        }
1808    }
1809
1810    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1811        Bundle extras = null;
1812        switch (res.returnCode) {
1813            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1814                extras = new Bundle();
1815                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1816                        res.origPermission);
1817                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1818                        res.origPackage);
1819                break;
1820            }
1821            case PackageManager.INSTALL_SUCCEEDED: {
1822                extras = new Bundle();
1823                extras.putBoolean(Intent.EXTRA_REPLACING,
1824                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1825                break;
1826            }
1827        }
1828        return extras;
1829    }
1830
1831    void scheduleWriteSettingsLocked() {
1832        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1833            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1834        }
1835    }
1836
1837    void scheduleWritePackageRestrictionsLocked(int userId) {
1838        if (!sUserManager.exists(userId)) return;
1839        mDirtyUsers.add(userId);
1840        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1841            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1842        }
1843    }
1844
1845    public static PackageManagerService main(Context context, Installer installer,
1846            boolean factoryTest, boolean onlyCore) {
1847        PackageManagerService m = new PackageManagerService(context, installer,
1848                factoryTest, onlyCore);
1849        m.enableSystemUserPackages();
1850        ServiceManager.addService("package", m);
1851        return m;
1852    }
1853
1854    private void enableSystemUserPackages() {
1855        if (!UserManager.isSplitSystemUser()) {
1856            return;
1857        }
1858        // For system user, enable apps based on the following conditions:
1859        // - app is whitelisted or belong to one of these groups:
1860        //   -- system app which has no launcher icons
1861        //   -- system app which has INTERACT_ACROSS_USERS permission
1862        //   -- system IME app
1863        // - app is not in the blacklist
1864        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1865        Set<String> enableApps = new ArraySet<>();
1866        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1867                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1868                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1869        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1870        enableApps.addAll(wlApps);
1871        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1872                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1873        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1874        enableApps.removeAll(blApps);
1875        Log.i(TAG, "Applications installed for system user: " + enableApps);
1876        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1877                UserHandle.SYSTEM);
1878        final int allAppsSize = allAps.size();
1879        synchronized (mPackages) {
1880            for (int i = 0; i < allAppsSize; i++) {
1881                String pName = allAps.get(i);
1882                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1883                // Should not happen, but we shouldn't be failing if it does
1884                if (pkgSetting == null) {
1885                    continue;
1886                }
1887                boolean install = enableApps.contains(pName);
1888                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1889                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1890                            + " for system user");
1891                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1892                }
1893            }
1894        }
1895    }
1896
1897    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1898        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1899                Context.DISPLAY_SERVICE);
1900        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1901    }
1902
1903    public PackageManagerService(Context context, Installer installer,
1904            boolean factoryTest, boolean onlyCore) {
1905        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1906                SystemClock.uptimeMillis());
1907
1908        if (mSdkVersion <= 0) {
1909            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1910        }
1911
1912        mContext = context;
1913        mFactoryTest = factoryTest;
1914        mOnlyCore = onlyCore;
1915        mMetrics = new DisplayMetrics();
1916        mSettings = new Settings(mPackages);
1917        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1918                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1919        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1920                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1921        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1922                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1923        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1924                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1925        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1926                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1927        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1928                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1929
1930        String separateProcesses = SystemProperties.get("debug.separate_processes");
1931        if (separateProcesses != null && separateProcesses.length() > 0) {
1932            if ("*".equals(separateProcesses)) {
1933                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1934                mSeparateProcesses = null;
1935                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1936            } else {
1937                mDefParseFlags = 0;
1938                mSeparateProcesses = separateProcesses.split(",");
1939                Slog.w(TAG, "Running with debug.separate_processes: "
1940                        + separateProcesses);
1941            }
1942        } else {
1943            mDefParseFlags = 0;
1944            mSeparateProcesses = null;
1945        }
1946
1947        mInstaller = installer;
1948        mPackageDexOptimizer = new PackageDexOptimizer(this);
1949        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1950
1951        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1952                FgThread.get().getLooper());
1953
1954        getDefaultDisplayMetrics(context, mMetrics);
1955
1956        SystemConfig systemConfig = SystemConfig.getInstance();
1957        mGlobalGids = systemConfig.getGlobalGids();
1958        mSystemPermissions = systemConfig.getSystemPermissions();
1959        mAvailableFeatures = systemConfig.getAvailableFeatures();
1960
1961        synchronized (mInstallLock) {
1962        // writer
1963        synchronized (mPackages) {
1964            mHandlerThread = new ServiceThread(TAG,
1965                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1966            mHandlerThread.start();
1967            mHandler = new PackageHandler(mHandlerThread.getLooper());
1968            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1969
1970            File dataDir = Environment.getDataDirectory();
1971            mAppInstallDir = new File(dataDir, "app");
1972            mAppLib32InstallDir = new File(dataDir, "app-lib");
1973            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1974            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1975            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1976
1977            sUserManager = new UserManagerService(context, this, mPackages);
1978
1979            // Propagate permission configuration in to package manager.
1980            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1981                    = systemConfig.getPermissions();
1982            for (int i=0; i<permConfig.size(); i++) {
1983                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1984                BasePermission bp = mSettings.mPermissions.get(perm.name);
1985                if (bp == null) {
1986                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1987                    mSettings.mPermissions.put(perm.name, bp);
1988                }
1989                if (perm.gids != null) {
1990                    bp.setGids(perm.gids, perm.perUser);
1991                }
1992            }
1993
1994            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1995            for (int i=0; i<libConfig.size(); i++) {
1996                mSharedLibraries.put(libConfig.keyAt(i),
1997                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1998            }
1999
2000            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2001
2002            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2003
2004            String customResolverActivity = Resources.getSystem().getString(
2005                    R.string.config_customResolverActivity);
2006            if (TextUtils.isEmpty(customResolverActivity)) {
2007                customResolverActivity = null;
2008            } else {
2009                mCustomResolverComponentName = ComponentName.unflattenFromString(
2010                        customResolverActivity);
2011            }
2012
2013            long startTime = SystemClock.uptimeMillis();
2014
2015            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2016                    startTime);
2017
2018            // Set flag to monitor and not change apk file paths when
2019            // scanning install directories.
2020            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2021
2022            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2023            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2024
2025            if (bootClassPath == null) {
2026                Slog.w(TAG, "No BOOTCLASSPATH found!");
2027            }
2028
2029            if (systemServerClassPath == null) {
2030                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2031            }
2032
2033            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2034            final String[] dexCodeInstructionSets =
2035                    getDexCodeInstructionSets(
2036                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2037
2038            /**
2039             * Ensure all external libraries have had dexopt run on them.
2040             */
2041            if (mSharedLibraries.size() > 0) {
2042                // NOTE: For now, we're compiling these system "shared libraries"
2043                // (and framework jars) into all available architectures. It's possible
2044                // to compile them only when we come across an app that uses them (there's
2045                // already logic for that in scanPackageLI) but that adds some complexity.
2046                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2047                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2048                        final String lib = libEntry.path;
2049                        if (lib == null) {
2050                            continue;
2051                        }
2052
2053                        try {
2054                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2055                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2056                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2057                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2058                            }
2059                        } catch (FileNotFoundException e) {
2060                            Slog.w(TAG, "Library not found: " + lib);
2061                        } catch (IOException e) {
2062                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2063                                    + e.getMessage());
2064                        }
2065                    }
2066                }
2067            }
2068
2069            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2070
2071            final VersionInfo ver = mSettings.getInternalVersion();
2072            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2073            // when upgrading from pre-M, promote system app permissions from install to runtime
2074            mPromoteSystemApps =
2075                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2076
2077            // save off the names of pre-existing system packages prior to scanning; we don't
2078            // want to automatically grant runtime permissions for new system apps
2079            if (mPromoteSystemApps) {
2080                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2081                while (pkgSettingIter.hasNext()) {
2082                    PackageSetting ps = pkgSettingIter.next();
2083                    if (isSystemApp(ps)) {
2084                        mExistingSystemPackages.add(ps.name);
2085                    }
2086                }
2087            }
2088
2089            // Collect vendor overlay packages.
2090            // (Do this before scanning any apps.)
2091            // For security and version matching reason, only consider
2092            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2093            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2094            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2095                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2096
2097            // Find base frameworks (resource packages without code).
2098            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2099                    | PackageParser.PARSE_IS_SYSTEM_DIR
2100                    | PackageParser.PARSE_IS_PRIVILEGED,
2101                    scanFlags | SCAN_NO_DEX, 0);
2102
2103            // Collected privileged system packages.
2104            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2105            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2106                    | PackageParser.PARSE_IS_SYSTEM_DIR
2107                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2108
2109            // Collect ordinary system packages.
2110            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2111            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2112                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2113
2114            // Collect all vendor packages.
2115            File vendorAppDir = new File("/vendor/app");
2116            try {
2117                vendorAppDir = vendorAppDir.getCanonicalFile();
2118            } catch (IOException e) {
2119                // failed to look up canonical path, continue with original one
2120            }
2121            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2122                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2123
2124            // Collect all OEM packages.
2125            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2126            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2127                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2128
2129            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2130            mInstaller.moveFiles();
2131
2132            // Prune any system packages that no longer exist.
2133            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2134            if (!mOnlyCore) {
2135                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2136                while (psit.hasNext()) {
2137                    PackageSetting ps = psit.next();
2138
2139                    /*
2140                     * If this is not a system app, it can't be a
2141                     * disable system app.
2142                     */
2143                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2144                        continue;
2145                    }
2146
2147                    /*
2148                     * If the package is scanned, it's not erased.
2149                     */
2150                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2151                    if (scannedPkg != null) {
2152                        /*
2153                         * If the system app is both scanned and in the
2154                         * disabled packages list, then it must have been
2155                         * added via OTA. Remove it from the currently
2156                         * scanned package so the previously user-installed
2157                         * application can be scanned.
2158                         */
2159                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2160                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2161                                    + ps.name + "; removing system app.  Last known codePath="
2162                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2163                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2164                                    + scannedPkg.mVersionCode);
2165                            removePackageLI(ps, true);
2166                            mExpectingBetter.put(ps.name, ps.codePath);
2167                        }
2168
2169                        continue;
2170                    }
2171
2172                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2173                        psit.remove();
2174                        logCriticalInfo(Log.WARN, "System package " + ps.name
2175                                + " no longer exists; wiping its data");
2176                        removeDataDirsLI(null, ps.name);
2177                    } else {
2178                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2179                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2180                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2181                        }
2182                    }
2183                }
2184            }
2185
2186            //look for any incomplete package installations
2187            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2188            //clean up list
2189            for(int i = 0; i < deletePkgsList.size(); i++) {
2190                //clean up here
2191                cleanupInstallFailedPackage(deletePkgsList.get(i));
2192            }
2193            //delete tmp files
2194            deleteTempPackageFiles();
2195
2196            // Remove any shared userIDs that have no associated packages
2197            mSettings.pruneSharedUsersLPw();
2198
2199            if (!mOnlyCore) {
2200                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2201                        SystemClock.uptimeMillis());
2202                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2203
2204                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2205                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2206
2207                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2208                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2209
2210                /**
2211                 * Remove disable package settings for any updated system
2212                 * apps that were removed via an OTA. If they're not a
2213                 * previously-updated app, remove them completely.
2214                 * Otherwise, just revoke their system-level permissions.
2215                 */
2216                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2217                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2218                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2219
2220                    String msg;
2221                    if (deletedPkg == null) {
2222                        msg = "Updated system package " + deletedAppName
2223                                + " no longer exists; wiping its data";
2224                        removeDataDirsLI(null, deletedAppName);
2225                    } else {
2226                        msg = "Updated system app + " + deletedAppName
2227                                + " no longer present; removing system privileges for "
2228                                + deletedAppName;
2229
2230                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2231
2232                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2233                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2234                    }
2235                    logCriticalInfo(Log.WARN, msg);
2236                }
2237
2238                /**
2239                 * Make sure all system apps that we expected to appear on
2240                 * the userdata partition actually showed up. If they never
2241                 * appeared, crawl back and revive the system version.
2242                 */
2243                for (int i = 0; i < mExpectingBetter.size(); i++) {
2244                    final String packageName = mExpectingBetter.keyAt(i);
2245                    if (!mPackages.containsKey(packageName)) {
2246                        final File scanFile = mExpectingBetter.valueAt(i);
2247
2248                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2249                                + " but never showed up; reverting to system");
2250
2251                        final int reparseFlags;
2252                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2253                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2254                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2255                                    | PackageParser.PARSE_IS_PRIVILEGED;
2256                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2257                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2258                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2259                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2260                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2261                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2262                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2263                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2264                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2265                        } else {
2266                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2267                            continue;
2268                        }
2269
2270                        mSettings.enableSystemPackageLPw(packageName);
2271
2272                        try {
2273                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2274                        } catch (PackageManagerException e) {
2275                            Slog.e(TAG, "Failed to parse original system package: "
2276                                    + e.getMessage());
2277                        }
2278                    }
2279                }
2280            }
2281            mExpectingBetter.clear();
2282
2283            // Now that we know all of the shared libraries, update all clients to have
2284            // the correct library paths.
2285            updateAllSharedLibrariesLPw();
2286
2287            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2288                // NOTE: We ignore potential failures here during a system scan (like
2289                // the rest of the commands above) because there's precious little we
2290                // can do about it. A settings error is reported, though.
2291                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2292                        false /* boot complete */);
2293            }
2294
2295            // Now that we know all the packages we are keeping,
2296            // read and update their last usage times.
2297            mPackageUsage.readLP();
2298
2299            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2300                    SystemClock.uptimeMillis());
2301            Slog.i(TAG, "Time to scan packages: "
2302                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2303                    + " seconds");
2304
2305            // If the platform SDK has changed since the last time we booted,
2306            // we need to re-grant app permission to catch any new ones that
2307            // appear.  This is really a hack, and means that apps can in some
2308            // cases get permissions that the user didn't initially explicitly
2309            // allow...  it would be nice to have some better way to handle
2310            // this situation.
2311            int updateFlags = UPDATE_PERMISSIONS_ALL;
2312            if (ver.sdkVersion != mSdkVersion) {
2313                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2314                        + mSdkVersion + "; regranting permissions for internal storage");
2315                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2316            }
2317            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2318            ver.sdkVersion = mSdkVersion;
2319
2320            // If this is the first boot or an update from pre-M, and it is a normal
2321            // boot, then we need to initialize the default preferred apps across
2322            // all defined users.
2323            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2324                for (UserInfo user : sUserManager.getUsers(true)) {
2325                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2326                    applyFactoryDefaultBrowserLPw(user.id);
2327                    primeDomainVerificationsLPw(user.id);
2328                }
2329            }
2330
2331            // If this is first boot after an OTA, and a normal boot, then
2332            // we need to clear code cache directories.
2333            if (mIsUpgrade && !onlyCore) {
2334                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2335                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2336                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2337                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2338                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2339                    }
2340                }
2341                ver.fingerprint = Build.FINGERPRINT;
2342            }
2343
2344            checkDefaultBrowser();
2345
2346            // clear only after permissions and other defaults have been updated
2347            mExistingSystemPackages.clear();
2348            mPromoteSystemApps = false;
2349
2350            // All the changes are done during package scanning.
2351            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2352
2353            // can downgrade to reader
2354            mSettings.writeLPr();
2355
2356            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2357                    SystemClock.uptimeMillis());
2358
2359            mRequiredVerifierPackage = getRequiredVerifierLPr();
2360            mRequiredInstallerPackage = getRequiredInstallerLPr();
2361
2362            mInstallerService = new PackageInstallerService(context, this);
2363
2364            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2365            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2366                    mIntentFilterVerifierComponent);
2367
2368            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2369            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2370            // both the installer and resolver must be present to enable ephemeral
2371            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2372                if (DEBUG_EPHEMERAL) {
2373                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2374                            + " installer:" + ephemeralInstallerComponent);
2375                }
2376                mEphemeralResolverComponent = ephemeralResolverComponent;
2377                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2378                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2379                mEphemeralResolverConnection =
2380                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2381            } else {
2382                if (DEBUG_EPHEMERAL) {
2383                    final String missingComponent =
2384                            (ephemeralResolverComponent == null)
2385                            ? (ephemeralInstallerComponent == null)
2386                                    ? "resolver and installer"
2387                                    : "resolver"
2388                            : "installer";
2389                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2390                }
2391                mEphemeralResolverComponent = null;
2392                mEphemeralInstallerComponent = null;
2393                mEphemeralResolverConnection = null;
2394            }
2395
2396            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2397        } // synchronized (mPackages)
2398        } // synchronized (mInstallLock)
2399
2400        // Now after opening every single application zip, make sure they
2401        // are all flushed.  Not really needed, but keeps things nice and
2402        // tidy.
2403        Runtime.getRuntime().gc();
2404
2405        // The initial scanning above does many calls into installd while
2406        // holding the mPackages lock, but we're mostly interested in yelling
2407        // once we have a booted system.
2408        mInstaller.setWarnIfHeld(mPackages);
2409
2410        // Expose private service for system components to use.
2411        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2412    }
2413
2414    @Override
2415    public boolean isFirstBoot() {
2416        return !mRestoredSettings;
2417    }
2418
2419    @Override
2420    public boolean isOnlyCoreApps() {
2421        return mOnlyCore;
2422    }
2423
2424    @Override
2425    public boolean isUpgrade() {
2426        return mIsUpgrade;
2427    }
2428
2429    private String getRequiredVerifierLPr() {
2430        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2431        // We only care about verifier that's installed under system user.
2432        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2433                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2434
2435        String requiredVerifier = null;
2436
2437        final int N = receivers.size();
2438        for (int i = 0; i < N; i++) {
2439            final ResolveInfo info = receivers.get(i);
2440
2441            if (info.activityInfo == null) {
2442                continue;
2443            }
2444
2445            final String packageName = info.activityInfo.packageName;
2446
2447            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2448                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2449                continue;
2450            }
2451
2452            if (requiredVerifier != null) {
2453                throw new RuntimeException("There can be only one required verifier");
2454            }
2455
2456            requiredVerifier = packageName;
2457        }
2458
2459        return requiredVerifier;
2460    }
2461
2462    private String getRequiredInstallerLPr() {
2463        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2464        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2465        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2466
2467        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2468                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2469
2470        String requiredInstaller = null;
2471
2472        final int N = installers.size();
2473        for (int i = 0; i < N; i++) {
2474            final ResolveInfo info = installers.get(i);
2475            final String packageName = info.activityInfo.packageName;
2476
2477            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2478                continue;
2479            }
2480
2481            if (requiredInstaller != null) {
2482                throw new RuntimeException("There must be one required installer");
2483            }
2484
2485            requiredInstaller = packageName;
2486        }
2487
2488        if (requiredInstaller == null) {
2489            throw new RuntimeException("There must be one required installer");
2490        }
2491
2492        return requiredInstaller;
2493    }
2494
2495    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2496        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2497        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2498                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2499
2500        ComponentName verifierComponentName = null;
2501
2502        int priority = -1000;
2503        final int N = receivers.size();
2504        for (int i = 0; i < N; i++) {
2505            final ResolveInfo info = receivers.get(i);
2506
2507            if (info.activityInfo == null) {
2508                continue;
2509            }
2510
2511            final String packageName = info.activityInfo.packageName;
2512
2513            final PackageSetting ps = mSettings.mPackages.get(packageName);
2514            if (ps == null) {
2515                continue;
2516            }
2517
2518            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2519                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2520                continue;
2521            }
2522
2523            // Select the IntentFilterVerifier with the highest priority
2524            if (priority < info.priority) {
2525                priority = info.priority;
2526                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2527                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2528                        + verifierComponentName + " with priority: " + info.priority);
2529            }
2530        }
2531
2532        return verifierComponentName;
2533    }
2534
2535    private ComponentName getEphemeralResolverLPr() {
2536        final String[] packageArray =
2537                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2538        if (packageArray.length == 0) {
2539            if (DEBUG_EPHEMERAL) {
2540                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2541            }
2542            return null;
2543        }
2544
2545        Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2546        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent,
2547                null /*resolvedType*/, 0 /*flags*/, UserHandle.USER_SYSTEM);
2548
2549        final int N = resolvers.size();
2550        if (N == 0) {
2551            if (DEBUG_EPHEMERAL) {
2552                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2553            }
2554            return null;
2555        }
2556
2557        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2558        for (int i = 0; i < N; i++) {
2559            final ResolveInfo info = resolvers.get(i);
2560
2561            if (info.serviceInfo == null) {
2562                continue;
2563            }
2564
2565            final String packageName = info.serviceInfo.packageName;
2566            if (!possiblePackages.contains(packageName)) {
2567                if (DEBUG_EPHEMERAL) {
2568                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2569                            + " pkg: " + packageName + ", info:" + info);
2570                }
2571                continue;
2572            }
2573
2574            if (DEBUG_EPHEMERAL) {
2575                Slog.v(TAG, "Ephemeral resolver found;"
2576                        + " pkg: " + packageName + ", info:" + info);
2577            }
2578            return new ComponentName(packageName, info.serviceInfo.name);
2579        }
2580        if (DEBUG_EPHEMERAL) {
2581            Slog.v(TAG, "Ephemeral resolver NOT found");
2582        }
2583        return null;
2584    }
2585
2586    private ComponentName getEphemeralInstallerLPr() {
2587        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2588        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2589        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2590        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2591                PACKAGE_MIME_TYPE, 0 /*flags*/, 0 /*userId*/);
2592
2593        ComponentName ephemeralInstaller = null;
2594
2595        final int N = installers.size();
2596        for (int i = 0; i < N; i++) {
2597            final ResolveInfo info = installers.get(i);
2598            final String packageName = info.activityInfo.packageName;
2599
2600            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2601                if (DEBUG_EPHEMERAL) {
2602                    Slog.d(TAG, "Ephemeral installer is not system app;"
2603                            + " pkg: " + packageName + ", info:" + info);
2604                }
2605                continue;
2606            }
2607
2608            if (ephemeralInstaller != null) {
2609                throw new RuntimeException("There must only be one ephemeral installer");
2610            }
2611
2612            ephemeralInstaller = new ComponentName(packageName, info.activityInfo.name);
2613        }
2614
2615        return ephemeralInstaller;
2616    }
2617
2618    private void primeDomainVerificationsLPw(int userId) {
2619        if (DEBUG_DOMAIN_VERIFICATION) {
2620            Slog.d(TAG, "Priming domain verifications in user " + userId);
2621        }
2622
2623        SystemConfig systemConfig = SystemConfig.getInstance();
2624        ArraySet<String> packages = systemConfig.getLinkedApps();
2625        ArraySet<String> domains = new ArraySet<String>();
2626
2627        for (String packageName : packages) {
2628            PackageParser.Package pkg = mPackages.get(packageName);
2629            if (pkg != null) {
2630                if (!pkg.isSystemApp()) {
2631                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2632                    continue;
2633                }
2634
2635                domains.clear();
2636                for (PackageParser.Activity a : pkg.activities) {
2637                    for (ActivityIntentInfo filter : a.intents) {
2638                        if (hasValidDomains(filter)) {
2639                            domains.addAll(filter.getHostsList());
2640                        }
2641                    }
2642                }
2643
2644                if (domains.size() > 0) {
2645                    if (DEBUG_DOMAIN_VERIFICATION) {
2646                        Slog.v(TAG, "      + " + packageName);
2647                    }
2648                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2649                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2650                    // and then 'always' in the per-user state actually used for intent resolution.
2651                    final IntentFilterVerificationInfo ivi;
2652                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2653                            new ArrayList<String>(domains));
2654                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2655                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2656                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2657                } else {
2658                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2659                            + "' does not handle web links");
2660                }
2661            } else {
2662                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2663            }
2664        }
2665
2666        scheduleWritePackageRestrictionsLocked(userId);
2667        scheduleWriteSettingsLocked();
2668    }
2669
2670    private void applyFactoryDefaultBrowserLPw(int userId) {
2671        // The default browser app's package name is stored in a string resource,
2672        // with a product-specific overlay used for vendor customization.
2673        String browserPkg = mContext.getResources().getString(
2674                com.android.internal.R.string.default_browser);
2675        if (!TextUtils.isEmpty(browserPkg)) {
2676            // non-empty string => required to be a known package
2677            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2678            if (ps == null) {
2679                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2680                browserPkg = null;
2681            } else {
2682                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2683            }
2684        }
2685
2686        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2687        // default.  If there's more than one, just leave everything alone.
2688        if (browserPkg == null) {
2689            calculateDefaultBrowserLPw(userId);
2690        }
2691    }
2692
2693    private void calculateDefaultBrowserLPw(int userId) {
2694        List<String> allBrowsers = resolveAllBrowserApps(userId);
2695        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2696        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2697    }
2698
2699    private List<String> resolveAllBrowserApps(int userId) {
2700        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2701        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2702                PackageManager.MATCH_ALL, userId);
2703
2704        final int count = list.size();
2705        List<String> result = new ArrayList<String>(count);
2706        for (int i=0; i<count; i++) {
2707            ResolveInfo info = list.get(i);
2708            if (info.activityInfo == null
2709                    || !info.handleAllWebDataURI
2710                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2711                    || result.contains(info.activityInfo.packageName)) {
2712                continue;
2713            }
2714            result.add(info.activityInfo.packageName);
2715        }
2716
2717        return result;
2718    }
2719
2720    private boolean packageIsBrowser(String packageName, int userId) {
2721        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2722                PackageManager.MATCH_ALL, userId);
2723        final int N = list.size();
2724        for (int i = 0; i < N; i++) {
2725            ResolveInfo info = list.get(i);
2726            if (packageName.equals(info.activityInfo.packageName)) {
2727                return true;
2728            }
2729        }
2730        return false;
2731    }
2732
2733    private void checkDefaultBrowser() {
2734        final int myUserId = UserHandle.myUserId();
2735        final String packageName = getDefaultBrowserPackageName(myUserId);
2736        if (packageName != null) {
2737            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2738            if (info == null) {
2739                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2740                synchronized (mPackages) {
2741                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2742                }
2743            }
2744        }
2745    }
2746
2747    @Override
2748    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2749            throws RemoteException {
2750        try {
2751            return super.onTransact(code, data, reply, flags);
2752        } catch (RuntimeException e) {
2753            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2754                Slog.wtf(TAG, "Package Manager Crash", e);
2755            }
2756            throw e;
2757        }
2758    }
2759
2760    void cleanupInstallFailedPackage(PackageSetting ps) {
2761        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2762
2763        removeDataDirsLI(ps.volumeUuid, ps.name);
2764        if (ps.codePath != null) {
2765            if (ps.codePath.isDirectory()) {
2766                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2767            } else {
2768                ps.codePath.delete();
2769            }
2770        }
2771        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2772            if (ps.resourcePath.isDirectory()) {
2773                FileUtils.deleteContents(ps.resourcePath);
2774            }
2775            ps.resourcePath.delete();
2776        }
2777        mSettings.removePackageLPw(ps.name);
2778    }
2779
2780    static int[] appendInts(int[] cur, int[] add) {
2781        if (add == null) return cur;
2782        if (cur == null) return add;
2783        final int N = add.length;
2784        for (int i=0; i<N; i++) {
2785            cur = appendInt(cur, add[i]);
2786        }
2787        return cur;
2788    }
2789
2790    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2791        if (!sUserManager.exists(userId)) return null;
2792        final PackageSetting ps = (PackageSetting) p.mExtras;
2793        if (ps == null) {
2794            return null;
2795        }
2796
2797        final PermissionsState permissionsState = ps.getPermissionsState();
2798
2799        final int[] gids = permissionsState.computeGids(userId);
2800        final Set<String> permissions = permissionsState.getPermissions(userId);
2801        final PackageUserState state = ps.readUserState(userId);
2802
2803        return PackageParser.generatePackageInfo(p, gids, flags,
2804                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2805    }
2806
2807    @Override
2808    public void checkPackageStartable(String packageName, int userId) {
2809        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2810
2811        synchronized (mPackages) {
2812            final PackageSetting ps = mSettings.mPackages.get(packageName);
2813            if (ps == null) {
2814                throw new SecurityException("Package " + packageName + " was not found!");
2815            }
2816
2817            if (ps.frozen) {
2818                throw new SecurityException("Package " + packageName + " is currently frozen!");
2819            }
2820
2821            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2822                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2823                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2824            }
2825        }
2826    }
2827
2828    @Override
2829    public boolean isPackageAvailable(String packageName, int userId) {
2830        if (!sUserManager.exists(userId)) return false;
2831        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2832        synchronized (mPackages) {
2833            PackageParser.Package p = mPackages.get(packageName);
2834            if (p != null) {
2835                final PackageSetting ps = (PackageSetting) p.mExtras;
2836                if (ps != null) {
2837                    final PackageUserState state = ps.readUserState(userId);
2838                    if (state != null) {
2839                        return PackageParser.isAvailable(state);
2840                    }
2841                }
2842            }
2843        }
2844        return false;
2845    }
2846
2847    @Override
2848    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2849        if (!sUserManager.exists(userId)) return null;
2850        flags = updateFlagsForPackage(flags, userId, packageName);
2851        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2852        // reader
2853        synchronized (mPackages) {
2854            PackageParser.Package p = mPackages.get(packageName);
2855            if (DEBUG_PACKAGE_INFO)
2856                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2857            if (p != null) {
2858                return generatePackageInfo(p, flags, userId);
2859            }
2860            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2861                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2862            }
2863        }
2864        return null;
2865    }
2866
2867    @Override
2868    public String[] currentToCanonicalPackageNames(String[] names) {
2869        String[] out = new String[names.length];
2870        // reader
2871        synchronized (mPackages) {
2872            for (int i=names.length-1; i>=0; i--) {
2873                PackageSetting ps = mSettings.mPackages.get(names[i]);
2874                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2875            }
2876        }
2877        return out;
2878    }
2879
2880    @Override
2881    public String[] canonicalToCurrentPackageNames(String[] names) {
2882        String[] out = new String[names.length];
2883        // reader
2884        synchronized (mPackages) {
2885            for (int i=names.length-1; i>=0; i--) {
2886                String cur = mSettings.mRenamedPackages.get(names[i]);
2887                out[i] = cur != null ? cur : names[i];
2888            }
2889        }
2890        return out;
2891    }
2892
2893    @Override
2894    public int getPackageUid(String packageName, int userId) {
2895        return getPackageUidEtc(packageName, 0, userId);
2896    }
2897
2898    @Override
2899    public int getPackageUidEtc(String packageName, int flags, int userId) {
2900        if (!sUserManager.exists(userId)) return -1;
2901        flags = updateFlagsForPackage(flags, userId, packageName);
2902        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2903
2904        // reader
2905        synchronized (mPackages) {
2906            final PackageParser.Package p = mPackages.get(packageName);
2907            if (p != null) {
2908                return UserHandle.getUid(userId, p.applicationInfo.uid);
2909            }
2910            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2911                final PackageSetting ps = mSettings.mPackages.get(packageName);
2912                if (ps != null) {
2913                    return UserHandle.getUid(userId, ps.appId);
2914                }
2915            }
2916        }
2917
2918        return -1;
2919    }
2920
2921    @Override
2922    public int[] getPackageGids(String packageName, int userId) {
2923        return getPackageGidsEtc(packageName, 0, userId);
2924    }
2925
2926    @Override
2927    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2928        if (!sUserManager.exists(userId)) return null;
2929        flags = updateFlagsForPackage(flags, userId, packageName);
2930        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2931                "getPackageGids");
2932
2933        // reader
2934        synchronized (mPackages) {
2935            final PackageParser.Package p = mPackages.get(packageName);
2936            if (p != null) {
2937                PackageSetting ps = (PackageSetting) p.mExtras;
2938                return ps.getPermissionsState().computeGids(userId);
2939            }
2940            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2941                final PackageSetting ps = mSettings.mPackages.get(packageName);
2942                if (ps != null) {
2943                    return ps.getPermissionsState().computeGids(userId);
2944                }
2945            }
2946        }
2947
2948        return null;
2949    }
2950
2951    static PermissionInfo generatePermissionInfo(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        flags = updateFlagsForApplication(flags, userId, packageName);
3070        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3071        // writer
3072        synchronized (mPackages) {
3073            PackageParser.Package p = mPackages.get(packageName);
3074            if (DEBUG_PACKAGE_INFO) Log.v(
3075                    TAG, "getApplicationInfo " + packageName
3076                    + ": " + p);
3077            if (p != null) {
3078                PackageSetting ps = mSettings.mPackages.get(packageName);
3079                if (ps == null) return null;
3080                // Note: isEnabledLP() does not apply here - always return info
3081                return PackageParser.generateApplicationInfo(
3082                        p, flags, ps.readUserState(userId), userId);
3083            }
3084            if ("android".equals(packageName)||"system".equals(packageName)) {
3085                return mAndroidApplication;
3086            }
3087            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
3088                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3089            }
3090        }
3091        return null;
3092    }
3093
3094    @Override
3095    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3096            final IPackageDataObserver observer) {
3097        mContext.enforceCallingOrSelfPermission(
3098                android.Manifest.permission.CLEAR_APP_CACHE, null);
3099        // Queue up an async operation since clearing cache may take a little while.
3100        mHandler.post(new Runnable() {
3101            public void run() {
3102                mHandler.removeCallbacks(this);
3103                int retCode = -1;
3104                synchronized (mInstallLock) {
3105                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3106                    if (retCode < 0) {
3107                        Slog.w(TAG, "Couldn't clear application caches");
3108                    }
3109                }
3110                if (observer != null) {
3111                    try {
3112                        observer.onRemoveCompleted(null, (retCode >= 0));
3113                    } catch (RemoteException e) {
3114                        Slog.w(TAG, "RemoveException when invoking call back");
3115                    }
3116                }
3117            }
3118        });
3119    }
3120
3121    @Override
3122    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3123            final IntentSender pi) {
3124        mContext.enforceCallingOrSelfPermission(
3125                android.Manifest.permission.CLEAR_APP_CACHE, null);
3126        // Queue up an async operation since clearing cache may take a little while.
3127        mHandler.post(new Runnable() {
3128            public void run() {
3129                mHandler.removeCallbacks(this);
3130                int retCode = -1;
3131                synchronized (mInstallLock) {
3132                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3133                    if (retCode < 0) {
3134                        Slog.w(TAG, "Couldn't clear application caches");
3135                    }
3136                }
3137                if(pi != null) {
3138                    try {
3139                        // Callback via pending intent
3140                        int code = (retCode >= 0) ? 1 : 0;
3141                        pi.sendIntent(null, code, null,
3142                                null, null);
3143                    } catch (SendIntentException e1) {
3144                        Slog.i(TAG, "Failed to send pending intent");
3145                    }
3146                }
3147            }
3148        });
3149    }
3150
3151    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3152        synchronized (mInstallLock) {
3153            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3154                throw new IOException("Failed to free enough space");
3155            }
3156        }
3157    }
3158
3159    /**
3160     * Return if the user key is currently unlocked.
3161     */
3162    private boolean isUserKeyUnlocked(int userId) {
3163        if (StorageManager.isFileBasedEncryptionEnabled()) {
3164            final IMountService mount = IMountService.Stub
3165                    .asInterface(ServiceManager.getService("mount"));
3166            if (mount == null) {
3167                Slog.w(TAG, "Early during boot, assuming locked");
3168                return false;
3169            }
3170            final long token = Binder.clearCallingIdentity();
3171            try {
3172                return mount.isUserKeyUnlocked(userId);
3173            } catch (RemoteException e) {
3174                throw e.rethrowAsRuntimeException();
3175            } finally {
3176                Binder.restoreCallingIdentity(token);
3177            }
3178        } else {
3179            return true;
3180        }
3181    }
3182
3183    /**
3184     * Update given flags based on encryption status of current user.
3185     */
3186    private int updateFlagsForEncryption(int flags, int userId) {
3187        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3188                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3189            // Caller expressed an explicit opinion about what encryption
3190            // aware/unaware components they want to see, so fall through and
3191            // give them what they want
3192        } else {
3193            // Caller expressed no opinion, so match based on user state
3194            if (isUserKeyUnlocked(userId)) {
3195                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3196            } else {
3197                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3198            }
3199        }
3200        return flags;
3201    }
3202
3203    /**
3204     * Update given flags when being used to request {@link PackageInfo}.
3205     */
3206    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3207        boolean triaged = true;
3208        if ((flags & PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3209                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS) != 0) {
3210            // Caller is asking for component details, so they'd better be
3211            // asking for specific encryption matching behavior, or be triaged
3212            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3213                    | PackageManager.MATCH_ENCRYPTION_AWARE
3214                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3215                triaged = false;
3216            }
3217        }
3218        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3219                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3220            triaged = false;
3221        }
3222        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3223            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie,
3224                    new Throwable());
3225        }
3226        return updateFlagsForEncryption(flags, userId);
3227    }
3228
3229    /**
3230     * Update given flags when being used to request {@link ApplicationInfo}.
3231     */
3232    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3233        return updateFlagsForPackage(flags, userId, cookie);
3234    }
3235
3236    /**
3237     * Update given flags when being used to request {@link ComponentInfo}.
3238     */
3239    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3240        boolean triaged = true;
3241        // Caller is asking for component details, so they'd better be
3242        // asking for specific encryption matching behavior, or be triaged
3243        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3244                | PackageManager.MATCH_ENCRYPTION_AWARE
3245                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3246            triaged = false;
3247        }
3248        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3249            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie,
3250                    new Throwable());
3251        }
3252        return updateFlagsForEncryption(flags, userId);
3253    }
3254
3255    /**
3256     * Update given flags when being used to request {@link ResolveInfo}.
3257     */
3258    private int updateFlagsForResolve(int flags, int userId, Object cookie) {
3259        return updateFlagsForComponent(flags, userId, cookie);
3260    }
3261
3262    @Override
3263    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3264        if (!sUserManager.exists(userId)) return null;
3265        flags = updateFlagsForComponent(flags, userId, component);
3266        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3267        synchronized (mPackages) {
3268            PackageParser.Activity a = mActivities.mActivities.get(component);
3269
3270            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3271            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3272                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3273                if (ps == null) return null;
3274                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3275                        userId);
3276            }
3277            if (mResolveComponentName.equals(component)) {
3278                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3279                        new PackageUserState(), userId);
3280            }
3281        }
3282        return null;
3283    }
3284
3285    @Override
3286    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3287            String resolvedType) {
3288        synchronized (mPackages) {
3289            if (component.equals(mResolveComponentName)) {
3290                // The resolver supports EVERYTHING!
3291                return true;
3292            }
3293            PackageParser.Activity a = mActivities.mActivities.get(component);
3294            if (a == null) {
3295                return false;
3296            }
3297            for (int i=0; i<a.intents.size(); i++) {
3298                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3299                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3300                    return true;
3301                }
3302            }
3303            return false;
3304        }
3305    }
3306
3307    @Override
3308    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3309        if (!sUserManager.exists(userId)) return null;
3310        flags = updateFlagsForComponent(flags, userId, component);
3311        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3312        synchronized (mPackages) {
3313            PackageParser.Activity a = mReceivers.mActivities.get(component);
3314            if (DEBUG_PACKAGE_INFO) Log.v(
3315                TAG, "getReceiverInfo " + component + ": " + a);
3316            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3317                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3318                if (ps == null) return null;
3319                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3320                        userId);
3321            }
3322        }
3323        return null;
3324    }
3325
3326    @Override
3327    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3328        if (!sUserManager.exists(userId)) return null;
3329        flags = updateFlagsForComponent(flags, userId, component);
3330        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3331        synchronized (mPackages) {
3332            PackageParser.Service s = mServices.mServices.get(component);
3333            if (DEBUG_PACKAGE_INFO) Log.v(
3334                TAG, "getServiceInfo " + component + ": " + s);
3335            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3336                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3337                if (ps == null) return null;
3338                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3339                        userId);
3340            }
3341        }
3342        return null;
3343    }
3344
3345    @Override
3346    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3347        if (!sUserManager.exists(userId)) return null;
3348        flags = updateFlagsForComponent(flags, userId, component);
3349        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3350        synchronized (mPackages) {
3351            PackageParser.Provider p = mProviders.mProviders.get(component);
3352            if (DEBUG_PACKAGE_INFO) Log.v(
3353                TAG, "getProviderInfo " + component + ": " + p);
3354            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3355                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3356                if (ps == null) return null;
3357                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3358                        userId);
3359            }
3360        }
3361        return null;
3362    }
3363
3364    @Override
3365    public String[] getSystemSharedLibraryNames() {
3366        Set<String> libSet;
3367        synchronized (mPackages) {
3368            libSet = mSharedLibraries.keySet();
3369            int size = libSet.size();
3370            if (size > 0) {
3371                String[] libs = new String[size];
3372                libSet.toArray(libs);
3373                return libs;
3374            }
3375        }
3376        return null;
3377    }
3378
3379    /**
3380     * @hide
3381     */
3382    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3383        synchronized (mPackages) {
3384            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3385            if (lib != null && lib.apk != null) {
3386                return mPackages.get(lib.apk);
3387            }
3388        }
3389        return null;
3390    }
3391
3392    @Override
3393    public FeatureInfo[] getSystemAvailableFeatures() {
3394        Collection<FeatureInfo> featSet;
3395        synchronized (mPackages) {
3396            featSet = mAvailableFeatures.values();
3397            int size = featSet.size();
3398            if (size > 0) {
3399                FeatureInfo[] features = new FeatureInfo[size+1];
3400                featSet.toArray(features);
3401                FeatureInfo fi = new FeatureInfo();
3402                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3403                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3404                features[size] = fi;
3405                return features;
3406            }
3407        }
3408        return null;
3409    }
3410
3411    @Override
3412    public boolean hasSystemFeature(String name) {
3413        synchronized (mPackages) {
3414            return mAvailableFeatures.containsKey(name);
3415        }
3416    }
3417
3418    @Override
3419    public int checkPermission(String permName, String pkgName, int userId) {
3420        if (!sUserManager.exists(userId)) {
3421            return PackageManager.PERMISSION_DENIED;
3422        }
3423
3424        synchronized (mPackages) {
3425            final PackageParser.Package p = mPackages.get(pkgName);
3426            if (p != null && p.mExtras != null) {
3427                final PackageSetting ps = (PackageSetting) p.mExtras;
3428                final PermissionsState permissionsState = ps.getPermissionsState();
3429                if (permissionsState.hasPermission(permName, userId)) {
3430                    return PackageManager.PERMISSION_GRANTED;
3431                }
3432                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3433                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3434                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3435                    return PackageManager.PERMISSION_GRANTED;
3436                }
3437            }
3438        }
3439
3440        return PackageManager.PERMISSION_DENIED;
3441    }
3442
3443    @Override
3444    public int checkUidPermission(String permName, int uid) {
3445        final int userId = UserHandle.getUserId(uid);
3446
3447        if (!sUserManager.exists(userId)) {
3448            return PackageManager.PERMISSION_DENIED;
3449        }
3450
3451        synchronized (mPackages) {
3452            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3453            if (obj != null) {
3454                final SettingBase ps = (SettingBase) obj;
3455                final PermissionsState permissionsState = ps.getPermissionsState();
3456                if (permissionsState.hasPermission(permName, userId)) {
3457                    return PackageManager.PERMISSION_GRANTED;
3458                }
3459                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3460                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3461                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3462                    return PackageManager.PERMISSION_GRANTED;
3463                }
3464            } else {
3465                ArraySet<String> perms = mSystemPermissions.get(uid);
3466                if (perms != null) {
3467                    if (perms.contains(permName)) {
3468                        return PackageManager.PERMISSION_GRANTED;
3469                    }
3470                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3471                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3472                        return PackageManager.PERMISSION_GRANTED;
3473                    }
3474                }
3475            }
3476        }
3477
3478        return PackageManager.PERMISSION_DENIED;
3479    }
3480
3481    @Override
3482    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3483        if (UserHandle.getCallingUserId() != userId) {
3484            mContext.enforceCallingPermission(
3485                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3486                    "isPermissionRevokedByPolicy for user " + userId);
3487        }
3488
3489        if (checkPermission(permission, packageName, userId)
3490                == PackageManager.PERMISSION_GRANTED) {
3491            return false;
3492        }
3493
3494        final long identity = Binder.clearCallingIdentity();
3495        try {
3496            final int flags = getPermissionFlags(permission, packageName, userId);
3497            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3498        } finally {
3499            Binder.restoreCallingIdentity(identity);
3500        }
3501    }
3502
3503    @Override
3504    public String getPermissionControllerPackageName() {
3505        synchronized (mPackages) {
3506            return mRequiredInstallerPackage;
3507        }
3508    }
3509
3510    /**
3511     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3512     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3513     * @param checkShell TODO(yamasani):
3514     * @param message the message to log on security exception
3515     */
3516    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3517            boolean checkShell, String message) {
3518        if (userId < 0) {
3519            throw new IllegalArgumentException("Invalid userId " + userId);
3520        }
3521        if (checkShell) {
3522            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3523        }
3524        if (userId == UserHandle.getUserId(callingUid)) return;
3525        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3526            if (requireFullPermission) {
3527                mContext.enforceCallingOrSelfPermission(
3528                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3529            } else {
3530                try {
3531                    mContext.enforceCallingOrSelfPermission(
3532                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3533                } catch (SecurityException se) {
3534                    mContext.enforceCallingOrSelfPermission(
3535                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3536                }
3537            }
3538        }
3539    }
3540
3541    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3542        if (callingUid == Process.SHELL_UID) {
3543            if (userHandle >= 0
3544                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3545                throw new SecurityException("Shell does not have permission to access user "
3546                        + userHandle);
3547            } else if (userHandle < 0) {
3548                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3549                        + Debug.getCallers(3));
3550            }
3551        }
3552    }
3553
3554    private BasePermission findPermissionTreeLP(String permName) {
3555        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3556            if (permName.startsWith(bp.name) &&
3557                    permName.length() > bp.name.length() &&
3558                    permName.charAt(bp.name.length()) == '.') {
3559                return bp;
3560            }
3561        }
3562        return null;
3563    }
3564
3565    private BasePermission checkPermissionTreeLP(String permName) {
3566        if (permName != null) {
3567            BasePermission bp = findPermissionTreeLP(permName);
3568            if (bp != null) {
3569                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3570                    return bp;
3571                }
3572                throw new SecurityException("Calling uid "
3573                        + Binder.getCallingUid()
3574                        + " is not allowed to add to permission tree "
3575                        + bp.name + " owned by uid " + bp.uid);
3576            }
3577        }
3578        throw new SecurityException("No permission tree found for " + permName);
3579    }
3580
3581    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3582        if (s1 == null) {
3583            return s2 == null;
3584        }
3585        if (s2 == null) {
3586            return false;
3587        }
3588        if (s1.getClass() != s2.getClass()) {
3589            return false;
3590        }
3591        return s1.equals(s2);
3592    }
3593
3594    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3595        if (pi1.icon != pi2.icon) return false;
3596        if (pi1.logo != pi2.logo) return false;
3597        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3598        if (!compareStrings(pi1.name, pi2.name)) return false;
3599        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3600        // We'll take care of setting this one.
3601        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3602        // These are not currently stored in settings.
3603        //if (!compareStrings(pi1.group, pi2.group)) return false;
3604        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3605        //if (pi1.labelRes != pi2.labelRes) return false;
3606        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3607        return true;
3608    }
3609
3610    int permissionInfoFootprint(PermissionInfo info) {
3611        int size = info.name.length();
3612        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3613        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3614        return size;
3615    }
3616
3617    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3618        int size = 0;
3619        for (BasePermission perm : mSettings.mPermissions.values()) {
3620            if (perm.uid == tree.uid) {
3621                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3622            }
3623        }
3624        return size;
3625    }
3626
3627    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3628        // We calculate the max size of permissions defined by this uid and throw
3629        // if that plus the size of 'info' would exceed our stated maximum.
3630        if (tree.uid != Process.SYSTEM_UID) {
3631            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3632            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3633                throw new SecurityException("Permission tree size cap exceeded");
3634            }
3635        }
3636    }
3637
3638    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3639        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3640            throw new SecurityException("Label must be specified in permission");
3641        }
3642        BasePermission tree = checkPermissionTreeLP(info.name);
3643        BasePermission bp = mSettings.mPermissions.get(info.name);
3644        boolean added = bp == null;
3645        boolean changed = true;
3646        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3647        if (added) {
3648            enforcePermissionCapLocked(info, tree);
3649            bp = new BasePermission(info.name, tree.sourcePackage,
3650                    BasePermission.TYPE_DYNAMIC);
3651        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3652            throw new SecurityException(
3653                    "Not allowed to modify non-dynamic permission "
3654                    + info.name);
3655        } else {
3656            if (bp.protectionLevel == fixedLevel
3657                    && bp.perm.owner.equals(tree.perm.owner)
3658                    && bp.uid == tree.uid
3659                    && comparePermissionInfos(bp.perm.info, info)) {
3660                changed = false;
3661            }
3662        }
3663        bp.protectionLevel = fixedLevel;
3664        info = new PermissionInfo(info);
3665        info.protectionLevel = fixedLevel;
3666        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3667        bp.perm.info.packageName = tree.perm.info.packageName;
3668        bp.uid = tree.uid;
3669        if (added) {
3670            mSettings.mPermissions.put(info.name, bp);
3671        }
3672        if (changed) {
3673            if (!async) {
3674                mSettings.writeLPr();
3675            } else {
3676                scheduleWriteSettingsLocked();
3677            }
3678        }
3679        return added;
3680    }
3681
3682    @Override
3683    public boolean addPermission(PermissionInfo info) {
3684        synchronized (mPackages) {
3685            return addPermissionLocked(info, false);
3686        }
3687    }
3688
3689    @Override
3690    public boolean addPermissionAsync(PermissionInfo info) {
3691        synchronized (mPackages) {
3692            return addPermissionLocked(info, true);
3693        }
3694    }
3695
3696    @Override
3697    public void removePermission(String name) {
3698        synchronized (mPackages) {
3699            checkPermissionTreeLP(name);
3700            BasePermission bp = mSettings.mPermissions.get(name);
3701            if (bp != null) {
3702                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3703                    throw new SecurityException(
3704                            "Not allowed to modify non-dynamic permission "
3705                            + name);
3706                }
3707                mSettings.mPermissions.remove(name);
3708                mSettings.writeLPr();
3709            }
3710        }
3711    }
3712
3713    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3714            BasePermission bp) {
3715        int index = pkg.requestedPermissions.indexOf(bp.name);
3716        if (index == -1) {
3717            throw new SecurityException("Package " + pkg.packageName
3718                    + " has not requested permission " + bp.name);
3719        }
3720        if (!bp.isRuntime() && !bp.isDevelopment()) {
3721            throw new SecurityException("Permission " + bp.name
3722                    + " is not a changeable permission type");
3723        }
3724    }
3725
3726    @Override
3727    public void grantRuntimePermission(String packageName, String name, final int userId) {
3728        if (!sUserManager.exists(userId)) {
3729            Log.e(TAG, "No such user:" + userId);
3730            return;
3731        }
3732
3733        mContext.enforceCallingOrSelfPermission(
3734                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3735                "grantRuntimePermission");
3736
3737        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3738                "grantRuntimePermission");
3739
3740        final int uid;
3741        final SettingBase sb;
3742
3743        synchronized (mPackages) {
3744            final PackageParser.Package pkg = mPackages.get(packageName);
3745            if (pkg == null) {
3746                throw new IllegalArgumentException("Unknown package: " + packageName);
3747            }
3748
3749            final BasePermission bp = mSettings.mPermissions.get(name);
3750            if (bp == null) {
3751                throw new IllegalArgumentException("Unknown permission: " + name);
3752            }
3753
3754            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3755
3756            // If a permission review is required for legacy apps we represent
3757            // their permissions as always granted runtime ones since we need
3758            // to keep the review required permission flag per user while an
3759            // install permission's state is shared across all users.
3760            if (Build.PERMISSIONS_REVIEW_REQUIRED
3761                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3762                    && bp.isRuntime()) {
3763                return;
3764            }
3765
3766            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3767            sb = (SettingBase) pkg.mExtras;
3768            if (sb == null) {
3769                throw new IllegalArgumentException("Unknown package: " + packageName);
3770            }
3771
3772            final PermissionsState permissionsState = sb.getPermissionsState();
3773
3774            final int flags = permissionsState.getPermissionFlags(name, userId);
3775            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3776                throw new SecurityException("Cannot grant system fixed permission: "
3777                        + name + " for package: " + packageName);
3778            }
3779
3780            if (bp.isDevelopment()) {
3781                // Development permissions must be handled specially, since they are not
3782                // normal runtime permissions.  For now they apply to all users.
3783                if (permissionsState.grantInstallPermission(bp) !=
3784                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3785                    scheduleWriteSettingsLocked();
3786                }
3787                return;
3788            }
3789
3790            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3791                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3792                return;
3793            }
3794
3795            final int result = permissionsState.grantRuntimePermission(bp, userId);
3796            switch (result) {
3797                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3798                    return;
3799                }
3800
3801                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3802                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3803                    mHandler.post(new Runnable() {
3804                        @Override
3805                        public void run() {
3806                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3807                        }
3808                    });
3809                }
3810                break;
3811            }
3812
3813            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3814
3815            // Not critical if that is lost - app has to request again.
3816            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3817        }
3818
3819        // Only need to do this if user is initialized. Otherwise it's a new user
3820        // and there are no processes running as the user yet and there's no need
3821        // to make an expensive call to remount processes for the changed permissions.
3822        if (READ_EXTERNAL_STORAGE.equals(name)
3823                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3824            final long token = Binder.clearCallingIdentity();
3825            try {
3826                if (sUserManager.isInitialized(userId)) {
3827                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3828                            MountServiceInternal.class);
3829                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3830                }
3831            } finally {
3832                Binder.restoreCallingIdentity(token);
3833            }
3834        }
3835    }
3836
3837    @Override
3838    public void revokeRuntimePermission(String packageName, String name, int userId) {
3839        if (!sUserManager.exists(userId)) {
3840            Log.e(TAG, "No such user:" + userId);
3841            return;
3842        }
3843
3844        mContext.enforceCallingOrSelfPermission(
3845                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3846                "revokeRuntimePermission");
3847
3848        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3849                "revokeRuntimePermission");
3850
3851        final int appId;
3852
3853        synchronized (mPackages) {
3854            final PackageParser.Package pkg = mPackages.get(packageName);
3855            if (pkg == null) {
3856                throw new IllegalArgumentException("Unknown package: " + packageName);
3857            }
3858
3859            final BasePermission bp = mSettings.mPermissions.get(name);
3860            if (bp == null) {
3861                throw new IllegalArgumentException("Unknown permission: " + name);
3862            }
3863
3864            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3865
3866            // If a permission review is required for legacy apps we represent
3867            // their permissions as always granted runtime ones since we need
3868            // to keep the review required permission flag per user while an
3869            // install permission's state is shared across all users.
3870            if (Build.PERMISSIONS_REVIEW_REQUIRED
3871                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3872                    && bp.isRuntime()) {
3873                return;
3874            }
3875
3876            SettingBase sb = (SettingBase) pkg.mExtras;
3877            if (sb == null) {
3878                throw new IllegalArgumentException("Unknown package: " + packageName);
3879            }
3880
3881            final PermissionsState permissionsState = sb.getPermissionsState();
3882
3883            final int flags = permissionsState.getPermissionFlags(name, userId);
3884            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3885                throw new SecurityException("Cannot revoke system fixed permission: "
3886                        + name + " for package: " + packageName);
3887            }
3888
3889            if (bp.isDevelopment()) {
3890                // Development permissions must be handled specially, since they are not
3891                // normal runtime permissions.  For now they apply to all users.
3892                if (permissionsState.revokeInstallPermission(bp) !=
3893                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3894                    scheduleWriteSettingsLocked();
3895                }
3896                return;
3897            }
3898
3899            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3900                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3901                return;
3902            }
3903
3904            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3905
3906            // Critical, after this call app should never have the permission.
3907            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3908
3909            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3910        }
3911
3912        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3913    }
3914
3915    @Override
3916    public void resetRuntimePermissions() {
3917        mContext.enforceCallingOrSelfPermission(
3918                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3919                "revokeRuntimePermission");
3920
3921        int callingUid = Binder.getCallingUid();
3922        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3923            mContext.enforceCallingOrSelfPermission(
3924                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3925                    "resetRuntimePermissions");
3926        }
3927
3928        synchronized (mPackages) {
3929            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3930            for (int userId : UserManagerService.getInstance().getUserIds()) {
3931                final int packageCount = mPackages.size();
3932                for (int i = 0; i < packageCount; i++) {
3933                    PackageParser.Package pkg = mPackages.valueAt(i);
3934                    if (!(pkg.mExtras instanceof PackageSetting)) {
3935                        continue;
3936                    }
3937                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3938                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3939                }
3940            }
3941        }
3942    }
3943
3944    @Override
3945    public int getPermissionFlags(String name, String packageName, int userId) {
3946        if (!sUserManager.exists(userId)) {
3947            return 0;
3948        }
3949
3950        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3951
3952        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3953                "getPermissionFlags");
3954
3955        synchronized (mPackages) {
3956            final PackageParser.Package pkg = mPackages.get(packageName);
3957            if (pkg == null) {
3958                throw new IllegalArgumentException("Unknown package: " + packageName);
3959            }
3960
3961            final BasePermission bp = mSettings.mPermissions.get(name);
3962            if (bp == null) {
3963                throw new IllegalArgumentException("Unknown permission: " + name);
3964            }
3965
3966            SettingBase sb = (SettingBase) pkg.mExtras;
3967            if (sb == null) {
3968                throw new IllegalArgumentException("Unknown package: " + packageName);
3969            }
3970
3971            PermissionsState permissionsState = sb.getPermissionsState();
3972            return permissionsState.getPermissionFlags(name, userId);
3973        }
3974    }
3975
3976    @Override
3977    public void updatePermissionFlags(String name, String packageName, int flagMask,
3978            int flagValues, int userId) {
3979        if (!sUserManager.exists(userId)) {
3980            return;
3981        }
3982
3983        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3984
3985        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3986                "updatePermissionFlags");
3987
3988        // Only the system can change these flags and nothing else.
3989        if (getCallingUid() != Process.SYSTEM_UID) {
3990            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3991            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3992            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3993            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3994            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3995        }
3996
3997        synchronized (mPackages) {
3998            final PackageParser.Package pkg = mPackages.get(packageName);
3999            if (pkg == null) {
4000                throw new IllegalArgumentException("Unknown package: " + packageName);
4001            }
4002
4003            final BasePermission bp = mSettings.mPermissions.get(name);
4004            if (bp == null) {
4005                throw new IllegalArgumentException("Unknown permission: " + name);
4006            }
4007
4008            SettingBase sb = (SettingBase) pkg.mExtras;
4009            if (sb == null) {
4010                throw new IllegalArgumentException("Unknown package: " + packageName);
4011            }
4012
4013            PermissionsState permissionsState = sb.getPermissionsState();
4014
4015            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4016
4017            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4018                // Install and runtime permissions are stored in different places,
4019                // so figure out what permission changed and persist the change.
4020                if (permissionsState.getInstallPermissionState(name) != null) {
4021                    scheduleWriteSettingsLocked();
4022                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4023                        || hadState) {
4024                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4025                }
4026            }
4027        }
4028    }
4029
4030    /**
4031     * Update the permission flags for all packages and runtime permissions of a user in order
4032     * to allow device or profile owner to remove POLICY_FIXED.
4033     */
4034    @Override
4035    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4036        if (!sUserManager.exists(userId)) {
4037            return;
4038        }
4039
4040        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4041
4042        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4043                "updatePermissionFlagsForAllApps");
4044
4045        // Only the system can change system fixed flags.
4046        if (getCallingUid() != Process.SYSTEM_UID) {
4047            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4048            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4049        }
4050
4051        synchronized (mPackages) {
4052            boolean changed = false;
4053            final int packageCount = mPackages.size();
4054            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4055                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4056                SettingBase sb = (SettingBase) pkg.mExtras;
4057                if (sb == null) {
4058                    continue;
4059                }
4060                PermissionsState permissionsState = sb.getPermissionsState();
4061                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4062                        userId, flagMask, flagValues);
4063            }
4064            if (changed) {
4065                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4066            }
4067        }
4068    }
4069
4070    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4071        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4072                != PackageManager.PERMISSION_GRANTED
4073            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4074                != PackageManager.PERMISSION_GRANTED) {
4075            throw new SecurityException(message + " requires "
4076                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4077                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4078        }
4079    }
4080
4081    @Override
4082    public boolean shouldShowRequestPermissionRationale(String permissionName,
4083            String packageName, int userId) {
4084        if (UserHandle.getCallingUserId() != userId) {
4085            mContext.enforceCallingPermission(
4086                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4087                    "canShowRequestPermissionRationale for user " + userId);
4088        }
4089
4090        final int uid = getPackageUid(packageName, userId);
4091        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4092            return false;
4093        }
4094
4095        if (checkPermission(permissionName, packageName, userId)
4096                == PackageManager.PERMISSION_GRANTED) {
4097            return false;
4098        }
4099
4100        final int flags;
4101
4102        final long identity = Binder.clearCallingIdentity();
4103        try {
4104            flags = getPermissionFlags(permissionName,
4105                    packageName, userId);
4106        } finally {
4107            Binder.restoreCallingIdentity(identity);
4108        }
4109
4110        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4111                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4112                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4113
4114        if ((flags & fixedFlags) != 0) {
4115            return false;
4116        }
4117
4118        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4119    }
4120
4121    @Override
4122    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4123        mContext.enforceCallingOrSelfPermission(
4124                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4125                "addOnPermissionsChangeListener");
4126
4127        synchronized (mPackages) {
4128            mOnPermissionChangeListeners.addListenerLocked(listener);
4129        }
4130    }
4131
4132    @Override
4133    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4134        synchronized (mPackages) {
4135            mOnPermissionChangeListeners.removeListenerLocked(listener);
4136        }
4137    }
4138
4139    @Override
4140    public boolean isProtectedBroadcast(String actionName) {
4141        synchronized (mPackages) {
4142            if (mProtectedBroadcasts.contains(actionName)) {
4143                return true;
4144            } else if (actionName != null) {
4145                // TODO: remove these terrible hacks
4146                if (actionName.startsWith("android.net.netmon.lingerExpired")
4147                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4148                    return true;
4149                }
4150            }
4151        }
4152        return false;
4153    }
4154
4155    @Override
4156    public int checkSignatures(String pkg1, String pkg2) {
4157        synchronized (mPackages) {
4158            final PackageParser.Package p1 = mPackages.get(pkg1);
4159            final PackageParser.Package p2 = mPackages.get(pkg2);
4160            if (p1 == null || p1.mExtras == null
4161                    || p2 == null || p2.mExtras == null) {
4162                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4163            }
4164            return compareSignatures(p1.mSignatures, p2.mSignatures);
4165        }
4166    }
4167
4168    @Override
4169    public int checkUidSignatures(int uid1, int uid2) {
4170        // Map to base uids.
4171        uid1 = UserHandle.getAppId(uid1);
4172        uid2 = UserHandle.getAppId(uid2);
4173        // reader
4174        synchronized (mPackages) {
4175            Signature[] s1;
4176            Signature[] s2;
4177            Object obj = mSettings.getUserIdLPr(uid1);
4178            if (obj != null) {
4179                if (obj instanceof SharedUserSetting) {
4180                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4181                } else if (obj instanceof PackageSetting) {
4182                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4183                } else {
4184                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4185                }
4186            } else {
4187                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4188            }
4189            obj = mSettings.getUserIdLPr(uid2);
4190            if (obj != null) {
4191                if (obj instanceof SharedUserSetting) {
4192                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4193                } else if (obj instanceof PackageSetting) {
4194                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4195                } else {
4196                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4197                }
4198            } else {
4199                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4200            }
4201            return compareSignatures(s1, s2);
4202        }
4203    }
4204
4205    private void killUid(int appId, int userId, String reason) {
4206        final long identity = Binder.clearCallingIdentity();
4207        try {
4208            IActivityManager am = ActivityManagerNative.getDefault();
4209            if (am != null) {
4210                try {
4211                    am.killUid(appId, userId, reason);
4212                } catch (RemoteException e) {
4213                    /* ignore - same process */
4214                }
4215            }
4216        } finally {
4217            Binder.restoreCallingIdentity(identity);
4218        }
4219    }
4220
4221    /**
4222     * Compares two sets of signatures. Returns:
4223     * <br />
4224     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4225     * <br />
4226     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4227     * <br />
4228     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4229     * <br />
4230     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4231     * <br />
4232     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4233     */
4234    static int compareSignatures(Signature[] s1, Signature[] s2) {
4235        if (s1 == null) {
4236            return s2 == null
4237                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4238                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4239        }
4240
4241        if (s2 == null) {
4242            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4243        }
4244
4245        if (s1.length != s2.length) {
4246            return PackageManager.SIGNATURE_NO_MATCH;
4247        }
4248
4249        // Since both signature sets are of size 1, we can compare without HashSets.
4250        if (s1.length == 1) {
4251            return s1[0].equals(s2[0]) ?
4252                    PackageManager.SIGNATURE_MATCH :
4253                    PackageManager.SIGNATURE_NO_MATCH;
4254        }
4255
4256        ArraySet<Signature> set1 = new ArraySet<Signature>();
4257        for (Signature sig : s1) {
4258            set1.add(sig);
4259        }
4260        ArraySet<Signature> set2 = new ArraySet<Signature>();
4261        for (Signature sig : s2) {
4262            set2.add(sig);
4263        }
4264        // Make sure s2 contains all signatures in s1.
4265        if (set1.equals(set2)) {
4266            return PackageManager.SIGNATURE_MATCH;
4267        }
4268        return PackageManager.SIGNATURE_NO_MATCH;
4269    }
4270
4271    /**
4272     * If the database version for this type of package (internal storage or
4273     * external storage) is less than the version where package signatures
4274     * were updated, return true.
4275     */
4276    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4277        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4278        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4279    }
4280
4281    /**
4282     * Used for backward compatibility to make sure any packages with
4283     * certificate chains get upgraded to the new style. {@code existingSigs}
4284     * will be in the old format (since they were stored on disk from before the
4285     * system upgrade) and {@code scannedSigs} will be in the newer format.
4286     */
4287    private int compareSignaturesCompat(PackageSignatures existingSigs,
4288            PackageParser.Package scannedPkg) {
4289        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4290            return PackageManager.SIGNATURE_NO_MATCH;
4291        }
4292
4293        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4294        for (Signature sig : existingSigs.mSignatures) {
4295            existingSet.add(sig);
4296        }
4297        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4298        for (Signature sig : scannedPkg.mSignatures) {
4299            try {
4300                Signature[] chainSignatures = sig.getChainSignatures();
4301                for (Signature chainSig : chainSignatures) {
4302                    scannedCompatSet.add(chainSig);
4303                }
4304            } catch (CertificateEncodingException e) {
4305                scannedCompatSet.add(sig);
4306            }
4307        }
4308        /*
4309         * Make sure the expanded scanned set contains all signatures in the
4310         * existing one.
4311         */
4312        if (scannedCompatSet.equals(existingSet)) {
4313            // Migrate the old signatures to the new scheme.
4314            existingSigs.assignSignatures(scannedPkg.mSignatures);
4315            // The new KeySets will be re-added later in the scanning process.
4316            synchronized (mPackages) {
4317                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4318            }
4319            return PackageManager.SIGNATURE_MATCH;
4320        }
4321        return PackageManager.SIGNATURE_NO_MATCH;
4322    }
4323
4324    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4325        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4326        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4327    }
4328
4329    private int compareSignaturesRecover(PackageSignatures existingSigs,
4330            PackageParser.Package scannedPkg) {
4331        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4332            return PackageManager.SIGNATURE_NO_MATCH;
4333        }
4334
4335        String msg = null;
4336        try {
4337            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4338                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4339                        + scannedPkg.packageName);
4340                return PackageManager.SIGNATURE_MATCH;
4341            }
4342        } catch (CertificateException e) {
4343            msg = e.getMessage();
4344        }
4345
4346        logCriticalInfo(Log.INFO,
4347                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4348        return PackageManager.SIGNATURE_NO_MATCH;
4349    }
4350
4351    @Override
4352    public String[] getPackagesForUid(int uid) {
4353        uid = UserHandle.getAppId(uid);
4354        // reader
4355        synchronized (mPackages) {
4356            Object obj = mSettings.getUserIdLPr(uid);
4357            if (obj instanceof SharedUserSetting) {
4358                final SharedUserSetting sus = (SharedUserSetting) obj;
4359                final int N = sus.packages.size();
4360                final String[] res = new String[N];
4361                final Iterator<PackageSetting> it = sus.packages.iterator();
4362                int i = 0;
4363                while (it.hasNext()) {
4364                    res[i++] = it.next().name;
4365                }
4366                return res;
4367            } else if (obj instanceof PackageSetting) {
4368                final PackageSetting ps = (PackageSetting) obj;
4369                return new String[] { ps.name };
4370            }
4371        }
4372        return null;
4373    }
4374
4375    @Override
4376    public String getNameForUid(int uid) {
4377        // reader
4378        synchronized (mPackages) {
4379            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4380            if (obj instanceof SharedUserSetting) {
4381                final SharedUserSetting sus = (SharedUserSetting) obj;
4382                return sus.name + ":" + sus.userId;
4383            } else if (obj instanceof PackageSetting) {
4384                final PackageSetting ps = (PackageSetting) obj;
4385                return ps.name;
4386            }
4387        }
4388        return null;
4389    }
4390
4391    @Override
4392    public int getUidForSharedUser(String sharedUserName) {
4393        if(sharedUserName == null) {
4394            return -1;
4395        }
4396        // reader
4397        synchronized (mPackages) {
4398            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4399            if (suid == null) {
4400                return -1;
4401            }
4402            return suid.userId;
4403        }
4404    }
4405
4406    @Override
4407    public int getFlagsForUid(int uid) {
4408        synchronized (mPackages) {
4409            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4410            if (obj instanceof SharedUserSetting) {
4411                final SharedUserSetting sus = (SharedUserSetting) obj;
4412                return sus.pkgFlags;
4413            } else if (obj instanceof PackageSetting) {
4414                final PackageSetting ps = (PackageSetting) obj;
4415                return ps.pkgFlags;
4416            }
4417        }
4418        return 0;
4419    }
4420
4421    @Override
4422    public int getPrivateFlagsForUid(int uid) {
4423        synchronized (mPackages) {
4424            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4425            if (obj instanceof SharedUserSetting) {
4426                final SharedUserSetting sus = (SharedUserSetting) obj;
4427                return sus.pkgPrivateFlags;
4428            } else if (obj instanceof PackageSetting) {
4429                final PackageSetting ps = (PackageSetting) obj;
4430                return ps.pkgPrivateFlags;
4431            }
4432        }
4433        return 0;
4434    }
4435
4436    @Override
4437    public boolean isUidPrivileged(int uid) {
4438        uid = UserHandle.getAppId(uid);
4439        // reader
4440        synchronized (mPackages) {
4441            Object obj = mSettings.getUserIdLPr(uid);
4442            if (obj instanceof SharedUserSetting) {
4443                final SharedUserSetting sus = (SharedUserSetting) obj;
4444                final Iterator<PackageSetting> it = sus.packages.iterator();
4445                while (it.hasNext()) {
4446                    if (it.next().isPrivileged()) {
4447                        return true;
4448                    }
4449                }
4450            } else if (obj instanceof PackageSetting) {
4451                final PackageSetting ps = (PackageSetting) obj;
4452                return ps.isPrivileged();
4453            }
4454        }
4455        return false;
4456    }
4457
4458    @Override
4459    public String[] getAppOpPermissionPackages(String permissionName) {
4460        synchronized (mPackages) {
4461            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4462            if (pkgs == null) {
4463                return null;
4464            }
4465            return pkgs.toArray(new String[pkgs.size()]);
4466        }
4467    }
4468
4469    @Override
4470    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4471            int flags, int userId) {
4472        if (!sUserManager.exists(userId)) return null;
4473        flags = updateFlagsForResolve(flags, userId, intent);
4474        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4475        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4476        final ResolveInfo bestChoice =
4477                chooseBestActivity(intent, resolvedType, flags, query, userId);
4478
4479        if (isEphemeralAllowed(intent, query, userId)) {
4480            final EphemeralResolveInfo ai =
4481                    getEphemeralResolveInfo(intent, resolvedType, userId);
4482            if (ai != null) {
4483                if (DEBUG_EPHEMERAL) {
4484                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4485                }
4486                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4487                bestChoice.ephemeralResolveInfo = ai;
4488            }
4489        }
4490        return bestChoice;
4491    }
4492
4493    @Override
4494    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4495            IntentFilter filter, int match, ComponentName activity) {
4496        final int userId = UserHandle.getCallingUserId();
4497        if (DEBUG_PREFERRED) {
4498            Log.v(TAG, "setLastChosenActivity intent=" + intent
4499                + " resolvedType=" + resolvedType
4500                + " flags=" + flags
4501                + " filter=" + filter
4502                + " match=" + match
4503                + " activity=" + activity);
4504            filter.dump(new PrintStreamPrinter(System.out), "    ");
4505        }
4506        intent.setComponent(null);
4507        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4508        // Find any earlier preferred or last chosen entries and nuke them
4509        findPreferredActivity(intent, resolvedType,
4510                flags, query, 0, false, true, false, userId);
4511        // Add the new activity as the last chosen for this filter
4512        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4513                "Setting last chosen");
4514    }
4515
4516    @Override
4517    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4518        final int userId = UserHandle.getCallingUserId();
4519        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4520        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4521        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4522                false, false, false, userId);
4523    }
4524
4525
4526    private boolean isEphemeralAllowed(
4527            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4528        // Short circuit and return early if possible.
4529        final int callingUser = UserHandle.getCallingUserId();
4530        if (callingUser != UserHandle.USER_SYSTEM) {
4531            return false;
4532        }
4533        if (mEphemeralResolverConnection == null) {
4534            return false;
4535        }
4536        if (intent.getComponent() != null) {
4537            return false;
4538        }
4539        if (intent.getPackage() != null) {
4540            return false;
4541        }
4542        final boolean isWebUri = hasWebURI(intent);
4543        if (!isWebUri) {
4544            return false;
4545        }
4546        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4547        synchronized (mPackages) {
4548            final int count = resolvedActivites.size();
4549            for (int n = 0; n < count; n++) {
4550                ResolveInfo info = resolvedActivites.get(n);
4551                String packageName = info.activityInfo.packageName;
4552                PackageSetting ps = mSettings.mPackages.get(packageName);
4553                if (ps != null) {
4554                    // Try to get the status from User settings first
4555                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4556                    int status = (int) (packedStatus >> 32);
4557                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4558                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4559                        if (DEBUG_EPHEMERAL) {
4560                            Slog.v(TAG, "DENY ephemeral apps;"
4561                                + " pkg: " + packageName + ", status: " + status);
4562                        }
4563                        return false;
4564                    }
4565                }
4566            }
4567        }
4568        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4569        return true;
4570    }
4571
4572    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4573            int userId) {
4574        MessageDigest digest = null;
4575        try {
4576            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4577        } catch (NoSuchAlgorithmException e) {
4578            // If we can't create a digest, ignore ephemeral apps.
4579            return null;
4580        }
4581
4582        final byte[] hostBytes = intent.getData().getHost().getBytes();
4583        final byte[] digestBytes = digest.digest(hostBytes);
4584        int shaPrefix =
4585                digestBytes[0] << 24
4586                | digestBytes[1] << 16
4587                | digestBytes[2] << 8
4588                | digestBytes[3] << 0;
4589        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4590                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4591        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4592            // No hash prefix match; there are no ephemeral apps for this domain.
4593            return null;
4594        }
4595        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4596            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4597            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4598                continue;
4599            }
4600            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4601            // No filters; this should never happen.
4602            if (filters.isEmpty()) {
4603                continue;
4604            }
4605            // We have a domain match; resolve the filters to see if anything matches.
4606            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4607            for (int j = filters.size() - 1; j >= 0; --j) {
4608                final EphemeralResolveIntentInfo intentInfo =
4609                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4610                ephemeralResolver.addFilter(intentInfo);
4611            }
4612            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4613                    intent, resolvedType, false /*defaultOnly*/, userId);
4614            if (!matchedResolveInfoList.isEmpty()) {
4615                return matchedResolveInfoList.get(0);
4616            }
4617        }
4618        // Hash or filter mis-match; no ephemeral apps for this domain.
4619        return null;
4620    }
4621
4622    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4623            int flags, List<ResolveInfo> query, int userId) {
4624        if (query != null) {
4625            final int N = query.size();
4626            if (N == 1) {
4627                return query.get(0);
4628            } else if (N > 1) {
4629                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4630                // If there is more than one activity with the same priority,
4631                // then let the user decide between them.
4632                ResolveInfo r0 = query.get(0);
4633                ResolveInfo r1 = query.get(1);
4634                if (DEBUG_INTENT_MATCHING || debug) {
4635                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4636                            + r1.activityInfo.name + "=" + r1.priority);
4637                }
4638                // If the first activity has a higher priority, or a different
4639                // default, then it is always desirable to pick it.
4640                if (r0.priority != r1.priority
4641                        || r0.preferredOrder != r1.preferredOrder
4642                        || r0.isDefault != r1.isDefault) {
4643                    return query.get(0);
4644                }
4645                // If we have saved a preference for a preferred activity for
4646                // this Intent, use that.
4647                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4648                        flags, query, r0.priority, true, false, debug, userId);
4649                if (ri != null) {
4650                    return ri;
4651                }
4652                ri = new ResolveInfo(mResolveInfo);
4653                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4654                ri.activityInfo.applicationInfo = new ApplicationInfo(
4655                        ri.activityInfo.applicationInfo);
4656                if (userId != 0) {
4657                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4658                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4659                }
4660                // Make sure that the resolver is displayable in car mode
4661                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4662                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4663                return ri;
4664            }
4665        }
4666        return null;
4667    }
4668
4669    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4670            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4671        final int N = query.size();
4672        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4673                .get(userId);
4674        // Get the list of persistent preferred activities that handle the intent
4675        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4676        List<PersistentPreferredActivity> pprefs = ppir != null
4677                ? ppir.queryIntent(intent, resolvedType,
4678                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4679                : null;
4680        if (pprefs != null && pprefs.size() > 0) {
4681            final int M = pprefs.size();
4682            for (int i=0; i<M; i++) {
4683                final PersistentPreferredActivity ppa = pprefs.get(i);
4684                if (DEBUG_PREFERRED || debug) {
4685                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4686                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4687                            + "\n  component=" + ppa.mComponent);
4688                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4689                }
4690                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4691                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4692                if (DEBUG_PREFERRED || debug) {
4693                    Slog.v(TAG, "Found persistent preferred activity:");
4694                    if (ai != null) {
4695                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4696                    } else {
4697                        Slog.v(TAG, "  null");
4698                    }
4699                }
4700                if (ai == null) {
4701                    // This previously registered persistent preferred activity
4702                    // component is no longer known. Ignore it and do NOT remove it.
4703                    continue;
4704                }
4705                for (int j=0; j<N; j++) {
4706                    final ResolveInfo ri = query.get(j);
4707                    if (!ri.activityInfo.applicationInfo.packageName
4708                            .equals(ai.applicationInfo.packageName)) {
4709                        continue;
4710                    }
4711                    if (!ri.activityInfo.name.equals(ai.name)) {
4712                        continue;
4713                    }
4714                    //  Found a persistent preference that can handle the intent.
4715                    if (DEBUG_PREFERRED || debug) {
4716                        Slog.v(TAG, "Returning persistent preferred activity: " +
4717                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4718                    }
4719                    return ri;
4720                }
4721            }
4722        }
4723        return null;
4724    }
4725
4726    // TODO: handle preferred activities missing while user has amnesia
4727    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4728            List<ResolveInfo> query, int priority, boolean always,
4729            boolean removeMatches, boolean debug, int userId) {
4730        if (!sUserManager.exists(userId)) return null;
4731        flags = updateFlagsForResolve(flags, userId, intent);
4732        // writer
4733        synchronized (mPackages) {
4734            if (intent.getSelector() != null) {
4735                intent = intent.getSelector();
4736            }
4737            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4738
4739            // Try to find a matching persistent preferred activity.
4740            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4741                    debug, userId);
4742
4743            // If a persistent preferred activity matched, use it.
4744            if (pri != null) {
4745                return pri;
4746            }
4747
4748            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4749            // Get the list of preferred activities that handle the intent
4750            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4751            List<PreferredActivity> prefs = pir != null
4752                    ? pir.queryIntent(intent, resolvedType,
4753                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4754                    : null;
4755            if (prefs != null && prefs.size() > 0) {
4756                boolean changed = false;
4757                try {
4758                    // First figure out how good the original match set is.
4759                    // We will only allow preferred activities that came
4760                    // from the same match quality.
4761                    int match = 0;
4762
4763                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4764
4765                    final int N = query.size();
4766                    for (int j=0; j<N; j++) {
4767                        final ResolveInfo ri = query.get(j);
4768                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4769                                + ": 0x" + Integer.toHexString(match));
4770                        if (ri.match > match) {
4771                            match = ri.match;
4772                        }
4773                    }
4774
4775                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4776                            + Integer.toHexString(match));
4777
4778                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4779                    final int M = prefs.size();
4780                    for (int i=0; i<M; i++) {
4781                        final PreferredActivity pa = prefs.get(i);
4782                        if (DEBUG_PREFERRED || debug) {
4783                            Slog.v(TAG, "Checking PreferredActivity ds="
4784                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4785                                    + "\n  component=" + pa.mPref.mComponent);
4786                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4787                        }
4788                        if (pa.mPref.mMatch != match) {
4789                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4790                                    + Integer.toHexString(pa.mPref.mMatch));
4791                            continue;
4792                        }
4793                        // If it's not an "always" type preferred activity and that's what we're
4794                        // looking for, skip it.
4795                        if (always && !pa.mPref.mAlways) {
4796                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4797                            continue;
4798                        }
4799                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4800                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4801                        if (DEBUG_PREFERRED || debug) {
4802                            Slog.v(TAG, "Found preferred activity:");
4803                            if (ai != null) {
4804                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4805                            } else {
4806                                Slog.v(TAG, "  null");
4807                            }
4808                        }
4809                        if (ai == null) {
4810                            // This previously registered preferred activity
4811                            // component is no longer known.  Most likely an update
4812                            // to the app was installed and in the new version this
4813                            // component no longer exists.  Clean it up by removing
4814                            // it from the preferred activities list, and skip it.
4815                            Slog.w(TAG, "Removing dangling preferred activity: "
4816                                    + pa.mPref.mComponent);
4817                            pir.removeFilter(pa);
4818                            changed = true;
4819                            continue;
4820                        }
4821                        for (int j=0; j<N; j++) {
4822                            final ResolveInfo ri = query.get(j);
4823                            if (!ri.activityInfo.applicationInfo.packageName
4824                                    .equals(ai.applicationInfo.packageName)) {
4825                                continue;
4826                            }
4827                            if (!ri.activityInfo.name.equals(ai.name)) {
4828                                continue;
4829                            }
4830
4831                            if (removeMatches) {
4832                                pir.removeFilter(pa);
4833                                changed = true;
4834                                if (DEBUG_PREFERRED) {
4835                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4836                                }
4837                                break;
4838                            }
4839
4840                            // Okay we found a previously set preferred or last chosen app.
4841                            // If the result set is different from when this
4842                            // was created, we need to clear it and re-ask the
4843                            // user their preference, if we're looking for an "always" type entry.
4844                            if (always && !pa.mPref.sameSet(query)) {
4845                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4846                                        + intent + " type " + resolvedType);
4847                                if (DEBUG_PREFERRED) {
4848                                    Slog.v(TAG, "Removing preferred activity since set changed "
4849                                            + pa.mPref.mComponent);
4850                                }
4851                                pir.removeFilter(pa);
4852                                // Re-add the filter as a "last chosen" entry (!always)
4853                                PreferredActivity lastChosen = new PreferredActivity(
4854                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4855                                pir.addFilter(lastChosen);
4856                                changed = true;
4857                                return null;
4858                            }
4859
4860                            // Yay! Either the set matched or we're looking for the last chosen
4861                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4862                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4863                            return ri;
4864                        }
4865                    }
4866                } finally {
4867                    if (changed) {
4868                        if (DEBUG_PREFERRED) {
4869                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4870                        }
4871                        scheduleWritePackageRestrictionsLocked(userId);
4872                    }
4873                }
4874            }
4875        }
4876        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4877        return null;
4878    }
4879
4880    /*
4881     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4882     */
4883    @Override
4884    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4885            int targetUserId) {
4886        mContext.enforceCallingOrSelfPermission(
4887                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4888        List<CrossProfileIntentFilter> matches =
4889                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4890        if (matches != null) {
4891            int size = matches.size();
4892            for (int i = 0; i < size; i++) {
4893                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4894            }
4895        }
4896        if (hasWebURI(intent)) {
4897            // cross-profile app linking works only towards the parent.
4898            final UserInfo parent = getProfileParent(sourceUserId);
4899            synchronized(mPackages) {
4900                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4901                        intent, resolvedType, 0, sourceUserId, parent.id);
4902                return xpDomainInfo != null;
4903            }
4904        }
4905        return false;
4906    }
4907
4908    private UserInfo getProfileParent(int userId) {
4909        final long identity = Binder.clearCallingIdentity();
4910        try {
4911            return sUserManager.getProfileParent(userId);
4912        } finally {
4913            Binder.restoreCallingIdentity(identity);
4914        }
4915    }
4916
4917    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4918            String resolvedType, int userId) {
4919        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4920        if (resolver != null) {
4921            return resolver.queryIntent(intent, resolvedType, false, userId);
4922        }
4923        return null;
4924    }
4925
4926    @Override
4927    public List<ResolveInfo> queryIntentActivities(Intent intent,
4928            String resolvedType, int flags, int userId) {
4929        if (!sUserManager.exists(userId)) return Collections.emptyList();
4930        flags = updateFlagsForResolve(flags, userId, intent);
4931        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4932        ComponentName comp = intent.getComponent();
4933        if (comp == null) {
4934            if (intent.getSelector() != null) {
4935                intent = intent.getSelector();
4936                comp = intent.getComponent();
4937            }
4938        }
4939
4940        if (comp != null) {
4941            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4942            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4943            if (ai != null) {
4944                final ResolveInfo ri = new ResolveInfo();
4945                ri.activityInfo = ai;
4946                list.add(ri);
4947            }
4948            return list;
4949        }
4950
4951        // reader
4952        synchronized (mPackages) {
4953            final String pkgName = intent.getPackage();
4954            if (pkgName == null) {
4955                List<CrossProfileIntentFilter> matchingFilters =
4956                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4957                // Check for results that need to skip the current profile.
4958                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4959                        resolvedType, flags, userId);
4960                if (xpResolveInfo != null) {
4961                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4962                    result.add(xpResolveInfo);
4963                    return filterIfNotSystemUser(result, userId);
4964                }
4965
4966                // Check for results in the current profile.
4967                List<ResolveInfo> result = mActivities.queryIntent(
4968                        intent, resolvedType, flags, userId);
4969                result = filterIfNotSystemUser(result, userId);
4970
4971                // Check for cross profile results.
4972                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4973                xpResolveInfo = queryCrossProfileIntents(
4974                        matchingFilters, intent, resolvedType, flags, userId,
4975                        hasNonNegativePriorityResult);
4976                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4977                    boolean isVisibleToUser = filterIfNotSystemUser(
4978                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4979                    if (isVisibleToUser) {
4980                        result.add(xpResolveInfo);
4981                        Collections.sort(result, mResolvePrioritySorter);
4982                    }
4983                }
4984                if (hasWebURI(intent)) {
4985                    CrossProfileDomainInfo xpDomainInfo = null;
4986                    final UserInfo parent = getProfileParent(userId);
4987                    if (parent != null) {
4988                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4989                                flags, userId, parent.id);
4990                    }
4991                    if (xpDomainInfo != null) {
4992                        if (xpResolveInfo != null) {
4993                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4994                            // in the result.
4995                            result.remove(xpResolveInfo);
4996                        }
4997                        if (result.size() == 0) {
4998                            result.add(xpDomainInfo.resolveInfo);
4999                            return result;
5000                        }
5001                    } else if (result.size() <= 1) {
5002                        return result;
5003                    }
5004                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5005                            xpDomainInfo, userId);
5006                    Collections.sort(result, mResolvePrioritySorter);
5007                }
5008                return result;
5009            }
5010            final PackageParser.Package pkg = mPackages.get(pkgName);
5011            if (pkg != null) {
5012                return filterIfNotSystemUser(
5013                        mActivities.queryIntentForPackage(
5014                                intent, resolvedType, flags, pkg.activities, userId),
5015                        userId);
5016            }
5017            return new ArrayList<ResolveInfo>();
5018        }
5019    }
5020
5021    private static class CrossProfileDomainInfo {
5022        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5023        ResolveInfo resolveInfo;
5024        /* Best domain verification status of the activities found in the other profile */
5025        int bestDomainVerificationStatus;
5026    }
5027
5028    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5029            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5030        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5031                sourceUserId)) {
5032            return null;
5033        }
5034        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5035                resolvedType, flags, parentUserId);
5036
5037        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5038            return null;
5039        }
5040        CrossProfileDomainInfo result = null;
5041        int size = resultTargetUser.size();
5042        for (int i = 0; i < size; i++) {
5043            ResolveInfo riTargetUser = resultTargetUser.get(i);
5044            // Intent filter verification is only for filters that specify a host. So don't return
5045            // those that handle all web uris.
5046            if (riTargetUser.handleAllWebDataURI) {
5047                continue;
5048            }
5049            String packageName = riTargetUser.activityInfo.packageName;
5050            PackageSetting ps = mSettings.mPackages.get(packageName);
5051            if (ps == null) {
5052                continue;
5053            }
5054            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5055            int status = (int)(verificationState >> 32);
5056            if (result == null) {
5057                result = new CrossProfileDomainInfo();
5058                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5059                        sourceUserId, parentUserId);
5060                result.bestDomainVerificationStatus = status;
5061            } else {
5062                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5063                        result.bestDomainVerificationStatus);
5064            }
5065        }
5066        // Don't consider matches with status NEVER across profiles.
5067        if (result != null && result.bestDomainVerificationStatus
5068                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5069            return null;
5070        }
5071        return result;
5072    }
5073
5074    /**
5075     * Verification statuses are ordered from the worse to the best, except for
5076     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5077     */
5078    private int bestDomainVerificationStatus(int status1, int status2) {
5079        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5080            return status2;
5081        }
5082        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5083            return status1;
5084        }
5085        return (int) MathUtils.max(status1, status2);
5086    }
5087
5088    private boolean isUserEnabled(int userId) {
5089        long callingId = Binder.clearCallingIdentity();
5090        try {
5091            UserInfo userInfo = sUserManager.getUserInfo(userId);
5092            return userInfo != null && userInfo.isEnabled();
5093        } finally {
5094            Binder.restoreCallingIdentity(callingId);
5095        }
5096    }
5097
5098    /**
5099     * Filter out activities with systemUserOnly flag set, when current user is not System.
5100     *
5101     * @return filtered list
5102     */
5103    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5104        if (userId == UserHandle.USER_SYSTEM) {
5105            return resolveInfos;
5106        }
5107        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5108            ResolveInfo info = resolveInfos.get(i);
5109            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5110                resolveInfos.remove(i);
5111            }
5112        }
5113        return resolveInfos;
5114    }
5115
5116    /**
5117     * @param resolveInfos list of resolve infos in descending priority order
5118     * @return if the list contains a resolve info with non-negative priority
5119     */
5120    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5121        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5122    }
5123
5124    private static boolean hasWebURI(Intent intent) {
5125        if (intent.getData() == null) {
5126            return false;
5127        }
5128        final String scheme = intent.getScheme();
5129        if (TextUtils.isEmpty(scheme)) {
5130            return false;
5131        }
5132        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5133    }
5134
5135    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5136            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5137            int userId) {
5138        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5139
5140        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5141            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5142                    candidates.size());
5143        }
5144
5145        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5146        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5147        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5148        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5149        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5150        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5151
5152        synchronized (mPackages) {
5153            final int count = candidates.size();
5154            // First, try to use linked apps. Partition the candidates into four lists:
5155            // one for the final results, one for the "do not use ever", one for "undefined status"
5156            // and finally one for "browser app type".
5157            for (int n=0; n<count; n++) {
5158                ResolveInfo info = candidates.get(n);
5159                String packageName = info.activityInfo.packageName;
5160                PackageSetting ps = mSettings.mPackages.get(packageName);
5161                if (ps != null) {
5162                    // Add to the special match all list (Browser use case)
5163                    if (info.handleAllWebDataURI) {
5164                        matchAllList.add(info);
5165                        continue;
5166                    }
5167                    // Try to get the status from User settings first
5168                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5169                    int status = (int)(packedStatus >> 32);
5170                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5171                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5172                        if (DEBUG_DOMAIN_VERIFICATION) {
5173                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5174                                    + " : linkgen=" + linkGeneration);
5175                        }
5176                        // Use link-enabled generation as preferredOrder, i.e.
5177                        // prefer newly-enabled over earlier-enabled.
5178                        info.preferredOrder = linkGeneration;
5179                        alwaysList.add(info);
5180                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5181                        if (DEBUG_DOMAIN_VERIFICATION) {
5182                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5183                        }
5184                        neverList.add(info);
5185                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5186                        if (DEBUG_DOMAIN_VERIFICATION) {
5187                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5188                        }
5189                        alwaysAskList.add(info);
5190                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5191                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5192                        if (DEBUG_DOMAIN_VERIFICATION) {
5193                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5194                        }
5195                        undefinedList.add(info);
5196                    }
5197                }
5198            }
5199
5200            // We'll want to include browser possibilities in a few cases
5201            boolean includeBrowser = false;
5202
5203            // First try to add the "always" resolution(s) for the current user, if any
5204            if (alwaysList.size() > 0) {
5205                result.addAll(alwaysList);
5206            } else {
5207                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5208                result.addAll(undefinedList);
5209                // Maybe add one for the other profile.
5210                if (xpDomainInfo != null && (
5211                        xpDomainInfo.bestDomainVerificationStatus
5212                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5213                    result.add(xpDomainInfo.resolveInfo);
5214                }
5215                includeBrowser = true;
5216            }
5217
5218            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5219            // If there were 'always' entries their preferred order has been set, so we also
5220            // back that off to make the alternatives equivalent
5221            if (alwaysAskList.size() > 0) {
5222                for (ResolveInfo i : result) {
5223                    i.preferredOrder = 0;
5224                }
5225                result.addAll(alwaysAskList);
5226                includeBrowser = true;
5227            }
5228
5229            if (includeBrowser) {
5230                // Also add browsers (all of them or only the default one)
5231                if (DEBUG_DOMAIN_VERIFICATION) {
5232                    Slog.v(TAG, "   ...including browsers in candidate set");
5233                }
5234                if ((matchFlags & MATCH_ALL) != 0) {
5235                    result.addAll(matchAllList);
5236                } else {
5237                    // Browser/generic handling case.  If there's a default browser, go straight
5238                    // to that (but only if there is no other higher-priority match).
5239                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5240                    int maxMatchPrio = 0;
5241                    ResolveInfo defaultBrowserMatch = null;
5242                    final int numCandidates = matchAllList.size();
5243                    for (int n = 0; n < numCandidates; n++) {
5244                        ResolveInfo info = matchAllList.get(n);
5245                        // track the highest overall match priority...
5246                        if (info.priority > maxMatchPrio) {
5247                            maxMatchPrio = info.priority;
5248                        }
5249                        // ...and the highest-priority default browser match
5250                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5251                            if (defaultBrowserMatch == null
5252                                    || (defaultBrowserMatch.priority < info.priority)) {
5253                                if (debug) {
5254                                    Slog.v(TAG, "Considering default browser match " + info);
5255                                }
5256                                defaultBrowserMatch = info;
5257                            }
5258                        }
5259                    }
5260                    if (defaultBrowserMatch != null
5261                            && defaultBrowserMatch.priority >= maxMatchPrio
5262                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5263                    {
5264                        if (debug) {
5265                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5266                        }
5267                        result.add(defaultBrowserMatch);
5268                    } else {
5269                        result.addAll(matchAllList);
5270                    }
5271                }
5272
5273                // If there is nothing selected, add all candidates and remove the ones that the user
5274                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5275                if (result.size() == 0) {
5276                    result.addAll(candidates);
5277                    result.removeAll(neverList);
5278                }
5279            }
5280        }
5281        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5282            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5283                    result.size());
5284            for (ResolveInfo info : result) {
5285                Slog.v(TAG, "  + " + info.activityInfo);
5286            }
5287        }
5288        return result;
5289    }
5290
5291    // Returns a packed value as a long:
5292    //
5293    // high 'int'-sized word: link status: undefined/ask/never/always.
5294    // low 'int'-sized word: relative priority among 'always' results.
5295    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5296        long result = ps.getDomainVerificationStatusForUser(userId);
5297        // if none available, get the master status
5298        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5299            if (ps.getIntentFilterVerificationInfo() != null) {
5300                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5301            }
5302        }
5303        return result;
5304    }
5305
5306    private ResolveInfo querySkipCurrentProfileIntents(
5307            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5308            int flags, int sourceUserId) {
5309        if (matchingFilters != null) {
5310            int size = matchingFilters.size();
5311            for (int i = 0; i < size; i ++) {
5312                CrossProfileIntentFilter filter = matchingFilters.get(i);
5313                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5314                    // Checking if there are activities in the target user that can handle the
5315                    // intent.
5316                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5317                            resolvedType, flags, sourceUserId);
5318                    if (resolveInfo != null) {
5319                        return resolveInfo;
5320                    }
5321                }
5322            }
5323        }
5324        return null;
5325    }
5326
5327    // Return matching ResolveInfo in target user if any.
5328    private ResolveInfo queryCrossProfileIntents(
5329            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5330            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5331        if (matchingFilters != null) {
5332            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5333            // match the same intent. For performance reasons, it is better not to
5334            // run queryIntent twice for the same userId
5335            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5336            int size = matchingFilters.size();
5337            for (int i = 0; i < size; i++) {
5338                CrossProfileIntentFilter filter = matchingFilters.get(i);
5339                int targetUserId = filter.getTargetUserId();
5340                boolean skipCurrentProfile =
5341                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5342                boolean skipCurrentProfileIfNoMatchFound =
5343                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5344                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5345                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5346                    // Checking if there are activities in the target user that can handle the
5347                    // intent.
5348                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5349                            resolvedType, flags, sourceUserId);
5350                    if (resolveInfo != null) return resolveInfo;
5351                    alreadyTriedUserIds.put(targetUserId, true);
5352                }
5353            }
5354        }
5355        return null;
5356    }
5357
5358    /**
5359     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5360     * will forward the intent to the filter's target user.
5361     * Otherwise, returns null.
5362     */
5363    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5364            String resolvedType, int flags, int sourceUserId) {
5365        int targetUserId = filter.getTargetUserId();
5366        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5367                resolvedType, flags, targetUserId);
5368        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5369                && isUserEnabled(targetUserId)) {
5370            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5371        }
5372        return null;
5373    }
5374
5375    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5376            int sourceUserId, int targetUserId) {
5377        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5378        long ident = Binder.clearCallingIdentity();
5379        boolean targetIsProfile;
5380        try {
5381            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5382        } finally {
5383            Binder.restoreCallingIdentity(ident);
5384        }
5385        String className;
5386        if (targetIsProfile) {
5387            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5388        } else {
5389            className = FORWARD_INTENT_TO_PARENT;
5390        }
5391        ComponentName forwardingActivityComponentName = new ComponentName(
5392                mAndroidApplication.packageName, className);
5393        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5394                sourceUserId);
5395        if (!targetIsProfile) {
5396            forwardingActivityInfo.showUserIcon = targetUserId;
5397            forwardingResolveInfo.noResourceId = true;
5398        }
5399        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5400        forwardingResolveInfo.priority = 0;
5401        forwardingResolveInfo.preferredOrder = 0;
5402        forwardingResolveInfo.match = 0;
5403        forwardingResolveInfo.isDefault = true;
5404        forwardingResolveInfo.filter = filter;
5405        forwardingResolveInfo.targetUserId = targetUserId;
5406        return forwardingResolveInfo;
5407    }
5408
5409    @Override
5410    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5411            Intent[] specifics, String[] specificTypes, Intent intent,
5412            String resolvedType, int flags, int userId) {
5413        if (!sUserManager.exists(userId)) return Collections.emptyList();
5414        flags = updateFlagsForResolve(flags, userId, intent);
5415        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5416                false, "query intent activity options");
5417        final String resultsAction = intent.getAction();
5418
5419        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5420                | PackageManager.GET_RESOLVED_FILTER, userId);
5421
5422        if (DEBUG_INTENT_MATCHING) {
5423            Log.v(TAG, "Query " + intent + ": " + results);
5424        }
5425
5426        int specificsPos = 0;
5427        int N;
5428
5429        // todo: note that the algorithm used here is O(N^2).  This
5430        // isn't a problem in our current environment, but if we start running
5431        // into situations where we have more than 5 or 10 matches then this
5432        // should probably be changed to something smarter...
5433
5434        // First we go through and resolve each of the specific items
5435        // that were supplied, taking care of removing any corresponding
5436        // duplicate items in the generic resolve list.
5437        if (specifics != null) {
5438            for (int i=0; i<specifics.length; i++) {
5439                final Intent sintent = specifics[i];
5440                if (sintent == null) {
5441                    continue;
5442                }
5443
5444                if (DEBUG_INTENT_MATCHING) {
5445                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5446                }
5447
5448                String action = sintent.getAction();
5449                if (resultsAction != null && resultsAction.equals(action)) {
5450                    // If this action was explicitly requested, then don't
5451                    // remove things that have it.
5452                    action = null;
5453                }
5454
5455                ResolveInfo ri = null;
5456                ActivityInfo ai = null;
5457
5458                ComponentName comp = sintent.getComponent();
5459                if (comp == null) {
5460                    ri = resolveIntent(
5461                        sintent,
5462                        specificTypes != null ? specificTypes[i] : null,
5463                            flags, userId);
5464                    if (ri == null) {
5465                        continue;
5466                    }
5467                    if (ri == mResolveInfo) {
5468                        // ACK!  Must do something better with this.
5469                    }
5470                    ai = ri.activityInfo;
5471                    comp = new ComponentName(ai.applicationInfo.packageName,
5472                            ai.name);
5473                } else {
5474                    ai = getActivityInfo(comp, flags, userId);
5475                    if (ai == null) {
5476                        continue;
5477                    }
5478                }
5479
5480                // Look for any generic query activities that are duplicates
5481                // of this specific one, and remove them from the results.
5482                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5483                N = results.size();
5484                int j;
5485                for (j=specificsPos; j<N; j++) {
5486                    ResolveInfo sri = results.get(j);
5487                    if ((sri.activityInfo.name.equals(comp.getClassName())
5488                            && sri.activityInfo.applicationInfo.packageName.equals(
5489                                    comp.getPackageName()))
5490                        || (action != null && sri.filter.matchAction(action))) {
5491                        results.remove(j);
5492                        if (DEBUG_INTENT_MATCHING) Log.v(
5493                            TAG, "Removing duplicate item from " + j
5494                            + " due to specific " + specificsPos);
5495                        if (ri == null) {
5496                            ri = sri;
5497                        }
5498                        j--;
5499                        N--;
5500                    }
5501                }
5502
5503                // Add this specific item to its proper place.
5504                if (ri == null) {
5505                    ri = new ResolveInfo();
5506                    ri.activityInfo = ai;
5507                }
5508                results.add(specificsPos, ri);
5509                ri.specificIndex = i;
5510                specificsPos++;
5511            }
5512        }
5513
5514        // Now we go through the remaining generic results and remove any
5515        // duplicate actions that are found here.
5516        N = results.size();
5517        for (int i=specificsPos; i<N-1; i++) {
5518            final ResolveInfo rii = results.get(i);
5519            if (rii.filter == null) {
5520                continue;
5521            }
5522
5523            // Iterate over all of the actions of this result's intent
5524            // filter...  typically this should be just one.
5525            final Iterator<String> it = rii.filter.actionsIterator();
5526            if (it == null) {
5527                continue;
5528            }
5529            while (it.hasNext()) {
5530                final String action = it.next();
5531                if (resultsAction != null && resultsAction.equals(action)) {
5532                    // If this action was explicitly requested, then don't
5533                    // remove things that have it.
5534                    continue;
5535                }
5536                for (int j=i+1; j<N; j++) {
5537                    final ResolveInfo rij = results.get(j);
5538                    if (rij.filter != null && rij.filter.hasAction(action)) {
5539                        results.remove(j);
5540                        if (DEBUG_INTENT_MATCHING) Log.v(
5541                            TAG, "Removing duplicate item from " + j
5542                            + " due to action " + action + " at " + i);
5543                        j--;
5544                        N--;
5545                    }
5546                }
5547            }
5548
5549            // If the caller didn't request filter information, drop it now
5550            // so we don't have to marshall/unmarshall it.
5551            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5552                rii.filter = null;
5553            }
5554        }
5555
5556        // Filter out the caller activity if so requested.
5557        if (caller != null) {
5558            N = results.size();
5559            for (int i=0; i<N; i++) {
5560                ActivityInfo ainfo = results.get(i).activityInfo;
5561                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5562                        && caller.getClassName().equals(ainfo.name)) {
5563                    results.remove(i);
5564                    break;
5565                }
5566            }
5567        }
5568
5569        // If the caller didn't request filter information,
5570        // drop them now so we don't have to
5571        // marshall/unmarshall it.
5572        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5573            N = results.size();
5574            for (int i=0; i<N; i++) {
5575                results.get(i).filter = null;
5576            }
5577        }
5578
5579        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5580        return results;
5581    }
5582
5583    @Override
5584    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5585            int userId) {
5586        if (!sUserManager.exists(userId)) return Collections.emptyList();
5587        flags = updateFlagsForResolve(flags, userId, intent);
5588        ComponentName comp = intent.getComponent();
5589        if (comp == null) {
5590            if (intent.getSelector() != null) {
5591                intent = intent.getSelector();
5592                comp = intent.getComponent();
5593            }
5594        }
5595        if (comp != null) {
5596            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5597            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5598            if (ai != null) {
5599                ResolveInfo ri = new ResolveInfo();
5600                ri.activityInfo = ai;
5601                list.add(ri);
5602            }
5603            return list;
5604        }
5605
5606        // reader
5607        synchronized (mPackages) {
5608            String pkgName = intent.getPackage();
5609            if (pkgName == null) {
5610                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5611            }
5612            final PackageParser.Package pkg = mPackages.get(pkgName);
5613            if (pkg != null) {
5614                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5615                        userId);
5616            }
5617            return null;
5618        }
5619    }
5620
5621    @Override
5622    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5623        if (!sUserManager.exists(userId)) return null;
5624        flags = updateFlagsForResolve(flags, userId, intent);
5625        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5626        if (query != null) {
5627            if (query.size() >= 1) {
5628                // If there is more than one service with the same priority,
5629                // just arbitrarily pick the first one.
5630                return query.get(0);
5631            }
5632        }
5633        return null;
5634    }
5635
5636    @Override
5637    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5638            int userId) {
5639        if (!sUserManager.exists(userId)) return Collections.emptyList();
5640        flags = updateFlagsForResolve(flags, userId, intent);
5641        ComponentName comp = intent.getComponent();
5642        if (comp == null) {
5643            if (intent.getSelector() != null) {
5644                intent = intent.getSelector();
5645                comp = intent.getComponent();
5646            }
5647        }
5648        if (comp != null) {
5649            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5650            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5651            if (si != null) {
5652                final ResolveInfo ri = new ResolveInfo();
5653                ri.serviceInfo = si;
5654                list.add(ri);
5655            }
5656            return list;
5657        }
5658
5659        // reader
5660        synchronized (mPackages) {
5661            String pkgName = intent.getPackage();
5662            if (pkgName == null) {
5663                return mServices.queryIntent(intent, resolvedType, flags, userId);
5664            }
5665            final PackageParser.Package pkg = mPackages.get(pkgName);
5666            if (pkg != null) {
5667                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5668                        userId);
5669            }
5670            return null;
5671        }
5672    }
5673
5674    @Override
5675    public List<ResolveInfo> queryIntentContentProviders(
5676            Intent intent, String resolvedType, int flags, int userId) {
5677        if (!sUserManager.exists(userId)) return Collections.emptyList();
5678        flags = updateFlagsForResolve(flags, userId, intent);
5679        ComponentName comp = intent.getComponent();
5680        if (comp == null) {
5681            if (intent.getSelector() != null) {
5682                intent = intent.getSelector();
5683                comp = intent.getComponent();
5684            }
5685        }
5686        if (comp != null) {
5687            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5688            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5689            if (pi != null) {
5690                final ResolveInfo ri = new ResolveInfo();
5691                ri.providerInfo = pi;
5692                list.add(ri);
5693            }
5694            return list;
5695        }
5696
5697        // reader
5698        synchronized (mPackages) {
5699            String pkgName = intent.getPackage();
5700            if (pkgName == null) {
5701                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5702            }
5703            final PackageParser.Package pkg = mPackages.get(pkgName);
5704            if (pkg != null) {
5705                return mProviders.queryIntentForPackage(
5706                        intent, resolvedType, flags, pkg.providers, userId);
5707            }
5708            return null;
5709        }
5710    }
5711
5712    @Override
5713    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5714        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5715        flags = updateFlagsForPackage(flags, userId, null);
5716        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5717        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5718
5719        // writer
5720        synchronized (mPackages) {
5721            ArrayList<PackageInfo> list;
5722            if (listUninstalled) {
5723                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5724                for (PackageSetting ps : mSettings.mPackages.values()) {
5725                    PackageInfo pi;
5726                    if (ps.pkg != null) {
5727                        pi = generatePackageInfo(ps.pkg, flags, userId);
5728                    } else {
5729                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5730                    }
5731                    if (pi != null) {
5732                        list.add(pi);
5733                    }
5734                }
5735            } else {
5736                list = new ArrayList<PackageInfo>(mPackages.size());
5737                for (PackageParser.Package p : mPackages.values()) {
5738                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5739                    if (pi != null) {
5740                        list.add(pi);
5741                    }
5742                }
5743            }
5744
5745            return new ParceledListSlice<PackageInfo>(list);
5746        }
5747    }
5748
5749    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5750            String[] permissions, boolean[] tmp, int flags, int userId) {
5751        int numMatch = 0;
5752        final PermissionsState permissionsState = ps.getPermissionsState();
5753        for (int i=0; i<permissions.length; i++) {
5754            final String permission = permissions[i];
5755            if (permissionsState.hasPermission(permission, userId)) {
5756                tmp[i] = true;
5757                numMatch++;
5758            } else {
5759                tmp[i] = false;
5760            }
5761        }
5762        if (numMatch == 0) {
5763            return;
5764        }
5765        PackageInfo pi;
5766        if (ps.pkg != null) {
5767            pi = generatePackageInfo(ps.pkg, flags, userId);
5768        } else {
5769            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5770        }
5771        // The above might return null in cases of uninstalled apps or install-state
5772        // skew across users/profiles.
5773        if (pi != null) {
5774            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5775                if (numMatch == permissions.length) {
5776                    pi.requestedPermissions = permissions;
5777                } else {
5778                    pi.requestedPermissions = new String[numMatch];
5779                    numMatch = 0;
5780                    for (int i=0; i<permissions.length; i++) {
5781                        if (tmp[i]) {
5782                            pi.requestedPermissions[numMatch] = permissions[i];
5783                            numMatch++;
5784                        }
5785                    }
5786                }
5787            }
5788            list.add(pi);
5789        }
5790    }
5791
5792    @Override
5793    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5794            String[] permissions, int flags, int userId) {
5795        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5796        flags = updateFlagsForPackage(flags, userId, permissions);
5797        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5798
5799        // writer
5800        synchronized (mPackages) {
5801            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5802            boolean[] tmpBools = new boolean[permissions.length];
5803            if (listUninstalled) {
5804                for (PackageSetting ps : mSettings.mPackages.values()) {
5805                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5806                }
5807            } else {
5808                for (PackageParser.Package pkg : mPackages.values()) {
5809                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5810                    if (ps != null) {
5811                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5812                                userId);
5813                    }
5814                }
5815            }
5816
5817            return new ParceledListSlice<PackageInfo>(list);
5818        }
5819    }
5820
5821    @Override
5822    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5823        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5824        flags = updateFlagsForApplication(flags, userId, null);
5825        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5826
5827        // writer
5828        synchronized (mPackages) {
5829            ArrayList<ApplicationInfo> list;
5830            if (listUninstalled) {
5831                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5832                for (PackageSetting ps : mSettings.mPackages.values()) {
5833                    ApplicationInfo ai;
5834                    if (ps.pkg != null) {
5835                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5836                                ps.readUserState(userId), userId);
5837                    } else {
5838                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5839                    }
5840                    if (ai != null) {
5841                        list.add(ai);
5842                    }
5843                }
5844            } else {
5845                list = new ArrayList<ApplicationInfo>(mPackages.size());
5846                for (PackageParser.Package p : mPackages.values()) {
5847                    if (p.mExtras != null) {
5848                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5849                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5850                        if (ai != null) {
5851                            list.add(ai);
5852                        }
5853                    }
5854                }
5855            }
5856
5857            return new ParceledListSlice<ApplicationInfo>(list);
5858        }
5859    }
5860
5861    @Override
5862    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5863        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5864                "getEphemeralApplications");
5865        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5866                "getEphemeralApplications");
5867        synchronized (mPackages) {
5868            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5869                    .getEphemeralApplicationsLPw(userId);
5870            if (ephemeralApps != null) {
5871                return new ParceledListSlice<>(ephemeralApps);
5872            }
5873        }
5874        return null;
5875    }
5876
5877    @Override
5878    public boolean isEphemeralApplication(String packageName, int userId) {
5879        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5880                "isEphemeral");
5881        if (!isCallerSameApp(packageName)) {
5882            return false;
5883        }
5884        synchronized (mPackages) {
5885            PackageParser.Package pkg = mPackages.get(packageName);
5886            if (pkg != null) {
5887                return pkg.applicationInfo.isEphemeralApp();
5888            }
5889        }
5890        return false;
5891    }
5892
5893    @Override
5894    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5895        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5896                "getCookie");
5897        if (!isCallerSameApp(packageName)) {
5898            return null;
5899        }
5900        synchronized (mPackages) {
5901            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5902                    packageName, userId);
5903        }
5904    }
5905
5906    @Override
5907    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5908        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5909                "setCookie");
5910        if (!isCallerSameApp(packageName)) {
5911            return false;
5912        }
5913        synchronized (mPackages) {
5914            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5915                    packageName, cookie, userId);
5916        }
5917    }
5918
5919    @Override
5920    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5921        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5922                "getEphemeralApplicationIcon");
5923        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5924                "getEphemeralApplicationIcon");
5925        synchronized (mPackages) {
5926            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5927                    packageName, userId);
5928        }
5929    }
5930
5931    private boolean isCallerSameApp(String packageName) {
5932        PackageParser.Package pkg = mPackages.get(packageName);
5933        return pkg != null
5934                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5935    }
5936
5937    public List<ApplicationInfo> getPersistentApplications(int flags) {
5938        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5939
5940        // reader
5941        synchronized (mPackages) {
5942            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5943            final int userId = UserHandle.getCallingUserId();
5944            while (i.hasNext()) {
5945                final PackageParser.Package p = i.next();
5946                if (p.applicationInfo != null
5947                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5948                        && (!mSafeMode || isSystemApp(p))) {
5949                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5950                    if (ps != null) {
5951                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5952                                ps.readUserState(userId), userId);
5953                        if (ai != null) {
5954                            finalList.add(ai);
5955                        }
5956                    }
5957                }
5958            }
5959        }
5960
5961        return finalList;
5962    }
5963
5964    @Override
5965    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5966        if (!sUserManager.exists(userId)) return null;
5967        flags = updateFlagsForComponent(flags, userId, name);
5968        // reader
5969        synchronized (mPackages) {
5970            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5971            PackageSetting ps = provider != null
5972                    ? mSettings.mPackages.get(provider.owner.packageName)
5973                    : null;
5974            return ps != null
5975                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5976                    && (!mSafeMode || (provider.info.applicationInfo.flags
5977                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5978                    ? PackageParser.generateProviderInfo(provider, flags,
5979                            ps.readUserState(userId), userId)
5980                    : null;
5981        }
5982    }
5983
5984    /**
5985     * @deprecated
5986     */
5987    @Deprecated
5988    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5989        // reader
5990        synchronized (mPackages) {
5991            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5992                    .entrySet().iterator();
5993            final int userId = UserHandle.getCallingUserId();
5994            while (i.hasNext()) {
5995                Map.Entry<String, PackageParser.Provider> entry = i.next();
5996                PackageParser.Provider p = entry.getValue();
5997                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5998
5999                if (ps != null && p.syncable
6000                        && (!mSafeMode || (p.info.applicationInfo.flags
6001                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6002                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6003                            ps.readUserState(userId), userId);
6004                    if (info != null) {
6005                        outNames.add(entry.getKey());
6006                        outInfo.add(info);
6007                    }
6008                }
6009            }
6010        }
6011    }
6012
6013    @Override
6014    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6015            int uid, int flags) {
6016        final int userId = processName != null ? UserHandle.getUserId(uid)
6017                : UserHandle.getCallingUserId();
6018        if (!sUserManager.exists(userId)) return null;
6019        flags = updateFlagsForComponent(flags, userId, processName);
6020
6021        ArrayList<ProviderInfo> finalList = null;
6022        // reader
6023        synchronized (mPackages) {
6024            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6025            while (i.hasNext()) {
6026                final PackageParser.Provider p = i.next();
6027                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6028                if (ps != null && p.info.authority != null
6029                        && (processName == null
6030                                || (p.info.processName.equals(processName)
6031                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6032                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)
6033                        && (!mSafeMode
6034                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
6035                    if (finalList == null) {
6036                        finalList = new ArrayList<ProviderInfo>(3);
6037                    }
6038                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6039                            ps.readUserState(userId), userId);
6040                    if (info != null) {
6041                        finalList.add(info);
6042                    }
6043                }
6044            }
6045        }
6046
6047        if (finalList != null) {
6048            Collections.sort(finalList, mProviderInitOrderSorter);
6049            return new ParceledListSlice<ProviderInfo>(finalList);
6050        }
6051
6052        return null;
6053    }
6054
6055    @Override
6056    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6057        // reader
6058        synchronized (mPackages) {
6059            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6060            return PackageParser.generateInstrumentationInfo(i, flags);
6061        }
6062    }
6063
6064    @Override
6065    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6066            int flags) {
6067        ArrayList<InstrumentationInfo> finalList =
6068            new ArrayList<InstrumentationInfo>();
6069
6070        // reader
6071        synchronized (mPackages) {
6072            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6073            while (i.hasNext()) {
6074                final PackageParser.Instrumentation p = i.next();
6075                if (targetPackage == null
6076                        || targetPackage.equals(p.info.targetPackage)) {
6077                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6078                            flags);
6079                    if (ii != null) {
6080                        finalList.add(ii);
6081                    }
6082                }
6083            }
6084        }
6085
6086        return finalList;
6087    }
6088
6089    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6090        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6091        if (overlays == null) {
6092            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6093            return;
6094        }
6095        for (PackageParser.Package opkg : overlays.values()) {
6096            // Not much to do if idmap fails: we already logged the error
6097            // and we certainly don't want to abort installation of pkg simply
6098            // because an overlay didn't fit properly. For these reasons,
6099            // ignore the return value of createIdmapForPackagePairLI.
6100            createIdmapForPackagePairLI(pkg, opkg);
6101        }
6102    }
6103
6104    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6105            PackageParser.Package opkg) {
6106        if (!opkg.mTrustedOverlay) {
6107            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6108                    opkg.baseCodePath + ": overlay not trusted");
6109            return false;
6110        }
6111        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6112        if (overlaySet == null) {
6113            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6114                    opkg.baseCodePath + " but target package has no known overlays");
6115            return false;
6116        }
6117        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6118        // TODO: generate idmap for split APKs
6119        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6120            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6121                    + opkg.baseCodePath);
6122            return false;
6123        }
6124        PackageParser.Package[] overlayArray =
6125            overlaySet.values().toArray(new PackageParser.Package[0]);
6126        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6127            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6128                return p1.mOverlayPriority - p2.mOverlayPriority;
6129            }
6130        };
6131        Arrays.sort(overlayArray, cmp);
6132
6133        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6134        int i = 0;
6135        for (PackageParser.Package p : overlayArray) {
6136            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6137        }
6138        return true;
6139    }
6140
6141    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6142        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6143        try {
6144            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6145        } finally {
6146            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6147        }
6148    }
6149
6150    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6151        final File[] files = dir.listFiles();
6152        if (ArrayUtils.isEmpty(files)) {
6153            Log.d(TAG, "No files in app dir " + dir);
6154            return;
6155        }
6156
6157        if (DEBUG_PACKAGE_SCANNING) {
6158            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6159                    + " flags=0x" + Integer.toHexString(parseFlags));
6160        }
6161
6162        for (File file : files) {
6163            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6164                    && !PackageInstallerService.isStageName(file.getName());
6165            if (!isPackage) {
6166                // Ignore entries which are not packages
6167                continue;
6168            }
6169            try {
6170                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6171                        scanFlags, currentTime, null);
6172            } catch (PackageManagerException e) {
6173                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6174
6175                // Delete invalid userdata apps
6176                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6177                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6178                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6179                    if (file.isDirectory()) {
6180                        mInstaller.rmPackageDir(file.getAbsolutePath());
6181                    } else {
6182                        file.delete();
6183                    }
6184                }
6185            }
6186        }
6187    }
6188
6189    private static File getSettingsProblemFile() {
6190        File dataDir = Environment.getDataDirectory();
6191        File systemDir = new File(dataDir, "system");
6192        File fname = new File(systemDir, "uiderrors.txt");
6193        return fname;
6194    }
6195
6196    static void reportSettingsProblem(int priority, String msg) {
6197        logCriticalInfo(priority, msg);
6198    }
6199
6200    static void logCriticalInfo(int priority, String msg) {
6201        Slog.println(priority, TAG, msg);
6202        EventLogTags.writePmCriticalInfo(msg);
6203        try {
6204            File fname = getSettingsProblemFile();
6205            FileOutputStream out = new FileOutputStream(fname, true);
6206            PrintWriter pw = new FastPrintWriter(out);
6207            SimpleDateFormat formatter = new SimpleDateFormat();
6208            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6209            pw.println(dateString + ": " + msg);
6210            pw.close();
6211            FileUtils.setPermissions(
6212                    fname.toString(),
6213                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6214                    -1, -1);
6215        } catch (java.io.IOException e) {
6216        }
6217    }
6218
6219    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6220            PackageParser.Package pkg, File srcFile, int parseFlags)
6221            throws PackageManagerException {
6222        if (ps != null
6223                && ps.codePath.equals(srcFile)
6224                && ps.timeStamp == srcFile.lastModified()
6225                && !isCompatSignatureUpdateNeeded(pkg)
6226                && !isRecoverSignatureUpdateNeeded(pkg)) {
6227            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6228            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6229            ArraySet<PublicKey> signingKs;
6230            synchronized (mPackages) {
6231                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6232            }
6233            if (ps.signatures.mSignatures != null
6234                    && ps.signatures.mSignatures.length != 0
6235                    && signingKs != null) {
6236                // Optimization: reuse the existing cached certificates
6237                // if the package appears to be unchanged.
6238                pkg.mSignatures = ps.signatures.mSignatures;
6239                pkg.mSigningKeys = signingKs;
6240                return;
6241            }
6242
6243            Slog.w(TAG, "PackageSetting for " + ps.name
6244                    + " is missing signatures.  Collecting certs again to recover them.");
6245        } else {
6246            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6247        }
6248
6249        try {
6250            pp.collectCertificates(pkg, parseFlags);
6251        } catch (PackageParserException e) {
6252            throw PackageManagerException.from(e);
6253        }
6254    }
6255
6256    /**
6257     *  Traces a package scan.
6258     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6259     */
6260    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6261            long currentTime, UserHandle user) throws PackageManagerException {
6262        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6263        try {
6264            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6265        } finally {
6266            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6267        }
6268    }
6269
6270    /**
6271     *  Scans a package and returns the newly parsed package.
6272     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6273     */
6274    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6275            long currentTime, UserHandle user) throws PackageManagerException {
6276        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6277        parseFlags |= mDefParseFlags;
6278        PackageParser pp = new PackageParser();
6279        pp.setSeparateProcesses(mSeparateProcesses);
6280        pp.setOnlyCoreApps(mOnlyCore);
6281        pp.setDisplayMetrics(mMetrics);
6282
6283        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6284            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6285        }
6286
6287        final PackageParser.Package pkg;
6288        try {
6289            pkg = pp.parsePackage(scanFile, parseFlags);
6290        } catch (PackageParserException e) {
6291            throw PackageManagerException.from(e);
6292        }
6293
6294        PackageSetting ps = null;
6295        PackageSetting updatedPkg;
6296        // reader
6297        synchronized (mPackages) {
6298            // Look to see if we already know about this package.
6299            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6300            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6301                // This package has been renamed to its original name.  Let's
6302                // use that.
6303                ps = mSettings.peekPackageLPr(oldName);
6304            }
6305            // If there was no original package, see one for the real package name.
6306            if (ps == null) {
6307                ps = mSettings.peekPackageLPr(pkg.packageName);
6308            }
6309            // Check to see if this package could be hiding/updating a system
6310            // package.  Must look for it either under the original or real
6311            // package name depending on our state.
6312            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6313            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6314        }
6315        boolean updatedPkgBetter = false;
6316        // First check if this is a system package that may involve an update
6317        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6318            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6319            // it needs to drop FLAG_PRIVILEGED.
6320            if (locationIsPrivileged(scanFile)) {
6321                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6322            } else {
6323                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6324            }
6325
6326            if (ps != null && !ps.codePath.equals(scanFile)) {
6327                // The path has changed from what was last scanned...  check the
6328                // version of the new path against what we have stored to determine
6329                // what to do.
6330                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6331                if (pkg.mVersionCode <= ps.versionCode) {
6332                    // The system package has been updated and the code path does not match
6333                    // Ignore entry. Skip it.
6334                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6335                            + " ignored: updated version " + ps.versionCode
6336                            + " better than this " + pkg.mVersionCode);
6337                    if (!updatedPkg.codePath.equals(scanFile)) {
6338                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6339                                + ps.name + " changing from " + updatedPkg.codePathString
6340                                + " to " + scanFile);
6341                        updatedPkg.codePath = scanFile;
6342                        updatedPkg.codePathString = scanFile.toString();
6343                        updatedPkg.resourcePath = scanFile;
6344                        updatedPkg.resourcePathString = scanFile.toString();
6345                    }
6346                    updatedPkg.pkg = pkg;
6347                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6348                            "Package " + ps.name + " at " + scanFile
6349                                    + " ignored: updated version " + ps.versionCode
6350                                    + " better than this " + pkg.mVersionCode);
6351                } else {
6352                    // The current app on the system partition is better than
6353                    // what we have updated to on the data partition; switch
6354                    // back to the system partition version.
6355                    // At this point, its safely assumed that package installation for
6356                    // apps in system partition will go through. If not there won't be a working
6357                    // version of the app
6358                    // writer
6359                    synchronized (mPackages) {
6360                        // Just remove the loaded entries from package lists.
6361                        mPackages.remove(ps.name);
6362                    }
6363
6364                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6365                            + " reverting from " + ps.codePathString
6366                            + ": new version " + pkg.mVersionCode
6367                            + " better than installed " + ps.versionCode);
6368
6369                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6370                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6371                    synchronized (mInstallLock) {
6372                        args.cleanUpResourcesLI();
6373                    }
6374                    synchronized (mPackages) {
6375                        mSettings.enableSystemPackageLPw(ps.name);
6376                    }
6377                    updatedPkgBetter = true;
6378                }
6379            }
6380        }
6381
6382        if (updatedPkg != null) {
6383            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6384            // initially
6385            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6386
6387            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6388            // flag set initially
6389            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6390                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6391            }
6392        }
6393
6394        // Verify certificates against what was last scanned
6395        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6396
6397        /*
6398         * A new system app appeared, but we already had a non-system one of the
6399         * same name installed earlier.
6400         */
6401        boolean shouldHideSystemApp = false;
6402        if (updatedPkg == null && ps != null
6403                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6404            /*
6405             * Check to make sure the signatures match first. If they don't,
6406             * wipe the installed application and its data.
6407             */
6408            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6409                    != PackageManager.SIGNATURE_MATCH) {
6410                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6411                        + " signatures don't match existing userdata copy; removing");
6412                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6413                ps = null;
6414            } else {
6415                /*
6416                 * If the newly-added system app is an older version than the
6417                 * already installed version, hide it. It will be scanned later
6418                 * and re-added like an update.
6419                 */
6420                if (pkg.mVersionCode <= ps.versionCode) {
6421                    shouldHideSystemApp = true;
6422                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6423                            + " but new version " + pkg.mVersionCode + " better than installed "
6424                            + ps.versionCode + "; hiding system");
6425                } else {
6426                    /*
6427                     * The newly found system app is a newer version that the
6428                     * one previously installed. Simply remove the
6429                     * already-installed application and replace it with our own
6430                     * while keeping the application data.
6431                     */
6432                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6433                            + " reverting from " + ps.codePathString + ": new version "
6434                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6435                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6436                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6437                    synchronized (mInstallLock) {
6438                        args.cleanUpResourcesLI();
6439                    }
6440                }
6441            }
6442        }
6443
6444        // The apk is forward locked (not public) if its code and resources
6445        // are kept in different files. (except for app in either system or
6446        // vendor path).
6447        // TODO grab this value from PackageSettings
6448        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6449            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6450                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6451            }
6452        }
6453
6454        // TODO: extend to support forward-locked splits
6455        String resourcePath = null;
6456        String baseResourcePath = null;
6457        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6458            if (ps != null && ps.resourcePathString != null) {
6459                resourcePath = ps.resourcePathString;
6460                baseResourcePath = ps.resourcePathString;
6461            } else {
6462                // Should not happen at all. Just log an error.
6463                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6464            }
6465        } else {
6466            resourcePath = pkg.codePath;
6467            baseResourcePath = pkg.baseCodePath;
6468        }
6469
6470        // Set application objects path explicitly.
6471        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6472        pkg.applicationInfo.setCodePath(pkg.codePath);
6473        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6474        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6475        pkg.applicationInfo.setResourcePath(resourcePath);
6476        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6477        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6478
6479        // Note that we invoke the following method only if we are about to unpack an application
6480        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6481                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6482
6483        /*
6484         * If the system app should be overridden by a previously installed
6485         * data, hide the system app now and let the /data/app scan pick it up
6486         * again.
6487         */
6488        if (shouldHideSystemApp) {
6489            synchronized (mPackages) {
6490                mSettings.disableSystemPackageLPw(pkg.packageName);
6491            }
6492        }
6493
6494        return scannedPkg;
6495    }
6496
6497    private static String fixProcessName(String defProcessName,
6498            String processName, int uid) {
6499        if (processName == null) {
6500            return defProcessName;
6501        }
6502        return processName;
6503    }
6504
6505    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6506            throws PackageManagerException {
6507        if (pkgSetting.signatures.mSignatures != null) {
6508            // Already existing package. Make sure signatures match
6509            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6510                    == PackageManager.SIGNATURE_MATCH;
6511            if (!match) {
6512                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6513                        == PackageManager.SIGNATURE_MATCH;
6514            }
6515            if (!match) {
6516                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6517                        == PackageManager.SIGNATURE_MATCH;
6518            }
6519            if (!match) {
6520                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6521                        + pkg.packageName + " signatures do not match the "
6522                        + "previously installed version; ignoring!");
6523            }
6524        }
6525
6526        // Check for shared user signatures
6527        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6528            // Already existing package. Make sure signatures match
6529            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6530                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6531            if (!match) {
6532                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6533                        == PackageManager.SIGNATURE_MATCH;
6534            }
6535            if (!match) {
6536                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6537                        == PackageManager.SIGNATURE_MATCH;
6538            }
6539            if (!match) {
6540                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6541                        "Package " + pkg.packageName
6542                        + " has no signatures that match those in shared user "
6543                        + pkgSetting.sharedUser.name + "; ignoring!");
6544            }
6545        }
6546    }
6547
6548    /**
6549     * Enforces that only the system UID or root's UID can call a method exposed
6550     * via Binder.
6551     *
6552     * @param message used as message if SecurityException is thrown
6553     * @throws SecurityException if the caller is not system or root
6554     */
6555    private static final void enforceSystemOrRoot(String message) {
6556        final int uid = Binder.getCallingUid();
6557        if (uid != Process.SYSTEM_UID && uid != 0) {
6558            throw new SecurityException(message);
6559        }
6560    }
6561
6562    @Override
6563    public void performFstrimIfNeeded() {
6564        enforceSystemOrRoot("Only the system can request fstrim");
6565
6566        // Before everything else, see whether we need to fstrim.
6567        try {
6568            IMountService ms = PackageHelper.getMountService();
6569            if (ms != null) {
6570                final boolean isUpgrade = isUpgrade();
6571                boolean doTrim = isUpgrade;
6572                if (doTrim) {
6573                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6574                } else {
6575                    final long interval = android.provider.Settings.Global.getLong(
6576                            mContext.getContentResolver(),
6577                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6578                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6579                    if (interval > 0) {
6580                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6581                        if (timeSinceLast > interval) {
6582                            doTrim = true;
6583                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6584                                    + "; running immediately");
6585                        }
6586                    }
6587                }
6588                if (doTrim) {
6589                    if (!isFirstBoot()) {
6590                        try {
6591                            ActivityManagerNative.getDefault().showBootMessage(
6592                                    mContext.getResources().getString(
6593                                            R.string.android_upgrading_fstrim), true);
6594                        } catch (RemoteException e) {
6595                        }
6596                    }
6597                    ms.runMaintenance();
6598                }
6599            } else {
6600                Slog.e(TAG, "Mount service unavailable!");
6601            }
6602        } catch (RemoteException e) {
6603            // Can't happen; MountService is local
6604        }
6605    }
6606
6607    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6608        List<ResolveInfo> ris = null;
6609        try {
6610            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6611                    intent, null, 0, userId);
6612        } catch (RemoteException e) {
6613        }
6614        ArraySet<String> pkgNames = new ArraySet<String>();
6615        if (ris != null) {
6616            for (ResolveInfo ri : ris) {
6617                pkgNames.add(ri.activityInfo.packageName);
6618            }
6619        }
6620        return pkgNames;
6621    }
6622
6623    @Override
6624    public void notifyPackageUse(String packageName) {
6625        synchronized (mPackages) {
6626            PackageParser.Package p = mPackages.get(packageName);
6627            if (p == null) {
6628                return;
6629            }
6630            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6631        }
6632    }
6633
6634    @Override
6635    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6636        return performDexOptTraced(packageName, instructionSet);
6637    }
6638
6639    public boolean performDexOpt(String packageName, String instructionSet) {
6640        return performDexOptTraced(packageName, instructionSet);
6641    }
6642
6643    private boolean performDexOptTraced(String packageName, String instructionSet) {
6644        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6645        try {
6646            return performDexOptInternal(packageName, instructionSet);
6647        } finally {
6648            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6649        }
6650    }
6651
6652    private boolean performDexOptInternal(String packageName, String instructionSet) {
6653        PackageParser.Package p;
6654        final String targetInstructionSet;
6655        synchronized (mPackages) {
6656            p = mPackages.get(packageName);
6657            if (p == null) {
6658                return false;
6659            }
6660            mPackageUsage.write(false);
6661
6662            targetInstructionSet = instructionSet != null ? instructionSet :
6663                    getPrimaryInstructionSet(p.applicationInfo);
6664            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6665                return false;
6666            }
6667        }
6668        long callingId = Binder.clearCallingIdentity();
6669        try {
6670            synchronized (mInstallLock) {
6671                final String[] instructionSets = new String[] { targetInstructionSet };
6672                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6673                        true /* inclDependencies */);
6674                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6675            }
6676        } finally {
6677            Binder.restoreCallingIdentity(callingId);
6678        }
6679    }
6680
6681    public ArraySet<String> getPackagesThatNeedDexOpt() {
6682        ArraySet<String> pkgs = null;
6683        synchronized (mPackages) {
6684            for (PackageParser.Package p : mPackages.values()) {
6685                if (DEBUG_DEXOPT) {
6686                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6687                }
6688                if (!p.mDexOptPerformed.isEmpty()) {
6689                    continue;
6690                }
6691                if (pkgs == null) {
6692                    pkgs = new ArraySet<String>();
6693                }
6694                pkgs.add(p.packageName);
6695            }
6696        }
6697        return pkgs;
6698    }
6699
6700    public void shutdown() {
6701        mPackageUsage.write(true);
6702    }
6703
6704    @Override
6705    public void forceDexOpt(String packageName) {
6706        enforceSystemOrRoot("forceDexOpt");
6707
6708        PackageParser.Package pkg;
6709        synchronized (mPackages) {
6710            pkg = mPackages.get(packageName);
6711            if (pkg == null) {
6712                throw new IllegalArgumentException("Missing package: " + packageName);
6713            }
6714        }
6715
6716        synchronized (mInstallLock) {
6717            final String[] instructionSets = new String[] {
6718                    getPrimaryInstructionSet(pkg.applicationInfo) };
6719
6720            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6721
6722            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6723                    true /* inclDependencies */);
6724
6725            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6726            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6727                throw new IllegalStateException("Failed to dexopt: " + res);
6728            }
6729        }
6730    }
6731
6732    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6733        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6734            Slog.w(TAG, "Unable to update from " + oldPkg.name
6735                    + " to " + newPkg.packageName
6736                    + ": old package not in system partition");
6737            return false;
6738        } else if (mPackages.get(oldPkg.name) != null) {
6739            Slog.w(TAG, "Unable to update from " + oldPkg.name
6740                    + " to " + newPkg.packageName
6741                    + ": old package still exists");
6742            return false;
6743        }
6744        return true;
6745    }
6746
6747    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6748            throws PackageManagerException {
6749        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6750        if (res != 0) {
6751            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6752                    "Failed to install " + packageName + ": " + res);
6753        }
6754
6755        final int[] users = sUserManager.getUserIds();
6756        for (int user : users) {
6757            if (user != 0) {
6758                res = mInstaller.createUserData(volumeUuid, packageName,
6759                        UserHandle.getUid(user, uid), user, seinfo);
6760                if (res != 0) {
6761                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6762                            "Failed to createUserData " + packageName + ": " + res);
6763                }
6764            }
6765        }
6766    }
6767
6768    private int removeDataDirsLI(String volumeUuid, String packageName) {
6769        int[] users = sUserManager.getUserIds();
6770        int res = 0;
6771        for (int user : users) {
6772            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6773            if (resInner < 0) {
6774                res = resInner;
6775            }
6776        }
6777
6778        return res;
6779    }
6780
6781    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6782        int[] users = sUserManager.getUserIds();
6783        int res = 0;
6784        for (int user : users) {
6785            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6786            if (resInner < 0) {
6787                res = resInner;
6788            }
6789        }
6790        return res;
6791    }
6792
6793    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6794            PackageParser.Package changingLib) {
6795        if (file.path != null) {
6796            usesLibraryFiles.add(file.path);
6797            return;
6798        }
6799        PackageParser.Package p = mPackages.get(file.apk);
6800        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6801            // If we are doing this while in the middle of updating a library apk,
6802            // then we need to make sure to use that new apk for determining the
6803            // dependencies here.  (We haven't yet finished committing the new apk
6804            // to the package manager state.)
6805            if (p == null || p.packageName.equals(changingLib.packageName)) {
6806                p = changingLib;
6807            }
6808        }
6809        if (p != null) {
6810            usesLibraryFiles.addAll(p.getAllCodePaths());
6811        }
6812    }
6813
6814    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6815            PackageParser.Package changingLib) throws PackageManagerException {
6816        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6817            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6818            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6819            for (int i=0; i<N; i++) {
6820                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6821                if (file == null) {
6822                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6823                            "Package " + pkg.packageName + " requires unavailable shared library "
6824                            + pkg.usesLibraries.get(i) + "; failing!");
6825                }
6826                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6827            }
6828            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6829            for (int i=0; i<N; i++) {
6830                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6831                if (file == null) {
6832                    Slog.w(TAG, "Package " + pkg.packageName
6833                            + " desires unavailable shared library "
6834                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6835                } else {
6836                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6837                }
6838            }
6839            N = usesLibraryFiles.size();
6840            if (N > 0) {
6841                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6842            } else {
6843                pkg.usesLibraryFiles = null;
6844            }
6845        }
6846    }
6847
6848    private static boolean hasString(List<String> list, List<String> which) {
6849        if (list == null) {
6850            return false;
6851        }
6852        for (int i=list.size()-1; i>=0; i--) {
6853            for (int j=which.size()-1; j>=0; j--) {
6854                if (which.get(j).equals(list.get(i))) {
6855                    return true;
6856                }
6857            }
6858        }
6859        return false;
6860    }
6861
6862    private void updateAllSharedLibrariesLPw() {
6863        for (PackageParser.Package pkg : mPackages.values()) {
6864            try {
6865                updateSharedLibrariesLPw(pkg, null);
6866            } catch (PackageManagerException e) {
6867                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6868            }
6869        }
6870    }
6871
6872    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6873            PackageParser.Package changingPkg) {
6874        ArrayList<PackageParser.Package> res = null;
6875        for (PackageParser.Package pkg : mPackages.values()) {
6876            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6877                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6878                if (res == null) {
6879                    res = new ArrayList<PackageParser.Package>();
6880                }
6881                res.add(pkg);
6882                try {
6883                    updateSharedLibrariesLPw(pkg, changingPkg);
6884                } catch (PackageManagerException e) {
6885                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6886                }
6887            }
6888        }
6889        return res;
6890    }
6891
6892    /**
6893     * Derive the value of the {@code cpuAbiOverride} based on the provided
6894     * value and an optional stored value from the package settings.
6895     */
6896    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6897        String cpuAbiOverride = null;
6898
6899        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6900            cpuAbiOverride = null;
6901        } else if (abiOverride != null) {
6902            cpuAbiOverride = abiOverride;
6903        } else if (settings != null) {
6904            cpuAbiOverride = settings.cpuAbiOverrideString;
6905        }
6906
6907        return cpuAbiOverride;
6908    }
6909
6910    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6911            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6912        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6913        try {
6914            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6915        } finally {
6916            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6917        }
6918    }
6919
6920    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6921            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6922        boolean success = false;
6923        try {
6924            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6925                    currentTime, user);
6926            success = true;
6927            return res;
6928        } finally {
6929            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6930                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6931            }
6932        }
6933    }
6934
6935    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6936            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6937        final File scanFile = new File(pkg.codePath);
6938        if (pkg.applicationInfo.getCodePath() == null ||
6939                pkg.applicationInfo.getResourcePath() == null) {
6940            // Bail out. The resource and code paths haven't been set.
6941            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6942                    "Code and resource paths haven't been set correctly");
6943        }
6944
6945        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6946            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6947        } else {
6948            // Only allow system apps to be flagged as core apps.
6949            pkg.coreApp = false;
6950        }
6951
6952        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6953            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6954        }
6955
6956        if (mCustomResolverComponentName != null &&
6957                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6958            setUpCustomResolverActivity(pkg);
6959        }
6960
6961        if (pkg.packageName.equals("android")) {
6962            synchronized (mPackages) {
6963                if (mAndroidApplication != null) {
6964                    Slog.w(TAG, "*************************************************");
6965                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6966                    Slog.w(TAG, " file=" + scanFile);
6967                    Slog.w(TAG, "*************************************************");
6968                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6969                            "Core android package being redefined.  Skipping.");
6970                }
6971
6972                // Set up information for our fall-back user intent resolution activity.
6973                mPlatformPackage = pkg;
6974                pkg.mVersionCode = mSdkVersion;
6975                mAndroidApplication = pkg.applicationInfo;
6976
6977                if (!mResolverReplaced) {
6978                    mResolveActivity.applicationInfo = mAndroidApplication;
6979                    mResolveActivity.name = ResolverActivity.class.getName();
6980                    mResolveActivity.packageName = mAndroidApplication.packageName;
6981                    mResolveActivity.processName = "system:ui";
6982                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6983                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6984                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6985                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6986                    mResolveActivity.exported = true;
6987                    mResolveActivity.enabled = true;
6988                    mResolveInfo.activityInfo = mResolveActivity;
6989                    mResolveInfo.priority = 0;
6990                    mResolveInfo.preferredOrder = 0;
6991                    mResolveInfo.match = 0;
6992                    mResolveComponentName = new ComponentName(
6993                            mAndroidApplication.packageName, mResolveActivity.name);
6994                }
6995            }
6996        }
6997
6998        if (DEBUG_PACKAGE_SCANNING) {
6999            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7000                Log.d(TAG, "Scanning package " + pkg.packageName);
7001        }
7002
7003        if (mPackages.containsKey(pkg.packageName)
7004                || mSharedLibraries.containsKey(pkg.packageName)) {
7005            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7006                    "Application package " + pkg.packageName
7007                    + " already installed.  Skipping duplicate.");
7008        }
7009
7010        // If we're only installing presumed-existing packages, require that the
7011        // scanned APK is both already known and at the path previously established
7012        // for it.  Previously unknown packages we pick up normally, but if we have an
7013        // a priori expectation about this package's install presence, enforce it.
7014        // With a singular exception for new system packages. When an OTA contains
7015        // a new system package, we allow the codepath to change from a system location
7016        // to the user-installed location. If we don't allow this change, any newer,
7017        // user-installed version of the application will be ignored.
7018        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7019            if (mExpectingBetter.containsKey(pkg.packageName)) {
7020                logCriticalInfo(Log.WARN,
7021                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7022            } else {
7023                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7024                if (known != null) {
7025                    if (DEBUG_PACKAGE_SCANNING) {
7026                        Log.d(TAG, "Examining " + pkg.codePath
7027                                + " and requiring known paths " + known.codePathString
7028                                + " & " + known.resourcePathString);
7029                    }
7030                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7031                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
7032                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7033                                "Application package " + pkg.packageName
7034                                + " found at " + pkg.applicationInfo.getCodePath()
7035                                + " but expected at " + known.codePathString + "; ignoring.");
7036                    }
7037                }
7038            }
7039        }
7040
7041        // Initialize package source and resource directories
7042        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7043        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7044
7045        SharedUserSetting suid = null;
7046        PackageSetting pkgSetting = null;
7047
7048        if (!isSystemApp(pkg)) {
7049            // Only system apps can use these features.
7050            pkg.mOriginalPackages = null;
7051            pkg.mRealPackage = null;
7052            pkg.mAdoptPermissions = null;
7053        }
7054
7055        // writer
7056        synchronized (mPackages) {
7057            if (pkg.mSharedUserId != null) {
7058                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7059                if (suid == null) {
7060                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7061                            "Creating application package " + pkg.packageName
7062                            + " for shared user failed");
7063                }
7064                if (DEBUG_PACKAGE_SCANNING) {
7065                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7066                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7067                                + "): packages=" + suid.packages);
7068                }
7069            }
7070
7071            // Check if we are renaming from an original package name.
7072            PackageSetting origPackage = null;
7073            String realName = null;
7074            if (pkg.mOriginalPackages != null) {
7075                // This package may need to be renamed to a previously
7076                // installed name.  Let's check on that...
7077                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7078                if (pkg.mOriginalPackages.contains(renamed)) {
7079                    // This package had originally been installed as the
7080                    // original name, and we have already taken care of
7081                    // transitioning to the new one.  Just update the new
7082                    // one to continue using the old name.
7083                    realName = pkg.mRealPackage;
7084                    if (!pkg.packageName.equals(renamed)) {
7085                        // Callers into this function may have already taken
7086                        // care of renaming the package; only do it here if
7087                        // it is not already done.
7088                        pkg.setPackageName(renamed);
7089                    }
7090
7091                } else {
7092                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7093                        if ((origPackage = mSettings.peekPackageLPr(
7094                                pkg.mOriginalPackages.get(i))) != null) {
7095                            // We do have the package already installed under its
7096                            // original name...  should we use it?
7097                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7098                                // New package is not compatible with original.
7099                                origPackage = null;
7100                                continue;
7101                            } else if (origPackage.sharedUser != null) {
7102                                // Make sure uid is compatible between packages.
7103                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7104                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7105                                            + " to " + pkg.packageName + ": old uid "
7106                                            + origPackage.sharedUser.name
7107                                            + " differs from " + pkg.mSharedUserId);
7108                                    origPackage = null;
7109                                    continue;
7110                                }
7111                            } else {
7112                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7113                                        + pkg.packageName + " to old name " + origPackage.name);
7114                            }
7115                            break;
7116                        }
7117                    }
7118                }
7119            }
7120
7121            if (mTransferedPackages.contains(pkg.packageName)) {
7122                Slog.w(TAG, "Package " + pkg.packageName
7123                        + " was transferred to another, but its .apk remains");
7124            }
7125
7126            // Just create the setting, don't add it yet. For already existing packages
7127            // the PkgSetting exists already and doesn't have to be created.
7128            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7129                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7130                    pkg.applicationInfo.primaryCpuAbi,
7131                    pkg.applicationInfo.secondaryCpuAbi,
7132                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7133                    user, false);
7134            if (pkgSetting == null) {
7135                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7136                        "Creating application package " + pkg.packageName + " failed");
7137            }
7138
7139            if (pkgSetting.origPackage != null) {
7140                // If we are first transitioning from an original package,
7141                // fix up the new package's name now.  We need to do this after
7142                // looking up the package under its new name, so getPackageLP
7143                // can take care of fiddling things correctly.
7144                pkg.setPackageName(origPackage.name);
7145
7146                // File a report about this.
7147                String msg = "New package " + pkgSetting.realName
7148                        + " renamed to replace old package " + pkgSetting.name;
7149                reportSettingsProblem(Log.WARN, msg);
7150
7151                // Make a note of it.
7152                mTransferedPackages.add(origPackage.name);
7153
7154                // No longer need to retain this.
7155                pkgSetting.origPackage = null;
7156            }
7157
7158            if (realName != null) {
7159                // Make a note of it.
7160                mTransferedPackages.add(pkg.packageName);
7161            }
7162
7163            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7164                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7165            }
7166
7167            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7168                // Check all shared libraries and map to their actual file path.
7169                // We only do this here for apps not on a system dir, because those
7170                // are the only ones that can fail an install due to this.  We
7171                // will take care of the system apps by updating all of their
7172                // library paths after the scan is done.
7173                updateSharedLibrariesLPw(pkg, null);
7174            }
7175
7176            if (mFoundPolicyFile) {
7177                SELinuxMMAC.assignSeinfoValue(pkg);
7178            }
7179
7180            pkg.applicationInfo.uid = pkgSetting.appId;
7181            pkg.mExtras = pkgSetting;
7182            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7183                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7184                    // We just determined the app is signed correctly, so bring
7185                    // over the latest parsed certs.
7186                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7187                } else {
7188                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7189                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7190                                "Package " + pkg.packageName + " upgrade keys do not match the "
7191                                + "previously installed version");
7192                    } else {
7193                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7194                        String msg = "System package " + pkg.packageName
7195                            + " signature changed; retaining data.";
7196                        reportSettingsProblem(Log.WARN, msg);
7197                    }
7198                }
7199            } else {
7200                try {
7201                    verifySignaturesLP(pkgSetting, pkg);
7202                    // We just determined the app is signed correctly, so bring
7203                    // over the latest parsed certs.
7204                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7205                } catch (PackageManagerException e) {
7206                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7207                        throw e;
7208                    }
7209                    // The signature has changed, but this package is in the system
7210                    // image...  let's recover!
7211                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7212                    // However...  if this package is part of a shared user, but it
7213                    // doesn't match the signature of the shared user, let's fail.
7214                    // What this means is that you can't change the signatures
7215                    // associated with an overall shared user, which doesn't seem all
7216                    // that unreasonable.
7217                    if (pkgSetting.sharedUser != null) {
7218                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7219                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7220                            throw new PackageManagerException(
7221                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7222                                            "Signature mismatch for shared user : "
7223                                            + pkgSetting.sharedUser);
7224                        }
7225                    }
7226                    // File a report about this.
7227                    String msg = "System package " + pkg.packageName
7228                        + " signature changed; retaining data.";
7229                    reportSettingsProblem(Log.WARN, msg);
7230                }
7231            }
7232            // Verify that this new package doesn't have any content providers
7233            // that conflict with existing packages.  Only do this if the
7234            // package isn't already installed, since we don't want to break
7235            // things that are installed.
7236            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7237                final int N = pkg.providers.size();
7238                int i;
7239                for (i=0; i<N; i++) {
7240                    PackageParser.Provider p = pkg.providers.get(i);
7241                    if (p.info.authority != null) {
7242                        String names[] = p.info.authority.split(";");
7243                        for (int j = 0; j < names.length; j++) {
7244                            if (mProvidersByAuthority.containsKey(names[j])) {
7245                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7246                                final String otherPackageName =
7247                                        ((other != null && other.getComponentName() != null) ?
7248                                                other.getComponentName().getPackageName() : "?");
7249                                throw new PackageManagerException(
7250                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7251                                                "Can't install because provider name " + names[j]
7252                                                + " (in package " + pkg.applicationInfo.packageName
7253                                                + ") is already used by " + otherPackageName);
7254                            }
7255                        }
7256                    }
7257                }
7258            }
7259
7260            if (pkg.mAdoptPermissions != null) {
7261                // This package wants to adopt ownership of permissions from
7262                // another package.
7263                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7264                    final String origName = pkg.mAdoptPermissions.get(i);
7265                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7266                    if (orig != null) {
7267                        if (verifyPackageUpdateLPr(orig, pkg)) {
7268                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7269                                    + pkg.packageName);
7270                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7271                        }
7272                    }
7273                }
7274            }
7275        }
7276
7277        final String pkgName = pkg.packageName;
7278
7279        final long scanFileTime = scanFile.lastModified();
7280        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7281        pkg.applicationInfo.processName = fixProcessName(
7282                pkg.applicationInfo.packageName,
7283                pkg.applicationInfo.processName,
7284                pkg.applicationInfo.uid);
7285
7286        if (pkg != mPlatformPackage) {
7287            // This is a normal package, need to make its data directory.
7288            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7289                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7290
7291            boolean uidError = false;
7292            if (dataPath.exists()) {
7293                int currentUid = 0;
7294                try {
7295                    StructStat stat = Os.stat(dataPath.getPath());
7296                    currentUid = stat.st_uid;
7297                } catch (ErrnoException e) {
7298                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7299                }
7300
7301                // If we have mismatched owners for the data path, we have a problem.
7302                if (currentUid != pkg.applicationInfo.uid) {
7303                    boolean recovered = false;
7304                    if (currentUid == 0) {
7305                        // The directory somehow became owned by root.  Wow.
7306                        // This is probably because the system was stopped while
7307                        // installd was in the middle of messing with its libs
7308                        // directory.  Ask installd to fix that.
7309                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7310                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7311                        if (ret >= 0) {
7312                            recovered = true;
7313                            String msg = "Package " + pkg.packageName
7314                                    + " unexpectedly changed to uid 0; recovered to " +
7315                                    + pkg.applicationInfo.uid;
7316                            reportSettingsProblem(Log.WARN, msg);
7317                        }
7318                    }
7319                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7320                            || (scanFlags&SCAN_BOOTING) != 0)) {
7321                        // If this is a system app, we can at least delete its
7322                        // current data so the application will still work.
7323                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7324                        if (ret >= 0) {
7325                            // TODO: Kill the processes first
7326                            // Old data gone!
7327                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7328                                    ? "System package " : "Third party package ";
7329                            String msg = prefix + pkg.packageName
7330                                    + " has changed from uid: "
7331                                    + currentUid + " to "
7332                                    + pkg.applicationInfo.uid + "; old data erased";
7333                            reportSettingsProblem(Log.WARN, msg);
7334                            recovered = true;
7335                        }
7336                        if (!recovered) {
7337                            mHasSystemUidErrors = true;
7338                        }
7339                    } else if (!recovered) {
7340                        // If we allow this install to proceed, we will be broken.
7341                        // Abort, abort!
7342                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7343                                "scanPackageLI");
7344                    }
7345                    if (!recovered) {
7346                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7347                            + pkg.applicationInfo.uid + "/fs_"
7348                            + currentUid;
7349                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7350                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7351                        String msg = "Package " + pkg.packageName
7352                                + " has mismatched uid: "
7353                                + currentUid + " on disk, "
7354                                + pkg.applicationInfo.uid + " in settings";
7355                        // writer
7356                        synchronized (mPackages) {
7357                            mSettings.mReadMessages.append(msg);
7358                            mSettings.mReadMessages.append('\n');
7359                            uidError = true;
7360                            if (!pkgSetting.uidError) {
7361                                reportSettingsProblem(Log.ERROR, msg);
7362                            }
7363                        }
7364                    }
7365                }
7366
7367                // Ensure that directories are prepared
7368                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7369                        pkg.applicationInfo.seinfo);
7370
7371                if (mShouldRestoreconData) {
7372                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7373                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7374                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7375                }
7376            } else {
7377                if (DEBUG_PACKAGE_SCANNING) {
7378                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7379                        Log.v(TAG, "Want this data dir: " + dataPath);
7380                }
7381                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7382                        pkg.applicationInfo.seinfo);
7383            }
7384
7385            // Get all of our default paths setup
7386            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7387
7388            pkgSetting.uidError = uidError;
7389        }
7390
7391        final String path = scanFile.getPath();
7392        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7393
7394        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7395            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7396
7397            // Some system apps still use directory structure for native libraries
7398            // in which case we might end up not detecting abi solely based on apk
7399            // structure. Try to detect abi based on directory structure.
7400            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7401                    pkg.applicationInfo.primaryCpuAbi == null) {
7402                setBundledAppAbisAndRoots(pkg, pkgSetting);
7403                setNativeLibraryPaths(pkg);
7404            }
7405
7406        } else {
7407            if ((scanFlags & SCAN_MOVE) != 0) {
7408                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7409                // but we already have this packages package info in the PackageSetting. We just
7410                // use that and derive the native library path based on the new codepath.
7411                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7412                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7413            }
7414
7415            // Set native library paths again. For moves, the path will be updated based on the
7416            // ABIs we've determined above. For non-moves, the path will be updated based on the
7417            // ABIs we determined during compilation, but the path will depend on the final
7418            // package path (after the rename away from the stage path).
7419            setNativeLibraryPaths(pkg);
7420        }
7421
7422        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7423        final int[] userIds = sUserManager.getUserIds();
7424        synchronized (mInstallLock) {
7425            // Make sure all user data directories are ready to roll; we're okay
7426            // if they already exist
7427            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7428                for (int userId : userIds) {
7429                    if (userId != UserHandle.USER_SYSTEM) {
7430                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7431                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7432                                pkg.applicationInfo.seinfo);
7433                    }
7434                }
7435            }
7436
7437            // Create a native library symlink only if we have native libraries
7438            // and if the native libraries are 32 bit libraries. We do not provide
7439            // this symlink for 64 bit libraries.
7440            if (pkg.applicationInfo.primaryCpuAbi != null &&
7441                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7442                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7443                try {
7444                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7445                    for (int userId : userIds) {
7446                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7447                                nativeLibPath, userId) < 0) {
7448                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7449                                    "Failed linking native library dir (user=" + userId + ")");
7450                        }
7451                    }
7452                } finally {
7453                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7454                }
7455            }
7456        }
7457
7458        // This is a special case for the "system" package, where the ABI is
7459        // dictated by the zygote configuration (and init.rc). We should keep track
7460        // of this ABI so that we can deal with "normal" applications that run under
7461        // the same UID correctly.
7462        if (mPlatformPackage == pkg) {
7463            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7464                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7465        }
7466
7467        // If there's a mismatch between the abi-override in the package setting
7468        // and the abiOverride specified for the install. Warn about this because we
7469        // would've already compiled the app without taking the package setting into
7470        // account.
7471        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7472            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7473                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7474                        " for package: " + pkg.packageName);
7475            }
7476        }
7477
7478        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7479        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7480        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7481
7482        // Copy the derived override back to the parsed package, so that we can
7483        // update the package settings accordingly.
7484        pkg.cpuAbiOverride = cpuAbiOverride;
7485
7486        if (DEBUG_ABI_SELECTION) {
7487            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7488                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7489                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7490        }
7491
7492        // Push the derived path down into PackageSettings so we know what to
7493        // clean up at uninstall time.
7494        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7495
7496        if (DEBUG_ABI_SELECTION) {
7497            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7498                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7499                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7500        }
7501
7502        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7503            // We don't do this here during boot because we can do it all
7504            // at once after scanning all existing packages.
7505            //
7506            // We also do this *before* we perform dexopt on this package, so that
7507            // we can avoid redundant dexopts, and also to make sure we've got the
7508            // code and package path correct.
7509            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7510                    pkg, true /* boot complete */);
7511        }
7512
7513        if (mFactoryTest && pkg.requestedPermissions.contains(
7514                android.Manifest.permission.FACTORY_TEST)) {
7515            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7516        }
7517
7518        ArrayList<PackageParser.Package> clientLibPkgs = null;
7519
7520        // writer
7521        synchronized (mPackages) {
7522            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7523                // Only system apps can add new shared libraries.
7524                if (pkg.libraryNames != null) {
7525                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7526                        String name = pkg.libraryNames.get(i);
7527                        boolean allowed = false;
7528                        if (pkg.isUpdatedSystemApp()) {
7529                            // New library entries can only be added through the
7530                            // system image.  This is important to get rid of a lot
7531                            // of nasty edge cases: for example if we allowed a non-
7532                            // system update of the app to add a library, then uninstalling
7533                            // the update would make the library go away, and assumptions
7534                            // we made such as through app install filtering would now
7535                            // have allowed apps on the device which aren't compatible
7536                            // with it.  Better to just have the restriction here, be
7537                            // conservative, and create many fewer cases that can negatively
7538                            // impact the user experience.
7539                            final PackageSetting sysPs = mSettings
7540                                    .getDisabledSystemPkgLPr(pkg.packageName);
7541                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7542                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7543                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7544                                        allowed = true;
7545                                        break;
7546                                    }
7547                                }
7548                            }
7549                        } else {
7550                            allowed = true;
7551                        }
7552                        if (allowed) {
7553                            if (!mSharedLibraries.containsKey(name)) {
7554                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7555                            } else if (!name.equals(pkg.packageName)) {
7556                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7557                                        + name + " already exists; skipping");
7558                            }
7559                        } else {
7560                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7561                                    + name + " that is not declared on system image; skipping");
7562                        }
7563                    }
7564                    if ((scanFlags & SCAN_BOOTING) == 0) {
7565                        // If we are not booting, we need to update any applications
7566                        // that are clients of our shared library.  If we are booting,
7567                        // this will all be done once the scan is complete.
7568                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7569                    }
7570                }
7571            }
7572        }
7573
7574        // Request the ActivityManager to kill the process(only for existing packages)
7575        // so that we do not end up in a confused state while the user is still using the older
7576        // version of the application while the new one gets installed.
7577        if ((scanFlags & SCAN_REPLACING) != 0) {
7578            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7579
7580            killApplication(pkg.applicationInfo.packageName,
7581                        pkg.applicationInfo.uid, "replace pkg");
7582
7583            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7584        }
7585
7586        // Also need to kill any apps that are dependent on the library.
7587        if (clientLibPkgs != null) {
7588            for (int i=0; i<clientLibPkgs.size(); i++) {
7589                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7590                killApplication(clientPkg.applicationInfo.packageName,
7591                        clientPkg.applicationInfo.uid, "update lib");
7592            }
7593        }
7594
7595        // Make sure we're not adding any bogus keyset info
7596        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7597        ksms.assertScannedPackageValid(pkg);
7598
7599        // writer
7600        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7601
7602        boolean createIdmapFailed = false;
7603        synchronized (mPackages) {
7604            // We don't expect installation to fail beyond this point
7605
7606            // Add the new setting to mSettings
7607            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7608            // Add the new setting to mPackages
7609            mPackages.put(pkg.applicationInfo.packageName, pkg);
7610            // Make sure we don't accidentally delete its data.
7611            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7612            while (iter.hasNext()) {
7613                PackageCleanItem item = iter.next();
7614                if (pkgName.equals(item.packageName)) {
7615                    iter.remove();
7616                }
7617            }
7618
7619            // Take care of first install / last update times.
7620            if (currentTime != 0) {
7621                if (pkgSetting.firstInstallTime == 0) {
7622                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7623                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7624                    pkgSetting.lastUpdateTime = currentTime;
7625                }
7626            } else if (pkgSetting.firstInstallTime == 0) {
7627                // We need *something*.  Take time time stamp of the file.
7628                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7629            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7630                if (scanFileTime != pkgSetting.timeStamp) {
7631                    // A package on the system image has changed; consider this
7632                    // to be an update.
7633                    pkgSetting.lastUpdateTime = scanFileTime;
7634                }
7635            }
7636
7637            // Add the package's KeySets to the global KeySetManagerService
7638            ksms.addScannedPackageLPw(pkg);
7639
7640            int N = pkg.providers.size();
7641            StringBuilder r = null;
7642            int i;
7643            for (i=0; i<N; i++) {
7644                PackageParser.Provider p = pkg.providers.get(i);
7645                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7646                        p.info.processName, pkg.applicationInfo.uid);
7647                mProviders.addProvider(p);
7648                p.syncable = p.info.isSyncable;
7649                if (p.info.authority != null) {
7650                    String names[] = p.info.authority.split(";");
7651                    p.info.authority = null;
7652                    for (int j = 0; j < names.length; j++) {
7653                        if (j == 1 && p.syncable) {
7654                            // We only want the first authority for a provider to possibly be
7655                            // syncable, so if we already added this provider using a different
7656                            // authority clear the syncable flag. We copy the provider before
7657                            // changing it because the mProviders object contains a reference
7658                            // to a provider that we don't want to change.
7659                            // Only do this for the second authority since the resulting provider
7660                            // object can be the same for all future authorities for this provider.
7661                            p = new PackageParser.Provider(p);
7662                            p.syncable = false;
7663                        }
7664                        if (!mProvidersByAuthority.containsKey(names[j])) {
7665                            mProvidersByAuthority.put(names[j], p);
7666                            if (p.info.authority == null) {
7667                                p.info.authority = names[j];
7668                            } else {
7669                                p.info.authority = p.info.authority + ";" + names[j];
7670                            }
7671                            if (DEBUG_PACKAGE_SCANNING) {
7672                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7673                                    Log.d(TAG, "Registered content provider: " + names[j]
7674                                            + ", className = " + p.info.name + ", isSyncable = "
7675                                            + p.info.isSyncable);
7676                            }
7677                        } else {
7678                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7679                            Slog.w(TAG, "Skipping provider name " + names[j] +
7680                                    " (in package " + pkg.applicationInfo.packageName +
7681                                    "): name already used by "
7682                                    + ((other != null && other.getComponentName() != null)
7683                                            ? other.getComponentName().getPackageName() : "?"));
7684                        }
7685                    }
7686                }
7687                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7688                    if (r == null) {
7689                        r = new StringBuilder(256);
7690                    } else {
7691                        r.append(' ');
7692                    }
7693                    r.append(p.info.name);
7694                }
7695            }
7696            if (r != null) {
7697                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7698            }
7699
7700            N = pkg.services.size();
7701            r = null;
7702            for (i=0; i<N; i++) {
7703                PackageParser.Service s = pkg.services.get(i);
7704                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7705                        s.info.processName, pkg.applicationInfo.uid);
7706                mServices.addService(s);
7707                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7708                    if (r == null) {
7709                        r = new StringBuilder(256);
7710                    } else {
7711                        r.append(' ');
7712                    }
7713                    r.append(s.info.name);
7714                }
7715            }
7716            if (r != null) {
7717                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7718            }
7719
7720            N = pkg.receivers.size();
7721            r = null;
7722            for (i=0; i<N; i++) {
7723                PackageParser.Activity a = pkg.receivers.get(i);
7724                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7725                        a.info.processName, pkg.applicationInfo.uid);
7726                mReceivers.addActivity(a, "receiver");
7727                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7728                    if (r == null) {
7729                        r = new StringBuilder(256);
7730                    } else {
7731                        r.append(' ');
7732                    }
7733                    r.append(a.info.name);
7734                }
7735            }
7736            if (r != null) {
7737                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7738            }
7739
7740            N = pkg.activities.size();
7741            r = null;
7742            for (i=0; i<N; i++) {
7743                PackageParser.Activity a = pkg.activities.get(i);
7744                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7745                        a.info.processName, pkg.applicationInfo.uid);
7746                mActivities.addActivity(a, "activity");
7747                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7748                    if (r == null) {
7749                        r = new StringBuilder(256);
7750                    } else {
7751                        r.append(' ');
7752                    }
7753                    r.append(a.info.name);
7754                }
7755            }
7756            if (r != null) {
7757                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7758            }
7759
7760            N = pkg.permissionGroups.size();
7761            r = null;
7762            for (i=0; i<N; i++) {
7763                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7764                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7765                if (cur == null) {
7766                    mPermissionGroups.put(pg.info.name, pg);
7767                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7768                        if (r == null) {
7769                            r = new StringBuilder(256);
7770                        } else {
7771                            r.append(' ');
7772                        }
7773                        r.append(pg.info.name);
7774                    }
7775                } else {
7776                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7777                            + pg.info.packageName + " ignored: original from "
7778                            + cur.info.packageName);
7779                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7780                        if (r == null) {
7781                            r = new StringBuilder(256);
7782                        } else {
7783                            r.append(' ');
7784                        }
7785                        r.append("DUP:");
7786                        r.append(pg.info.name);
7787                    }
7788                }
7789            }
7790            if (r != null) {
7791                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7792            }
7793
7794            N = pkg.permissions.size();
7795            r = null;
7796            for (i=0; i<N; i++) {
7797                PackageParser.Permission p = pkg.permissions.get(i);
7798
7799                // Assume by default that we did not install this permission into the system.
7800                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7801
7802                // Now that permission groups have a special meaning, we ignore permission
7803                // groups for legacy apps to prevent unexpected behavior. In particular,
7804                // permissions for one app being granted to someone just becuase they happen
7805                // to be in a group defined by another app (before this had no implications).
7806                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7807                    p.group = mPermissionGroups.get(p.info.group);
7808                    // Warn for a permission in an unknown group.
7809                    if (p.info.group != null && p.group == null) {
7810                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7811                                + p.info.packageName + " in an unknown group " + p.info.group);
7812                    }
7813                }
7814
7815                ArrayMap<String, BasePermission> permissionMap =
7816                        p.tree ? mSettings.mPermissionTrees
7817                                : mSettings.mPermissions;
7818                BasePermission bp = permissionMap.get(p.info.name);
7819
7820                // Allow system apps to redefine non-system permissions
7821                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7822                    final boolean currentOwnerIsSystem = (bp.perm != null
7823                            && isSystemApp(bp.perm.owner));
7824                    if (isSystemApp(p.owner)) {
7825                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7826                            // It's a built-in permission and no owner, take ownership now
7827                            bp.packageSetting = pkgSetting;
7828                            bp.perm = p;
7829                            bp.uid = pkg.applicationInfo.uid;
7830                            bp.sourcePackage = p.info.packageName;
7831                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7832                        } else if (!currentOwnerIsSystem) {
7833                            String msg = "New decl " + p.owner + " of permission  "
7834                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7835                            reportSettingsProblem(Log.WARN, msg);
7836                            bp = null;
7837                        }
7838                    }
7839                }
7840
7841                if (bp == null) {
7842                    bp = new BasePermission(p.info.name, p.info.packageName,
7843                            BasePermission.TYPE_NORMAL);
7844                    permissionMap.put(p.info.name, bp);
7845                }
7846
7847                if (bp.perm == null) {
7848                    if (bp.sourcePackage == null
7849                            || bp.sourcePackage.equals(p.info.packageName)) {
7850                        BasePermission tree = findPermissionTreeLP(p.info.name);
7851                        if (tree == null
7852                                || tree.sourcePackage.equals(p.info.packageName)) {
7853                            bp.packageSetting = pkgSetting;
7854                            bp.perm = p;
7855                            bp.uid = pkg.applicationInfo.uid;
7856                            bp.sourcePackage = p.info.packageName;
7857                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7858                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7859                                if (r == null) {
7860                                    r = new StringBuilder(256);
7861                                } else {
7862                                    r.append(' ');
7863                                }
7864                                r.append(p.info.name);
7865                            }
7866                        } else {
7867                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7868                                    + p.info.packageName + " ignored: base tree "
7869                                    + tree.name + " is from package "
7870                                    + tree.sourcePackage);
7871                        }
7872                    } else {
7873                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7874                                + p.info.packageName + " ignored: original from "
7875                                + bp.sourcePackage);
7876                    }
7877                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7878                    if (r == null) {
7879                        r = new StringBuilder(256);
7880                    } else {
7881                        r.append(' ');
7882                    }
7883                    r.append("DUP:");
7884                    r.append(p.info.name);
7885                }
7886                if (bp.perm == p) {
7887                    bp.protectionLevel = p.info.protectionLevel;
7888                }
7889            }
7890
7891            if (r != null) {
7892                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7893            }
7894
7895            N = pkg.instrumentation.size();
7896            r = null;
7897            for (i=0; i<N; i++) {
7898                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7899                a.info.packageName = pkg.applicationInfo.packageName;
7900                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7901                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7902                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7903                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7904                a.info.dataDir = pkg.applicationInfo.dataDir;
7905                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7906                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7907
7908                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7909                // need other information about the application, like the ABI and what not ?
7910                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7911                mInstrumentation.put(a.getComponentName(), a);
7912                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7913                    if (r == null) {
7914                        r = new StringBuilder(256);
7915                    } else {
7916                        r.append(' ');
7917                    }
7918                    r.append(a.info.name);
7919                }
7920            }
7921            if (r != null) {
7922                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7923            }
7924
7925            if (pkg.protectedBroadcasts != null) {
7926                N = pkg.protectedBroadcasts.size();
7927                for (i=0; i<N; i++) {
7928                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7929                }
7930            }
7931
7932            pkgSetting.setTimeStamp(scanFileTime);
7933
7934            // Create idmap files for pairs of (packages, overlay packages).
7935            // Note: "android", ie framework-res.apk, is handled by native layers.
7936            if (pkg.mOverlayTarget != null) {
7937                // This is an overlay package.
7938                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7939                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7940                        mOverlays.put(pkg.mOverlayTarget,
7941                                new ArrayMap<String, PackageParser.Package>());
7942                    }
7943                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7944                    map.put(pkg.packageName, pkg);
7945                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7946                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7947                        createIdmapFailed = true;
7948                    }
7949                }
7950            } else if (mOverlays.containsKey(pkg.packageName) &&
7951                    !pkg.packageName.equals("android")) {
7952                // This is a regular package, with one or more known overlay packages.
7953                createIdmapsForPackageLI(pkg);
7954            }
7955        }
7956
7957        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7958
7959        if (createIdmapFailed) {
7960            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7961                    "scanPackageLI failed to createIdmap");
7962        }
7963        return pkg;
7964    }
7965
7966    /**
7967     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7968     * is derived purely on the basis of the contents of {@code scanFile} and
7969     * {@code cpuAbiOverride}.
7970     *
7971     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7972     */
7973    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7974                                 String cpuAbiOverride, boolean extractLibs)
7975            throws PackageManagerException {
7976        // TODO: We can probably be smarter about this stuff. For installed apps,
7977        // we can calculate this information at install time once and for all. For
7978        // system apps, we can probably assume that this information doesn't change
7979        // after the first boot scan. As things stand, we do lots of unnecessary work.
7980
7981        // Give ourselves some initial paths; we'll come back for another
7982        // pass once we've determined ABI below.
7983        setNativeLibraryPaths(pkg);
7984
7985        // We would never need to extract libs for forward-locked and external packages,
7986        // since the container service will do it for us. We shouldn't attempt to
7987        // extract libs from system app when it was not updated.
7988        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7989                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7990            extractLibs = false;
7991        }
7992
7993        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7994        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7995
7996        NativeLibraryHelper.Handle handle = null;
7997        try {
7998            handle = NativeLibraryHelper.Handle.create(pkg);
7999            // TODO(multiArch): This can be null for apps that didn't go through the
8000            // usual installation process. We can calculate it again, like we
8001            // do during install time.
8002            //
8003            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8004            // unnecessary.
8005            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8006
8007            // Null out the abis so that they can be recalculated.
8008            pkg.applicationInfo.primaryCpuAbi = null;
8009            pkg.applicationInfo.secondaryCpuAbi = null;
8010            if (isMultiArch(pkg.applicationInfo)) {
8011                // Warn if we've set an abiOverride for multi-lib packages..
8012                // By definition, we need to copy both 32 and 64 bit libraries for
8013                // such packages.
8014                if (pkg.cpuAbiOverride != null
8015                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8016                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8017                }
8018
8019                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8020                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8021                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8022                    if (extractLibs) {
8023                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8024                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8025                                useIsaSpecificSubdirs);
8026                    } else {
8027                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8028                    }
8029                }
8030
8031                maybeThrowExceptionForMultiArchCopy(
8032                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8033
8034                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8035                    if (extractLibs) {
8036                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8037                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8038                                useIsaSpecificSubdirs);
8039                    } else {
8040                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8041                    }
8042                }
8043
8044                maybeThrowExceptionForMultiArchCopy(
8045                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8046
8047                if (abi64 >= 0) {
8048                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8049                }
8050
8051                if (abi32 >= 0) {
8052                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8053                    if (abi64 >= 0) {
8054                        pkg.applicationInfo.secondaryCpuAbi = abi;
8055                    } else {
8056                        pkg.applicationInfo.primaryCpuAbi = abi;
8057                    }
8058                }
8059            } else {
8060                String[] abiList = (cpuAbiOverride != null) ?
8061                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8062
8063                // Enable gross and lame hacks for apps that are built with old
8064                // SDK tools. We must scan their APKs for renderscript bitcode and
8065                // not launch them if it's present. Don't bother checking on devices
8066                // that don't have 64 bit support.
8067                boolean needsRenderScriptOverride = false;
8068                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8069                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8070                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8071                    needsRenderScriptOverride = true;
8072                }
8073
8074                final int copyRet;
8075                if (extractLibs) {
8076                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8077                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8078                } else {
8079                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8080                }
8081
8082                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8083                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8084                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8085                }
8086
8087                if (copyRet >= 0) {
8088                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8089                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8090                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8091                } else if (needsRenderScriptOverride) {
8092                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8093                }
8094            }
8095        } catch (IOException ioe) {
8096            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8097        } finally {
8098            IoUtils.closeQuietly(handle);
8099        }
8100
8101        // Now that we've calculated the ABIs and determined if it's an internal app,
8102        // we will go ahead and populate the nativeLibraryPath.
8103        setNativeLibraryPaths(pkg);
8104    }
8105
8106    /**
8107     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8108     * i.e, so that all packages can be run inside a single process if required.
8109     *
8110     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8111     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8112     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8113     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8114     * updating a package that belongs to a shared user.
8115     *
8116     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8117     * adds unnecessary complexity.
8118     */
8119    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8120            PackageParser.Package scannedPackage, boolean bootComplete) {
8121        String requiredInstructionSet = null;
8122        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8123            requiredInstructionSet = VMRuntime.getInstructionSet(
8124                     scannedPackage.applicationInfo.primaryCpuAbi);
8125        }
8126
8127        PackageSetting requirer = null;
8128        for (PackageSetting ps : packagesForUser) {
8129            // If packagesForUser contains scannedPackage, we skip it. This will happen
8130            // when scannedPackage is an update of an existing package. Without this check,
8131            // we will never be able to change the ABI of any package belonging to a shared
8132            // user, even if it's compatible with other packages.
8133            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8134                if (ps.primaryCpuAbiString == null) {
8135                    continue;
8136                }
8137
8138                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8139                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8140                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8141                    // this but there's not much we can do.
8142                    String errorMessage = "Instruction set mismatch, "
8143                            + ((requirer == null) ? "[caller]" : requirer)
8144                            + " requires " + requiredInstructionSet + " whereas " + ps
8145                            + " requires " + instructionSet;
8146                    Slog.w(TAG, errorMessage);
8147                }
8148
8149                if (requiredInstructionSet == null) {
8150                    requiredInstructionSet = instructionSet;
8151                    requirer = ps;
8152                }
8153            }
8154        }
8155
8156        if (requiredInstructionSet != null) {
8157            String adjustedAbi;
8158            if (requirer != null) {
8159                // requirer != null implies that either scannedPackage was null or that scannedPackage
8160                // did not require an ABI, in which case we have to adjust scannedPackage to match
8161                // the ABI of the set (which is the same as requirer's ABI)
8162                adjustedAbi = requirer.primaryCpuAbiString;
8163                if (scannedPackage != null) {
8164                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8165                }
8166            } else {
8167                // requirer == null implies that we're updating all ABIs in the set to
8168                // match scannedPackage.
8169                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8170            }
8171
8172            for (PackageSetting ps : packagesForUser) {
8173                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8174                    if (ps.primaryCpuAbiString != null) {
8175                        continue;
8176                    }
8177
8178                    ps.primaryCpuAbiString = adjustedAbi;
8179                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8180                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8181                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8182                        mInstaller.rmdex(ps.codePathString,
8183                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8184                    }
8185                }
8186            }
8187        }
8188    }
8189
8190    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8191        synchronized (mPackages) {
8192            mResolverReplaced = true;
8193            // Set up information for custom user intent resolution activity.
8194            mResolveActivity.applicationInfo = pkg.applicationInfo;
8195            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8196            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8197            mResolveActivity.processName = pkg.applicationInfo.packageName;
8198            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8199            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8200                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8201            mResolveActivity.theme = 0;
8202            mResolveActivity.exported = true;
8203            mResolveActivity.enabled = true;
8204            mResolveInfo.activityInfo = mResolveActivity;
8205            mResolveInfo.priority = 0;
8206            mResolveInfo.preferredOrder = 0;
8207            mResolveInfo.match = 0;
8208            mResolveComponentName = mCustomResolverComponentName;
8209            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8210                    mResolveComponentName);
8211        }
8212    }
8213
8214    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8215        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8216
8217        // Set up information for ephemeral installer activity
8218        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8219        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8220        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8221        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8222        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8223        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8224                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8225        mEphemeralInstallerActivity.theme = 0;
8226        mEphemeralInstallerActivity.exported = true;
8227        mEphemeralInstallerActivity.enabled = true;
8228        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8229        mEphemeralInstallerInfo.priority = 0;
8230        mEphemeralInstallerInfo.preferredOrder = 0;
8231        mEphemeralInstallerInfo.match = 0;
8232
8233        if (DEBUG_EPHEMERAL) {
8234            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8235        }
8236    }
8237
8238    private static String calculateBundledApkRoot(final String codePathString) {
8239        final File codePath = new File(codePathString);
8240        final File codeRoot;
8241        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8242            codeRoot = Environment.getRootDirectory();
8243        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8244            codeRoot = Environment.getOemDirectory();
8245        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8246            codeRoot = Environment.getVendorDirectory();
8247        } else {
8248            // Unrecognized code path; take its top real segment as the apk root:
8249            // e.g. /something/app/blah.apk => /something
8250            try {
8251                File f = codePath.getCanonicalFile();
8252                File parent = f.getParentFile();    // non-null because codePath is a file
8253                File tmp;
8254                while ((tmp = parent.getParentFile()) != null) {
8255                    f = parent;
8256                    parent = tmp;
8257                }
8258                codeRoot = f;
8259                Slog.w(TAG, "Unrecognized code path "
8260                        + codePath + " - using " + codeRoot);
8261            } catch (IOException e) {
8262                // Can't canonicalize the code path -- shenanigans?
8263                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8264                return Environment.getRootDirectory().getPath();
8265            }
8266        }
8267        return codeRoot.getPath();
8268    }
8269
8270    /**
8271     * Derive and set the location of native libraries for the given package,
8272     * which varies depending on where and how the package was installed.
8273     */
8274    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8275        final ApplicationInfo info = pkg.applicationInfo;
8276        final String codePath = pkg.codePath;
8277        final File codeFile = new File(codePath);
8278        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8279        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8280
8281        info.nativeLibraryRootDir = null;
8282        info.nativeLibraryRootRequiresIsa = false;
8283        info.nativeLibraryDir = null;
8284        info.secondaryNativeLibraryDir = null;
8285
8286        if (isApkFile(codeFile)) {
8287            // Monolithic install
8288            if (bundledApp) {
8289                // If "/system/lib64/apkname" exists, assume that is the per-package
8290                // native library directory to use; otherwise use "/system/lib/apkname".
8291                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8292                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8293                        getPrimaryInstructionSet(info));
8294
8295                // This is a bundled system app so choose the path based on the ABI.
8296                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8297                // is just the default path.
8298                final String apkName = deriveCodePathName(codePath);
8299                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8300                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8301                        apkName).getAbsolutePath();
8302
8303                if (info.secondaryCpuAbi != null) {
8304                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8305                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8306                            secondaryLibDir, apkName).getAbsolutePath();
8307                }
8308            } else if (asecApp) {
8309                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8310                        .getAbsolutePath();
8311            } else {
8312                final String apkName = deriveCodePathName(codePath);
8313                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8314                        .getAbsolutePath();
8315            }
8316
8317            info.nativeLibraryRootRequiresIsa = false;
8318            info.nativeLibraryDir = info.nativeLibraryRootDir;
8319        } else {
8320            // Cluster install
8321            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8322            info.nativeLibraryRootRequiresIsa = true;
8323
8324            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8325                    getPrimaryInstructionSet(info)).getAbsolutePath();
8326
8327            if (info.secondaryCpuAbi != null) {
8328                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8329                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8330            }
8331        }
8332    }
8333
8334    /**
8335     * Calculate the abis and roots for a bundled app. These can uniquely
8336     * be determined from the contents of the system partition, i.e whether
8337     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8338     * of this information, and instead assume that the system was built
8339     * sensibly.
8340     */
8341    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8342                                           PackageSetting pkgSetting) {
8343        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8344
8345        // If "/system/lib64/apkname" exists, assume that is the per-package
8346        // native library directory to use; otherwise use "/system/lib/apkname".
8347        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8348        setBundledAppAbi(pkg, apkRoot, apkName);
8349        // pkgSetting might be null during rescan following uninstall of updates
8350        // to a bundled app, so accommodate that possibility.  The settings in
8351        // that case will be established later from the parsed package.
8352        //
8353        // If the settings aren't null, sync them up with what we've just derived.
8354        // note that apkRoot isn't stored in the package settings.
8355        if (pkgSetting != null) {
8356            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8357            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8358        }
8359    }
8360
8361    /**
8362     * Deduces the ABI of a bundled app and sets the relevant fields on the
8363     * parsed pkg object.
8364     *
8365     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8366     *        under which system libraries are installed.
8367     * @param apkName the name of the installed package.
8368     */
8369    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8370        final File codeFile = new File(pkg.codePath);
8371
8372        final boolean has64BitLibs;
8373        final boolean has32BitLibs;
8374        if (isApkFile(codeFile)) {
8375            // Monolithic install
8376            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8377            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8378        } else {
8379            // Cluster install
8380            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8381            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8382                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8383                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8384                has64BitLibs = (new File(rootDir, isa)).exists();
8385            } else {
8386                has64BitLibs = false;
8387            }
8388            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8389                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8390                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8391                has32BitLibs = (new File(rootDir, isa)).exists();
8392            } else {
8393                has32BitLibs = false;
8394            }
8395        }
8396
8397        if (has64BitLibs && !has32BitLibs) {
8398            // The package has 64 bit libs, but not 32 bit libs. Its primary
8399            // ABI should be 64 bit. We can safely assume here that the bundled
8400            // native libraries correspond to the most preferred ABI in the list.
8401
8402            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8403            pkg.applicationInfo.secondaryCpuAbi = null;
8404        } else if (has32BitLibs && !has64BitLibs) {
8405            // The package has 32 bit libs but not 64 bit libs. Its primary
8406            // ABI should be 32 bit.
8407
8408            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8409            pkg.applicationInfo.secondaryCpuAbi = null;
8410        } else if (has32BitLibs && has64BitLibs) {
8411            // The application has both 64 and 32 bit bundled libraries. We check
8412            // here that the app declares multiArch support, and warn if it doesn't.
8413            //
8414            // We will be lenient here and record both ABIs. The primary will be the
8415            // ABI that's higher on the list, i.e, a device that's configured to prefer
8416            // 64 bit apps will see a 64 bit primary ABI,
8417
8418            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8419                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8420            }
8421
8422            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8423                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8424                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8425            } else {
8426                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8427                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8428            }
8429        } else {
8430            pkg.applicationInfo.primaryCpuAbi = null;
8431            pkg.applicationInfo.secondaryCpuAbi = null;
8432        }
8433    }
8434
8435    private void killApplication(String pkgName, int appId, String reason) {
8436        // Request the ActivityManager to kill the process(only for existing packages)
8437        // so that we do not end up in a confused state while the user is still using the older
8438        // version of the application while the new one gets installed.
8439        IActivityManager am = ActivityManagerNative.getDefault();
8440        if (am != null) {
8441            try {
8442                am.killApplicationWithAppId(pkgName, appId, reason);
8443            } catch (RemoteException e) {
8444            }
8445        }
8446    }
8447
8448    void removePackageLI(PackageSetting ps, boolean chatty) {
8449        if (DEBUG_INSTALL) {
8450            if (chatty)
8451                Log.d(TAG, "Removing package " + ps.name);
8452        }
8453
8454        // writer
8455        synchronized (mPackages) {
8456            mPackages.remove(ps.name);
8457            final PackageParser.Package pkg = ps.pkg;
8458            if (pkg != null) {
8459                cleanPackageDataStructuresLILPw(pkg, chatty);
8460            }
8461        }
8462    }
8463
8464    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8465        if (DEBUG_INSTALL) {
8466            if (chatty)
8467                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8468        }
8469
8470        // writer
8471        synchronized (mPackages) {
8472            mPackages.remove(pkg.applicationInfo.packageName);
8473            cleanPackageDataStructuresLILPw(pkg, chatty);
8474        }
8475    }
8476
8477    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8478        int N = pkg.providers.size();
8479        StringBuilder r = null;
8480        int i;
8481        for (i=0; i<N; i++) {
8482            PackageParser.Provider p = pkg.providers.get(i);
8483            mProviders.removeProvider(p);
8484            if (p.info.authority == null) {
8485
8486                /* There was another ContentProvider with this authority when
8487                 * this app was installed so this authority is null,
8488                 * Ignore it as we don't have to unregister the provider.
8489                 */
8490                continue;
8491            }
8492            String names[] = p.info.authority.split(";");
8493            for (int j = 0; j < names.length; j++) {
8494                if (mProvidersByAuthority.get(names[j]) == p) {
8495                    mProvidersByAuthority.remove(names[j]);
8496                    if (DEBUG_REMOVE) {
8497                        if (chatty)
8498                            Log.d(TAG, "Unregistered content provider: " + names[j]
8499                                    + ", className = " + p.info.name + ", isSyncable = "
8500                                    + p.info.isSyncable);
8501                    }
8502                }
8503            }
8504            if (DEBUG_REMOVE && chatty) {
8505                if (r == null) {
8506                    r = new StringBuilder(256);
8507                } else {
8508                    r.append(' ');
8509                }
8510                r.append(p.info.name);
8511            }
8512        }
8513        if (r != null) {
8514            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8515        }
8516
8517        N = pkg.services.size();
8518        r = null;
8519        for (i=0; i<N; i++) {
8520            PackageParser.Service s = pkg.services.get(i);
8521            mServices.removeService(s);
8522            if (chatty) {
8523                if (r == null) {
8524                    r = new StringBuilder(256);
8525                } else {
8526                    r.append(' ');
8527                }
8528                r.append(s.info.name);
8529            }
8530        }
8531        if (r != null) {
8532            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8533        }
8534
8535        N = pkg.receivers.size();
8536        r = null;
8537        for (i=0; i<N; i++) {
8538            PackageParser.Activity a = pkg.receivers.get(i);
8539            mReceivers.removeActivity(a, "receiver");
8540            if (DEBUG_REMOVE && chatty) {
8541                if (r == null) {
8542                    r = new StringBuilder(256);
8543                } else {
8544                    r.append(' ');
8545                }
8546                r.append(a.info.name);
8547            }
8548        }
8549        if (r != null) {
8550            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8551        }
8552
8553        N = pkg.activities.size();
8554        r = null;
8555        for (i=0; i<N; i++) {
8556            PackageParser.Activity a = pkg.activities.get(i);
8557            mActivities.removeActivity(a, "activity");
8558            if (DEBUG_REMOVE && chatty) {
8559                if (r == null) {
8560                    r = new StringBuilder(256);
8561                } else {
8562                    r.append(' ');
8563                }
8564                r.append(a.info.name);
8565            }
8566        }
8567        if (r != null) {
8568            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8569        }
8570
8571        N = pkg.permissions.size();
8572        r = null;
8573        for (i=0; i<N; i++) {
8574            PackageParser.Permission p = pkg.permissions.get(i);
8575            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8576            if (bp == null) {
8577                bp = mSettings.mPermissionTrees.get(p.info.name);
8578            }
8579            if (bp != null && bp.perm == p) {
8580                bp.perm = null;
8581                if (DEBUG_REMOVE && chatty) {
8582                    if (r == null) {
8583                        r = new StringBuilder(256);
8584                    } else {
8585                        r.append(' ');
8586                    }
8587                    r.append(p.info.name);
8588                }
8589            }
8590            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8591                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8592                if (appOpPkgs != null) {
8593                    appOpPkgs.remove(pkg.packageName);
8594                }
8595            }
8596        }
8597        if (r != null) {
8598            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8599        }
8600
8601        N = pkg.requestedPermissions.size();
8602        r = null;
8603        for (i=0; i<N; i++) {
8604            String perm = pkg.requestedPermissions.get(i);
8605            BasePermission bp = mSettings.mPermissions.get(perm);
8606            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8607                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8608                if (appOpPkgs != null) {
8609                    appOpPkgs.remove(pkg.packageName);
8610                    if (appOpPkgs.isEmpty()) {
8611                        mAppOpPermissionPackages.remove(perm);
8612                    }
8613                }
8614            }
8615        }
8616        if (r != null) {
8617            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8618        }
8619
8620        N = pkg.instrumentation.size();
8621        r = null;
8622        for (i=0; i<N; i++) {
8623            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8624            mInstrumentation.remove(a.getComponentName());
8625            if (DEBUG_REMOVE && chatty) {
8626                if (r == null) {
8627                    r = new StringBuilder(256);
8628                } else {
8629                    r.append(' ');
8630                }
8631                r.append(a.info.name);
8632            }
8633        }
8634        if (r != null) {
8635            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8636        }
8637
8638        r = null;
8639        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8640            // Only system apps can hold shared libraries.
8641            if (pkg.libraryNames != null) {
8642                for (i=0; i<pkg.libraryNames.size(); i++) {
8643                    String name = pkg.libraryNames.get(i);
8644                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8645                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8646                        mSharedLibraries.remove(name);
8647                        if (DEBUG_REMOVE && chatty) {
8648                            if (r == null) {
8649                                r = new StringBuilder(256);
8650                            } else {
8651                                r.append(' ');
8652                            }
8653                            r.append(name);
8654                        }
8655                    }
8656                }
8657            }
8658        }
8659        if (r != null) {
8660            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8661        }
8662    }
8663
8664    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8665        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8666            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8667                return true;
8668            }
8669        }
8670        return false;
8671    }
8672
8673    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8674    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8675    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8676
8677    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8678            int flags) {
8679        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8680        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8681    }
8682
8683    private void updatePermissionsLPw(String changingPkg,
8684            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8685        // Make sure there are no dangling permission trees.
8686        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8687        while (it.hasNext()) {
8688            final BasePermission bp = it.next();
8689            if (bp.packageSetting == null) {
8690                // We may not yet have parsed the package, so just see if
8691                // we still know about its settings.
8692                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8693            }
8694            if (bp.packageSetting == null) {
8695                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8696                        + " from package " + bp.sourcePackage);
8697                it.remove();
8698            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8699                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8700                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8701                            + " from package " + bp.sourcePackage);
8702                    flags |= UPDATE_PERMISSIONS_ALL;
8703                    it.remove();
8704                }
8705            }
8706        }
8707
8708        // Make sure all dynamic permissions have been assigned to a package,
8709        // and make sure there are no dangling permissions.
8710        it = mSettings.mPermissions.values().iterator();
8711        while (it.hasNext()) {
8712            final BasePermission bp = it.next();
8713            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8714                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8715                        + bp.name + " pkg=" + bp.sourcePackage
8716                        + " info=" + bp.pendingInfo);
8717                if (bp.packageSetting == null && bp.pendingInfo != null) {
8718                    final BasePermission tree = findPermissionTreeLP(bp.name);
8719                    if (tree != null && tree.perm != null) {
8720                        bp.packageSetting = tree.packageSetting;
8721                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8722                                new PermissionInfo(bp.pendingInfo));
8723                        bp.perm.info.packageName = tree.perm.info.packageName;
8724                        bp.perm.info.name = bp.name;
8725                        bp.uid = tree.uid;
8726                    }
8727                }
8728            }
8729            if (bp.packageSetting == null) {
8730                // We may not yet have parsed the package, so just see if
8731                // we still know about its settings.
8732                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8733            }
8734            if (bp.packageSetting == null) {
8735                Slog.w(TAG, "Removing dangling permission: " + bp.name
8736                        + " from package " + bp.sourcePackage);
8737                it.remove();
8738            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8739                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8740                    Slog.i(TAG, "Removing old permission: " + bp.name
8741                            + " from package " + bp.sourcePackage);
8742                    flags |= UPDATE_PERMISSIONS_ALL;
8743                    it.remove();
8744                }
8745            }
8746        }
8747
8748        // Now update the permissions for all packages, in particular
8749        // replace the granted permissions of the system packages.
8750        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8751            for (PackageParser.Package pkg : mPackages.values()) {
8752                if (pkg != pkgInfo) {
8753                    // Only replace for packages on requested volume
8754                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8755                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8756                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8757                    grantPermissionsLPw(pkg, replace, changingPkg);
8758                }
8759            }
8760        }
8761
8762        if (pkgInfo != null) {
8763            // Only replace for packages on requested volume
8764            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8765            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8766                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8767            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8768        }
8769    }
8770
8771    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8772            String packageOfInterest) {
8773        // IMPORTANT: There are two types of permissions: install and runtime.
8774        // Install time permissions are granted when the app is installed to
8775        // all device users and users added in the future. Runtime permissions
8776        // are granted at runtime explicitly to specific users. Normal and signature
8777        // protected permissions are install time permissions. Dangerous permissions
8778        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8779        // otherwise they are runtime permissions. This function does not manage
8780        // runtime permissions except for the case an app targeting Lollipop MR1
8781        // being upgraded to target a newer SDK, in which case dangerous permissions
8782        // are transformed from install time to runtime ones.
8783
8784        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8785        if (ps == null) {
8786            return;
8787        }
8788
8789        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8790
8791        PermissionsState permissionsState = ps.getPermissionsState();
8792        PermissionsState origPermissions = permissionsState;
8793
8794        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8795
8796        boolean runtimePermissionsRevoked = false;
8797        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8798
8799        boolean changedInstallPermission = false;
8800
8801        if (replace) {
8802            ps.installPermissionsFixed = false;
8803            if (!ps.isSharedUser()) {
8804                origPermissions = new PermissionsState(permissionsState);
8805                permissionsState.reset();
8806            } else {
8807                // We need to know only about runtime permission changes since the
8808                // calling code always writes the install permissions state but
8809                // the runtime ones are written only if changed. The only cases of
8810                // changed runtime permissions here are promotion of an install to
8811                // runtime and revocation of a runtime from a shared user.
8812                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8813                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8814                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8815                    runtimePermissionsRevoked = true;
8816                }
8817            }
8818        }
8819
8820        permissionsState.setGlobalGids(mGlobalGids);
8821
8822        final int N = pkg.requestedPermissions.size();
8823        for (int i=0; i<N; i++) {
8824            final String name = pkg.requestedPermissions.get(i);
8825            final BasePermission bp = mSettings.mPermissions.get(name);
8826
8827            if (DEBUG_INSTALL) {
8828                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8829            }
8830
8831            if (bp == null || bp.packageSetting == null) {
8832                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8833                    Slog.w(TAG, "Unknown permission " + name
8834                            + " in package " + pkg.packageName);
8835                }
8836                continue;
8837            }
8838
8839            final String perm = bp.name;
8840            boolean allowedSig = false;
8841            int grant = GRANT_DENIED;
8842
8843            // Keep track of app op permissions.
8844            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8845                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8846                if (pkgs == null) {
8847                    pkgs = new ArraySet<>();
8848                    mAppOpPermissionPackages.put(bp.name, pkgs);
8849                }
8850                pkgs.add(pkg.packageName);
8851            }
8852
8853            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8854            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8855                    >= Build.VERSION_CODES.M;
8856            switch (level) {
8857                case PermissionInfo.PROTECTION_NORMAL: {
8858                    // For all apps normal permissions are install time ones.
8859                    grant = GRANT_INSTALL;
8860                } break;
8861
8862                case PermissionInfo.PROTECTION_DANGEROUS: {
8863                    // If a permission review is required for legacy apps we represent
8864                    // their permissions as always granted runtime ones since we need
8865                    // to keep the review required permission flag per user while an
8866                    // install permission's state is shared across all users.
8867                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8868                        // For legacy apps dangerous permissions are install time ones.
8869                        grant = GRANT_INSTALL;
8870                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8871                        // For legacy apps that became modern, install becomes runtime.
8872                        grant = GRANT_UPGRADE;
8873                    } else if (mPromoteSystemApps
8874                            && isSystemApp(ps)
8875                            && mExistingSystemPackages.contains(ps.name)) {
8876                        // For legacy system apps, install becomes runtime.
8877                        // We cannot check hasInstallPermission() for system apps since those
8878                        // permissions were granted implicitly and not persisted pre-M.
8879                        grant = GRANT_UPGRADE;
8880                    } else {
8881                        // For modern apps keep runtime permissions unchanged.
8882                        grant = GRANT_RUNTIME;
8883                    }
8884                } break;
8885
8886                case PermissionInfo.PROTECTION_SIGNATURE: {
8887                    // For all apps signature permissions are install time ones.
8888                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8889                    if (allowedSig) {
8890                        grant = GRANT_INSTALL;
8891                    }
8892                } break;
8893            }
8894
8895            if (DEBUG_INSTALL) {
8896                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8897            }
8898
8899            if (grant != GRANT_DENIED) {
8900                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8901                    // If this is an existing, non-system package, then
8902                    // we can't add any new permissions to it.
8903                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8904                        // Except...  if this is a permission that was added
8905                        // to the platform (note: need to only do this when
8906                        // updating the platform).
8907                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8908                            grant = GRANT_DENIED;
8909                        }
8910                    }
8911                }
8912
8913                switch (grant) {
8914                    case GRANT_INSTALL: {
8915                        // Revoke this as runtime permission to handle the case of
8916                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8917                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8918                            if (origPermissions.getRuntimePermissionState(
8919                                    bp.name, userId) != null) {
8920                                // Revoke the runtime permission and clear the flags.
8921                                origPermissions.revokeRuntimePermission(bp, userId);
8922                                origPermissions.updatePermissionFlags(bp, userId,
8923                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8924                                // If we revoked a permission permission, we have to write.
8925                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8926                                        changedRuntimePermissionUserIds, userId);
8927                            }
8928                        }
8929                        // Grant an install permission.
8930                        if (permissionsState.grantInstallPermission(bp) !=
8931                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8932                            changedInstallPermission = true;
8933                        }
8934                    } break;
8935
8936                    case GRANT_RUNTIME: {
8937                        // Grant previously granted runtime permissions.
8938                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8939                            PermissionState permissionState = origPermissions
8940                                    .getRuntimePermissionState(bp.name, userId);
8941                            int flags = permissionState != null
8942                                    ? permissionState.getFlags() : 0;
8943                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8944                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8945                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8946                                    // If we cannot put the permission as it was, we have to write.
8947                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8948                                            changedRuntimePermissionUserIds, userId);
8949                                }
8950                                // If the app supports runtime permissions no need for a review.
8951                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8952                                        && appSupportsRuntimePermissions
8953                                        && (flags & PackageManager
8954                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8955                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8956                                    // Since we changed the flags, we have to write.
8957                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8958                                            changedRuntimePermissionUserIds, userId);
8959                                }
8960                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8961                                    && !appSupportsRuntimePermissions) {
8962                                // For legacy apps that need a permission review, every new
8963                                // runtime permission is granted but it is pending a review.
8964                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8965                                    permissionsState.grantRuntimePermission(bp, userId);
8966                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8967                                    // We changed the permission and flags, hence have to write.
8968                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8969                                            changedRuntimePermissionUserIds, userId);
8970                                }
8971                            }
8972                            // Propagate the permission flags.
8973                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8974                        }
8975                    } break;
8976
8977                    case GRANT_UPGRADE: {
8978                        // Grant runtime permissions for a previously held install permission.
8979                        PermissionState permissionState = origPermissions
8980                                .getInstallPermissionState(bp.name);
8981                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8982
8983                        if (origPermissions.revokeInstallPermission(bp)
8984                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8985                            // We will be transferring the permission flags, so clear them.
8986                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8987                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8988                            changedInstallPermission = true;
8989                        }
8990
8991                        // If the permission is not to be promoted to runtime we ignore it and
8992                        // also its other flags as they are not applicable to install permissions.
8993                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8994                            for (int userId : currentUserIds) {
8995                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8996                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8997                                    // Transfer the permission flags.
8998                                    permissionsState.updatePermissionFlags(bp, userId,
8999                                            flags, flags);
9000                                    // If we granted the permission, we have to write.
9001                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9002                                            changedRuntimePermissionUserIds, userId);
9003                                }
9004                            }
9005                        }
9006                    } break;
9007
9008                    default: {
9009                        if (packageOfInterest == null
9010                                || packageOfInterest.equals(pkg.packageName)) {
9011                            Slog.w(TAG, "Not granting permission " + perm
9012                                    + " to package " + pkg.packageName
9013                                    + " because it was previously installed without");
9014                        }
9015                    } break;
9016                }
9017            } else {
9018                if (permissionsState.revokeInstallPermission(bp) !=
9019                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9020                    // Also drop the permission flags.
9021                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9022                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9023                    changedInstallPermission = true;
9024                    Slog.i(TAG, "Un-granting permission " + perm
9025                            + " from package " + pkg.packageName
9026                            + " (protectionLevel=" + bp.protectionLevel
9027                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9028                            + ")");
9029                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9030                    // Don't print warning for app op permissions, since it is fine for them
9031                    // not to be granted, there is a UI for the user to decide.
9032                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9033                        Slog.w(TAG, "Not granting permission " + perm
9034                                + " to package " + pkg.packageName
9035                                + " (protectionLevel=" + bp.protectionLevel
9036                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9037                                + ")");
9038                    }
9039                }
9040            }
9041        }
9042
9043        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9044                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9045            // This is the first that we have heard about this package, so the
9046            // permissions we have now selected are fixed until explicitly
9047            // changed.
9048            ps.installPermissionsFixed = true;
9049        }
9050
9051        // Persist the runtime permissions state for users with changes. If permissions
9052        // were revoked because no app in the shared user declares them we have to
9053        // write synchronously to avoid losing runtime permissions state.
9054        for (int userId : changedRuntimePermissionUserIds) {
9055            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9056        }
9057
9058        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9059    }
9060
9061    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9062        boolean allowed = false;
9063        final int NP = PackageParser.NEW_PERMISSIONS.length;
9064        for (int ip=0; ip<NP; ip++) {
9065            final PackageParser.NewPermissionInfo npi
9066                    = PackageParser.NEW_PERMISSIONS[ip];
9067            if (npi.name.equals(perm)
9068                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9069                allowed = true;
9070                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9071                        + pkg.packageName);
9072                break;
9073            }
9074        }
9075        return allowed;
9076    }
9077
9078    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9079            BasePermission bp, PermissionsState origPermissions) {
9080        boolean allowed;
9081        allowed = (compareSignatures(
9082                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9083                        == PackageManager.SIGNATURE_MATCH)
9084                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9085                        == PackageManager.SIGNATURE_MATCH);
9086        if (!allowed && (bp.protectionLevel
9087                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9088            if (isSystemApp(pkg)) {
9089                // For updated system applications, a system permission
9090                // is granted only if it had been defined by the original application.
9091                if (pkg.isUpdatedSystemApp()) {
9092                    final PackageSetting sysPs = mSettings
9093                            .getDisabledSystemPkgLPr(pkg.packageName);
9094                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9095                        // If the original was granted this permission, we take
9096                        // that grant decision as read and propagate it to the
9097                        // update.
9098                        if (sysPs.isPrivileged()) {
9099                            allowed = true;
9100                        }
9101                    } else {
9102                        // The system apk may have been updated with an older
9103                        // version of the one on the data partition, but which
9104                        // granted a new system permission that it didn't have
9105                        // before.  In this case we do want to allow the app to
9106                        // now get the new permission if the ancestral apk is
9107                        // privileged to get it.
9108                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9109                            for (int j=0;
9110                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9111                                if (perm.equals(
9112                                        sysPs.pkg.requestedPermissions.get(j))) {
9113                                    allowed = true;
9114                                    break;
9115                                }
9116                            }
9117                        }
9118                    }
9119                } else {
9120                    allowed = isPrivilegedApp(pkg);
9121                }
9122            }
9123        }
9124        if (!allowed) {
9125            if (!allowed && (bp.protectionLevel
9126                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9127                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9128                // If this was a previously normal/dangerous permission that got moved
9129                // to a system permission as part of the runtime permission redesign, then
9130                // we still want to blindly grant it to old apps.
9131                allowed = true;
9132            }
9133            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9134                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9135                // If this permission is to be granted to the system installer and
9136                // this app is an installer, then it gets the permission.
9137                allowed = true;
9138            }
9139            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9140                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9141                // If this permission is to be granted to the system verifier and
9142                // this app is a verifier, then it gets the permission.
9143                allowed = true;
9144            }
9145            if (!allowed && (bp.protectionLevel
9146                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9147                    && isSystemApp(pkg)) {
9148                // Any pre-installed system app is allowed to get this permission.
9149                allowed = true;
9150            }
9151            if (!allowed && (bp.protectionLevel
9152                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9153                // For development permissions, a development permission
9154                // is granted only if it was already granted.
9155                allowed = origPermissions.hasInstallPermission(perm);
9156            }
9157        }
9158        return allowed;
9159    }
9160
9161    final class ActivityIntentResolver
9162            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9163        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9164                boolean defaultOnly, int userId) {
9165            if (!sUserManager.exists(userId)) return null;
9166            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9167            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9168        }
9169
9170        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9171                int userId) {
9172            if (!sUserManager.exists(userId)) return null;
9173            mFlags = flags;
9174            return super.queryIntent(intent, resolvedType,
9175                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9176        }
9177
9178        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9179                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9180            if (!sUserManager.exists(userId)) return null;
9181            if (packageActivities == null) {
9182                return null;
9183            }
9184            mFlags = flags;
9185            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9186            final int N = packageActivities.size();
9187            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9188                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9189
9190            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9191            for (int i = 0; i < N; ++i) {
9192                intentFilters = packageActivities.get(i).intents;
9193                if (intentFilters != null && intentFilters.size() > 0) {
9194                    PackageParser.ActivityIntentInfo[] array =
9195                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9196                    intentFilters.toArray(array);
9197                    listCut.add(array);
9198                }
9199            }
9200            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9201        }
9202
9203        public final void addActivity(PackageParser.Activity a, String type) {
9204            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9205            mActivities.put(a.getComponentName(), a);
9206            if (DEBUG_SHOW_INFO)
9207                Log.v(
9208                TAG, "  " + type + " " +
9209                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9210            if (DEBUG_SHOW_INFO)
9211                Log.v(TAG, "    Class=" + a.info.name);
9212            final int NI = a.intents.size();
9213            for (int j=0; j<NI; j++) {
9214                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9215                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9216                    intent.setPriority(0);
9217                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9218                            + a.className + " with priority > 0, forcing to 0");
9219                }
9220                if (DEBUG_SHOW_INFO) {
9221                    Log.v(TAG, "    IntentFilter:");
9222                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9223                }
9224                if (!intent.debugCheck()) {
9225                    Log.w(TAG, "==> For Activity " + a.info.name);
9226                }
9227                addFilter(intent);
9228            }
9229        }
9230
9231        public final void removeActivity(PackageParser.Activity a, String type) {
9232            mActivities.remove(a.getComponentName());
9233            if (DEBUG_SHOW_INFO) {
9234                Log.v(TAG, "  " + type + " "
9235                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9236                                : a.info.name) + ":");
9237                Log.v(TAG, "    Class=" + a.info.name);
9238            }
9239            final int NI = a.intents.size();
9240            for (int j=0; j<NI; j++) {
9241                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9242                if (DEBUG_SHOW_INFO) {
9243                    Log.v(TAG, "    IntentFilter:");
9244                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9245                }
9246                removeFilter(intent);
9247            }
9248        }
9249
9250        @Override
9251        protected boolean allowFilterResult(
9252                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9253            ActivityInfo filterAi = filter.activity.info;
9254            for (int i=dest.size()-1; i>=0; i--) {
9255                ActivityInfo destAi = dest.get(i).activityInfo;
9256                if (destAi.name == filterAi.name
9257                        && destAi.packageName == filterAi.packageName) {
9258                    return false;
9259                }
9260            }
9261            return true;
9262        }
9263
9264        @Override
9265        protected ActivityIntentInfo[] newArray(int size) {
9266            return new ActivityIntentInfo[size];
9267        }
9268
9269        @Override
9270        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9271            if (!sUserManager.exists(userId)) return true;
9272            PackageParser.Package p = filter.activity.owner;
9273            if (p != null) {
9274                PackageSetting ps = (PackageSetting)p.mExtras;
9275                if (ps != null) {
9276                    // System apps are never considered stopped for purposes of
9277                    // filtering, because there may be no way for the user to
9278                    // actually re-launch them.
9279                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9280                            && ps.getStopped(userId);
9281                }
9282            }
9283            return false;
9284        }
9285
9286        @Override
9287        protected boolean isPackageForFilter(String packageName,
9288                PackageParser.ActivityIntentInfo info) {
9289            return packageName.equals(info.activity.owner.packageName);
9290        }
9291
9292        @Override
9293        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9294                int match, int userId) {
9295            if (!sUserManager.exists(userId)) return null;
9296            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9297                return null;
9298            }
9299            final PackageParser.Activity activity = info.activity;
9300            if (mSafeMode && (activity.info.applicationInfo.flags
9301                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9302                return null;
9303            }
9304            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9305            if (ps == null) {
9306                return null;
9307            }
9308            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9309                    ps.readUserState(userId), userId);
9310            if (ai == null) {
9311                return null;
9312            }
9313            final ResolveInfo res = new ResolveInfo();
9314            res.activityInfo = ai;
9315            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9316                res.filter = info;
9317            }
9318            if (info != null) {
9319                res.handleAllWebDataURI = info.handleAllWebDataURI();
9320            }
9321            res.priority = info.getPriority();
9322            res.preferredOrder = activity.owner.mPreferredOrder;
9323            //System.out.println("Result: " + res.activityInfo.className +
9324            //                   " = " + res.priority);
9325            res.match = match;
9326            res.isDefault = info.hasDefault;
9327            res.labelRes = info.labelRes;
9328            res.nonLocalizedLabel = info.nonLocalizedLabel;
9329            if (userNeedsBadging(userId)) {
9330                res.noResourceId = true;
9331            } else {
9332                res.icon = info.icon;
9333            }
9334            res.iconResourceId = info.icon;
9335            res.system = res.activityInfo.applicationInfo.isSystemApp();
9336            return res;
9337        }
9338
9339        @Override
9340        protected void sortResults(List<ResolveInfo> results) {
9341            Collections.sort(results, mResolvePrioritySorter);
9342        }
9343
9344        @Override
9345        protected void dumpFilter(PrintWriter out, String prefix,
9346                PackageParser.ActivityIntentInfo filter) {
9347            out.print(prefix); out.print(
9348                    Integer.toHexString(System.identityHashCode(filter.activity)));
9349                    out.print(' ');
9350                    filter.activity.printComponentShortName(out);
9351                    out.print(" filter ");
9352                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9353        }
9354
9355        @Override
9356        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9357            return filter.activity;
9358        }
9359
9360        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9361            PackageParser.Activity activity = (PackageParser.Activity)label;
9362            out.print(prefix); out.print(
9363                    Integer.toHexString(System.identityHashCode(activity)));
9364                    out.print(' ');
9365                    activity.printComponentShortName(out);
9366            if (count > 1) {
9367                out.print(" ("); out.print(count); out.print(" filters)");
9368            }
9369            out.println();
9370        }
9371
9372//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9373//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9374//            final List<ResolveInfo> retList = Lists.newArrayList();
9375//            while (i.hasNext()) {
9376//                final ResolveInfo resolveInfo = i.next();
9377//                if (isEnabledLP(resolveInfo.activityInfo)) {
9378//                    retList.add(resolveInfo);
9379//                }
9380//            }
9381//            return retList;
9382//        }
9383
9384        // Keys are String (activity class name), values are Activity.
9385        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9386                = new ArrayMap<ComponentName, PackageParser.Activity>();
9387        private int mFlags;
9388    }
9389
9390    private final class ServiceIntentResolver
9391            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9392        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9393                boolean defaultOnly, int userId) {
9394            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9395            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9396        }
9397
9398        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9399                int userId) {
9400            if (!sUserManager.exists(userId)) return null;
9401            mFlags = flags;
9402            return super.queryIntent(intent, resolvedType,
9403                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9404        }
9405
9406        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9407                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9408            if (!sUserManager.exists(userId)) return null;
9409            if (packageServices == null) {
9410                return null;
9411            }
9412            mFlags = flags;
9413            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9414            final int N = packageServices.size();
9415            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9416                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9417
9418            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9419            for (int i = 0; i < N; ++i) {
9420                intentFilters = packageServices.get(i).intents;
9421                if (intentFilters != null && intentFilters.size() > 0) {
9422                    PackageParser.ServiceIntentInfo[] array =
9423                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9424                    intentFilters.toArray(array);
9425                    listCut.add(array);
9426                }
9427            }
9428            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9429        }
9430
9431        public final void addService(PackageParser.Service s) {
9432            mServices.put(s.getComponentName(), s);
9433            if (DEBUG_SHOW_INFO) {
9434                Log.v(TAG, "  "
9435                        + (s.info.nonLocalizedLabel != null
9436                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9437                Log.v(TAG, "    Class=" + s.info.name);
9438            }
9439            final int NI = s.intents.size();
9440            int j;
9441            for (j=0; j<NI; j++) {
9442                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9443                if (DEBUG_SHOW_INFO) {
9444                    Log.v(TAG, "    IntentFilter:");
9445                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9446                }
9447                if (!intent.debugCheck()) {
9448                    Log.w(TAG, "==> For Service " + s.info.name);
9449                }
9450                addFilter(intent);
9451            }
9452        }
9453
9454        public final void removeService(PackageParser.Service s) {
9455            mServices.remove(s.getComponentName());
9456            if (DEBUG_SHOW_INFO) {
9457                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9458                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9459                Log.v(TAG, "    Class=" + s.info.name);
9460            }
9461            final int NI = s.intents.size();
9462            int j;
9463            for (j=0; j<NI; j++) {
9464                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9465                if (DEBUG_SHOW_INFO) {
9466                    Log.v(TAG, "    IntentFilter:");
9467                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9468                }
9469                removeFilter(intent);
9470            }
9471        }
9472
9473        @Override
9474        protected boolean allowFilterResult(
9475                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9476            ServiceInfo filterSi = filter.service.info;
9477            for (int i=dest.size()-1; i>=0; i--) {
9478                ServiceInfo destAi = dest.get(i).serviceInfo;
9479                if (destAi.name == filterSi.name
9480                        && destAi.packageName == filterSi.packageName) {
9481                    return false;
9482                }
9483            }
9484            return true;
9485        }
9486
9487        @Override
9488        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9489            return new PackageParser.ServiceIntentInfo[size];
9490        }
9491
9492        @Override
9493        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9494            if (!sUserManager.exists(userId)) return true;
9495            PackageParser.Package p = filter.service.owner;
9496            if (p != null) {
9497                PackageSetting ps = (PackageSetting)p.mExtras;
9498                if (ps != null) {
9499                    // System apps are never considered stopped for purposes of
9500                    // filtering, because there may be no way for the user to
9501                    // actually re-launch them.
9502                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9503                            && ps.getStopped(userId);
9504                }
9505            }
9506            return false;
9507        }
9508
9509        @Override
9510        protected boolean isPackageForFilter(String packageName,
9511                PackageParser.ServiceIntentInfo info) {
9512            return packageName.equals(info.service.owner.packageName);
9513        }
9514
9515        @Override
9516        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9517                int match, int userId) {
9518            if (!sUserManager.exists(userId)) return null;
9519            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9520            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9521                return null;
9522            }
9523            final PackageParser.Service service = info.service;
9524            if (mSafeMode && (service.info.applicationInfo.flags
9525                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9526                return null;
9527            }
9528            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9529            if (ps == null) {
9530                return null;
9531            }
9532            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9533                    ps.readUserState(userId), userId);
9534            if (si == null) {
9535                return null;
9536            }
9537            final ResolveInfo res = new ResolveInfo();
9538            res.serviceInfo = si;
9539            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9540                res.filter = filter;
9541            }
9542            res.priority = info.getPriority();
9543            res.preferredOrder = service.owner.mPreferredOrder;
9544            res.match = match;
9545            res.isDefault = info.hasDefault;
9546            res.labelRes = info.labelRes;
9547            res.nonLocalizedLabel = info.nonLocalizedLabel;
9548            res.icon = info.icon;
9549            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9550            return res;
9551        }
9552
9553        @Override
9554        protected void sortResults(List<ResolveInfo> results) {
9555            Collections.sort(results, mResolvePrioritySorter);
9556        }
9557
9558        @Override
9559        protected void dumpFilter(PrintWriter out, String prefix,
9560                PackageParser.ServiceIntentInfo filter) {
9561            out.print(prefix); out.print(
9562                    Integer.toHexString(System.identityHashCode(filter.service)));
9563                    out.print(' ');
9564                    filter.service.printComponentShortName(out);
9565                    out.print(" filter ");
9566                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9567        }
9568
9569        @Override
9570        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9571            return filter.service;
9572        }
9573
9574        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9575            PackageParser.Service service = (PackageParser.Service)label;
9576            out.print(prefix); out.print(
9577                    Integer.toHexString(System.identityHashCode(service)));
9578                    out.print(' ');
9579                    service.printComponentShortName(out);
9580            if (count > 1) {
9581                out.print(" ("); out.print(count); out.print(" filters)");
9582            }
9583            out.println();
9584        }
9585
9586//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9587//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9588//            final List<ResolveInfo> retList = Lists.newArrayList();
9589//            while (i.hasNext()) {
9590//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9591//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9592//                    retList.add(resolveInfo);
9593//                }
9594//            }
9595//            return retList;
9596//        }
9597
9598        // Keys are String (activity class name), values are Activity.
9599        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9600                = new ArrayMap<ComponentName, PackageParser.Service>();
9601        private int mFlags;
9602    };
9603
9604    private final class ProviderIntentResolver
9605            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9606        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9607                boolean defaultOnly, int userId) {
9608            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9609            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9610        }
9611
9612        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9613                int userId) {
9614            if (!sUserManager.exists(userId))
9615                return null;
9616            mFlags = flags;
9617            return super.queryIntent(intent, resolvedType,
9618                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9619        }
9620
9621        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9622                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9623            if (!sUserManager.exists(userId))
9624                return null;
9625            if (packageProviders == null) {
9626                return null;
9627            }
9628            mFlags = flags;
9629            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9630            final int N = packageProviders.size();
9631            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9632                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9633
9634            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9635            for (int i = 0; i < N; ++i) {
9636                intentFilters = packageProviders.get(i).intents;
9637                if (intentFilters != null && intentFilters.size() > 0) {
9638                    PackageParser.ProviderIntentInfo[] array =
9639                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9640                    intentFilters.toArray(array);
9641                    listCut.add(array);
9642                }
9643            }
9644            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9645        }
9646
9647        public final void addProvider(PackageParser.Provider p) {
9648            if (mProviders.containsKey(p.getComponentName())) {
9649                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9650                return;
9651            }
9652
9653            mProviders.put(p.getComponentName(), p);
9654            if (DEBUG_SHOW_INFO) {
9655                Log.v(TAG, "  "
9656                        + (p.info.nonLocalizedLabel != null
9657                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9658                Log.v(TAG, "    Class=" + p.info.name);
9659            }
9660            final int NI = p.intents.size();
9661            int j;
9662            for (j = 0; j < NI; j++) {
9663                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9664                if (DEBUG_SHOW_INFO) {
9665                    Log.v(TAG, "    IntentFilter:");
9666                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9667                }
9668                if (!intent.debugCheck()) {
9669                    Log.w(TAG, "==> For Provider " + p.info.name);
9670                }
9671                addFilter(intent);
9672            }
9673        }
9674
9675        public final void removeProvider(PackageParser.Provider p) {
9676            mProviders.remove(p.getComponentName());
9677            if (DEBUG_SHOW_INFO) {
9678                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9679                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9680                Log.v(TAG, "    Class=" + p.info.name);
9681            }
9682            final int NI = p.intents.size();
9683            int j;
9684            for (j = 0; j < NI; j++) {
9685                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9686                if (DEBUG_SHOW_INFO) {
9687                    Log.v(TAG, "    IntentFilter:");
9688                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9689                }
9690                removeFilter(intent);
9691            }
9692        }
9693
9694        @Override
9695        protected boolean allowFilterResult(
9696                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9697            ProviderInfo filterPi = filter.provider.info;
9698            for (int i = dest.size() - 1; i >= 0; i--) {
9699                ProviderInfo destPi = dest.get(i).providerInfo;
9700                if (destPi.name == filterPi.name
9701                        && destPi.packageName == filterPi.packageName) {
9702                    return false;
9703                }
9704            }
9705            return true;
9706        }
9707
9708        @Override
9709        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9710            return new PackageParser.ProviderIntentInfo[size];
9711        }
9712
9713        @Override
9714        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9715            if (!sUserManager.exists(userId))
9716                return true;
9717            PackageParser.Package p = filter.provider.owner;
9718            if (p != null) {
9719                PackageSetting ps = (PackageSetting) p.mExtras;
9720                if (ps != null) {
9721                    // System apps are never considered stopped for purposes of
9722                    // filtering, because there may be no way for the user to
9723                    // actually re-launch them.
9724                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9725                            && ps.getStopped(userId);
9726                }
9727            }
9728            return false;
9729        }
9730
9731        @Override
9732        protected boolean isPackageForFilter(String packageName,
9733                PackageParser.ProviderIntentInfo info) {
9734            return packageName.equals(info.provider.owner.packageName);
9735        }
9736
9737        @Override
9738        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9739                int match, int userId) {
9740            if (!sUserManager.exists(userId))
9741                return null;
9742            final PackageParser.ProviderIntentInfo info = filter;
9743            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9744                return null;
9745            }
9746            final PackageParser.Provider provider = info.provider;
9747            if (mSafeMode && (provider.info.applicationInfo.flags
9748                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9749                return null;
9750            }
9751            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9752            if (ps == null) {
9753                return null;
9754            }
9755            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9756                    ps.readUserState(userId), userId);
9757            if (pi == null) {
9758                return null;
9759            }
9760            final ResolveInfo res = new ResolveInfo();
9761            res.providerInfo = pi;
9762            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9763                res.filter = filter;
9764            }
9765            res.priority = info.getPriority();
9766            res.preferredOrder = provider.owner.mPreferredOrder;
9767            res.match = match;
9768            res.isDefault = info.hasDefault;
9769            res.labelRes = info.labelRes;
9770            res.nonLocalizedLabel = info.nonLocalizedLabel;
9771            res.icon = info.icon;
9772            res.system = res.providerInfo.applicationInfo.isSystemApp();
9773            return res;
9774        }
9775
9776        @Override
9777        protected void sortResults(List<ResolveInfo> results) {
9778            Collections.sort(results, mResolvePrioritySorter);
9779        }
9780
9781        @Override
9782        protected void dumpFilter(PrintWriter out, String prefix,
9783                PackageParser.ProviderIntentInfo filter) {
9784            out.print(prefix);
9785            out.print(
9786                    Integer.toHexString(System.identityHashCode(filter.provider)));
9787            out.print(' ');
9788            filter.provider.printComponentShortName(out);
9789            out.print(" filter ");
9790            out.println(Integer.toHexString(System.identityHashCode(filter)));
9791        }
9792
9793        @Override
9794        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9795            return filter.provider;
9796        }
9797
9798        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9799            PackageParser.Provider provider = (PackageParser.Provider)label;
9800            out.print(prefix); out.print(
9801                    Integer.toHexString(System.identityHashCode(provider)));
9802                    out.print(' ');
9803                    provider.printComponentShortName(out);
9804            if (count > 1) {
9805                out.print(" ("); out.print(count); out.print(" filters)");
9806            }
9807            out.println();
9808        }
9809
9810        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9811                = new ArrayMap<ComponentName, PackageParser.Provider>();
9812        private int mFlags;
9813    }
9814
9815    private static final class EphemeralIntentResolver
9816            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9817        @Override
9818        protected EphemeralResolveIntentInfo[] newArray(int size) {
9819            return new EphemeralResolveIntentInfo[size];
9820        }
9821
9822        @Override
9823        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9824            return true;
9825        }
9826
9827        @Override
9828        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9829                int userId) {
9830            if (!sUserManager.exists(userId)) {
9831                return null;
9832            }
9833            return info.getEphemeralResolveInfo();
9834        }
9835    }
9836
9837    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9838            new Comparator<ResolveInfo>() {
9839        public int compare(ResolveInfo r1, ResolveInfo r2) {
9840            int v1 = r1.priority;
9841            int v2 = r2.priority;
9842            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9843            if (v1 != v2) {
9844                return (v1 > v2) ? -1 : 1;
9845            }
9846            v1 = r1.preferredOrder;
9847            v2 = r2.preferredOrder;
9848            if (v1 != v2) {
9849                return (v1 > v2) ? -1 : 1;
9850            }
9851            if (r1.isDefault != r2.isDefault) {
9852                return r1.isDefault ? -1 : 1;
9853            }
9854            v1 = r1.match;
9855            v2 = r2.match;
9856            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9857            if (v1 != v2) {
9858                return (v1 > v2) ? -1 : 1;
9859            }
9860            if (r1.system != r2.system) {
9861                return r1.system ? -1 : 1;
9862            }
9863            if (r1.activityInfo != null) {
9864                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9865            }
9866            if (r1.serviceInfo != null) {
9867                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9868            }
9869            if (r1.providerInfo != null) {
9870                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9871            }
9872            return 0;
9873        }
9874    };
9875
9876    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9877            new Comparator<ProviderInfo>() {
9878        public int compare(ProviderInfo p1, ProviderInfo p2) {
9879            final int v1 = p1.initOrder;
9880            final int v2 = p2.initOrder;
9881            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9882        }
9883    };
9884
9885    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9886            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9887            final int[] userIds) {
9888        mHandler.post(new Runnable() {
9889            @Override
9890            public void run() {
9891                try {
9892                    final IActivityManager am = ActivityManagerNative.getDefault();
9893                    if (am == null) return;
9894                    final int[] resolvedUserIds;
9895                    if (userIds == null) {
9896                        resolvedUserIds = am.getRunningUserIds();
9897                    } else {
9898                        resolvedUserIds = userIds;
9899                    }
9900                    for (int id : resolvedUserIds) {
9901                        final Intent intent = new Intent(action,
9902                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9903                        if (extras != null) {
9904                            intent.putExtras(extras);
9905                        }
9906                        if (targetPkg != null) {
9907                            intent.setPackage(targetPkg);
9908                        }
9909                        // Modify the UID when posting to other users
9910                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9911                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9912                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9913                            intent.putExtra(Intent.EXTRA_UID, uid);
9914                        }
9915                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9916                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9917                        if (DEBUG_BROADCASTS) {
9918                            RuntimeException here = new RuntimeException("here");
9919                            here.fillInStackTrace();
9920                            Slog.d(TAG, "Sending to user " + id + ": "
9921                                    + intent.toShortString(false, true, false, false)
9922                                    + " " + intent.getExtras(), here);
9923                        }
9924                        am.broadcastIntent(null, intent, null, finishedReceiver,
9925                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9926                                null, finishedReceiver != null, false, id);
9927                    }
9928                } catch (RemoteException ex) {
9929                }
9930            }
9931        });
9932    }
9933
9934    /**
9935     * Check if the external storage media is available. This is true if there
9936     * is a mounted external storage medium or if the external storage is
9937     * emulated.
9938     */
9939    private boolean isExternalMediaAvailable() {
9940        return mMediaMounted || Environment.isExternalStorageEmulated();
9941    }
9942
9943    @Override
9944    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9945        // writer
9946        synchronized (mPackages) {
9947            if (!isExternalMediaAvailable()) {
9948                // If the external storage is no longer mounted at this point,
9949                // the caller may not have been able to delete all of this
9950                // packages files and can not delete any more.  Bail.
9951                return null;
9952            }
9953            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9954            if (lastPackage != null) {
9955                pkgs.remove(lastPackage);
9956            }
9957            if (pkgs.size() > 0) {
9958                return pkgs.get(0);
9959            }
9960        }
9961        return null;
9962    }
9963
9964    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9965        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9966                userId, andCode ? 1 : 0, packageName);
9967        if (mSystemReady) {
9968            msg.sendToTarget();
9969        } else {
9970            if (mPostSystemReadyMessages == null) {
9971                mPostSystemReadyMessages = new ArrayList<>();
9972            }
9973            mPostSystemReadyMessages.add(msg);
9974        }
9975    }
9976
9977    void startCleaningPackages() {
9978        // reader
9979        synchronized (mPackages) {
9980            if (!isExternalMediaAvailable()) {
9981                return;
9982            }
9983            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9984                return;
9985            }
9986        }
9987        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9988        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9989        IActivityManager am = ActivityManagerNative.getDefault();
9990        if (am != null) {
9991            try {
9992                am.startService(null, intent, null, mContext.getOpPackageName(),
9993                        UserHandle.USER_SYSTEM);
9994            } catch (RemoteException e) {
9995            }
9996        }
9997    }
9998
9999    @Override
10000    public void installPackage(String originPath, IPackageInstallObserver2 observer,
10001            int installFlags, String installerPackageName, VerificationParams verificationParams,
10002            String packageAbiOverride) {
10003        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
10004                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
10005    }
10006
10007    @Override
10008    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10009            int installFlags, String installerPackageName, VerificationParams verificationParams,
10010            String packageAbiOverride, int userId) {
10011        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10012
10013        final int callingUid = Binder.getCallingUid();
10014        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
10015
10016        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10017            try {
10018                if (observer != null) {
10019                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10020                }
10021            } catch (RemoteException re) {
10022            }
10023            return;
10024        }
10025
10026        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10027            installFlags |= PackageManager.INSTALL_FROM_ADB;
10028
10029        } else {
10030            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10031            // about installerPackageName.
10032
10033            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10034            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10035        }
10036
10037        UserHandle user;
10038        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10039            user = UserHandle.ALL;
10040        } else {
10041            user = new UserHandle(userId);
10042        }
10043
10044        // Only system components can circumvent runtime permissions when installing.
10045        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10046                && mContext.checkCallingOrSelfPermission(Manifest.permission
10047                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10048            throw new SecurityException("You need the "
10049                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10050                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10051        }
10052
10053        verificationParams.setInstallerUid(callingUid);
10054
10055        final File originFile = new File(originPath);
10056        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10057
10058        final Message msg = mHandler.obtainMessage(INIT_COPY);
10059        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10060                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10061        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10062        msg.obj = params;
10063
10064        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10065                System.identityHashCode(msg.obj));
10066        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10067                System.identityHashCode(msg.obj));
10068
10069        mHandler.sendMessage(msg);
10070    }
10071
10072    void installStage(String packageName, File stagedDir, String stagedCid,
10073            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10074            String installerPackageName, int installerUid, UserHandle user) {
10075        if (DEBUG_EPHEMERAL) {
10076            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10077                Slog.d(TAG, "Ephemeral install of " + packageName);
10078            }
10079        }
10080        final VerificationParams verifParams = new VerificationParams(
10081                null, sessionParams.originatingUri, sessionParams.referrerUri,
10082                sessionParams.originatingUid);
10083        verifParams.setInstallerUid(installerUid);
10084
10085        final OriginInfo origin;
10086        if (stagedDir != null) {
10087            origin = OriginInfo.fromStagedFile(stagedDir);
10088        } else {
10089            origin = OriginInfo.fromStagedContainer(stagedCid);
10090        }
10091
10092        final Message msg = mHandler.obtainMessage(INIT_COPY);
10093        final InstallParams params = new InstallParams(origin, null, observer,
10094                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10095                verifParams, user, sessionParams.abiOverride,
10096                sessionParams.grantedRuntimePermissions);
10097        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10098        msg.obj = params;
10099
10100        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10101                System.identityHashCode(msg.obj));
10102        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10103                System.identityHashCode(msg.obj));
10104
10105        mHandler.sendMessage(msg);
10106    }
10107
10108    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10109        Bundle extras = new Bundle(1);
10110        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10111
10112        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10113                packageName, extras, 0, null, null, new int[] {userId});
10114        try {
10115            IActivityManager am = ActivityManagerNative.getDefault();
10116            final boolean isSystem =
10117                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10118            if (isSystem && am.isUserRunning(userId, 0)) {
10119                // The just-installed/enabled app is bundled on the system, so presumed
10120                // to be able to run automatically without needing an explicit launch.
10121                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10122                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10123                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10124                        .setPackage(packageName);
10125                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10126                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10127            }
10128        } catch (RemoteException e) {
10129            // shouldn't happen
10130            Slog.w(TAG, "Unable to bootstrap installed package", e);
10131        }
10132    }
10133
10134    @Override
10135    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10136            int userId) {
10137        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10138        PackageSetting pkgSetting;
10139        final int uid = Binder.getCallingUid();
10140        enforceCrossUserPermission(uid, userId, true, true,
10141                "setApplicationHiddenSetting for user " + userId);
10142
10143        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10144            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10145            return false;
10146        }
10147
10148        long callingId = Binder.clearCallingIdentity();
10149        try {
10150            boolean sendAdded = false;
10151            boolean sendRemoved = false;
10152            // writer
10153            synchronized (mPackages) {
10154                pkgSetting = mSettings.mPackages.get(packageName);
10155                if (pkgSetting == null) {
10156                    return false;
10157                }
10158                if (pkgSetting.getHidden(userId) != hidden) {
10159                    pkgSetting.setHidden(hidden, userId);
10160                    mSettings.writePackageRestrictionsLPr(userId);
10161                    if (hidden) {
10162                        sendRemoved = true;
10163                    } else {
10164                        sendAdded = true;
10165                    }
10166                }
10167            }
10168            if (sendAdded) {
10169                sendPackageAddedForUser(packageName, pkgSetting, userId);
10170                return true;
10171            }
10172            if (sendRemoved) {
10173                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10174                        "hiding pkg");
10175                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10176                return true;
10177            }
10178        } finally {
10179            Binder.restoreCallingIdentity(callingId);
10180        }
10181        return false;
10182    }
10183
10184    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10185            int userId) {
10186        final PackageRemovedInfo info = new PackageRemovedInfo();
10187        info.removedPackage = packageName;
10188        info.removedUsers = new int[] {userId};
10189        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10190        info.sendBroadcast(false, false, false);
10191    }
10192
10193    /**
10194     * Returns true if application is not found or there was an error. Otherwise it returns
10195     * the hidden state of the package for the given user.
10196     */
10197    @Override
10198    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10199        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10200        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10201                false, "getApplicationHidden for user " + userId);
10202        PackageSetting pkgSetting;
10203        long callingId = Binder.clearCallingIdentity();
10204        try {
10205            // writer
10206            synchronized (mPackages) {
10207                pkgSetting = mSettings.mPackages.get(packageName);
10208                if (pkgSetting == null) {
10209                    return true;
10210                }
10211                return pkgSetting.getHidden(userId);
10212            }
10213        } finally {
10214            Binder.restoreCallingIdentity(callingId);
10215        }
10216    }
10217
10218    /**
10219     * @hide
10220     */
10221    @Override
10222    public int installExistingPackageAsUser(String packageName, int userId) {
10223        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10224                null);
10225        PackageSetting pkgSetting;
10226        final int uid = Binder.getCallingUid();
10227        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10228                + userId);
10229        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10230            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10231        }
10232
10233        long callingId = Binder.clearCallingIdentity();
10234        try {
10235            boolean sendAdded = false;
10236
10237            // writer
10238            synchronized (mPackages) {
10239                pkgSetting = mSettings.mPackages.get(packageName);
10240                if (pkgSetting == null) {
10241                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10242                }
10243                if (!pkgSetting.getInstalled(userId)) {
10244                    pkgSetting.setInstalled(true, userId);
10245                    pkgSetting.setHidden(false, userId);
10246                    mSettings.writePackageRestrictionsLPr(userId);
10247                    sendAdded = true;
10248                }
10249            }
10250
10251            if (sendAdded) {
10252                sendPackageAddedForUser(packageName, pkgSetting, userId);
10253            }
10254        } finally {
10255            Binder.restoreCallingIdentity(callingId);
10256        }
10257
10258        return PackageManager.INSTALL_SUCCEEDED;
10259    }
10260
10261    boolean isUserRestricted(int userId, String restrictionKey) {
10262        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10263        if (restrictions.getBoolean(restrictionKey, false)) {
10264            Log.w(TAG, "User is restricted: " + restrictionKey);
10265            return true;
10266        }
10267        return false;
10268    }
10269
10270    @Override
10271    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10272        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10273        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10274                "setPackageSuspended for user " + userId);
10275
10276        long callingId = Binder.clearCallingIdentity();
10277        try {
10278            synchronized (mPackages) {
10279                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10280                if (pkgSetting != null) {
10281                    if (pkgSetting.getSuspended(userId) != suspended) {
10282                        pkgSetting.setSuspended(suspended, userId);
10283                        mSettings.writePackageRestrictionsLPr(userId);
10284                    }
10285
10286                    // TODO:
10287                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10288                    // * remove app from recents (kill app it if it is running)
10289                    // * erase existing notifications for this app
10290                    return true;
10291                }
10292
10293                return false;
10294            }
10295        } finally {
10296            Binder.restoreCallingIdentity(callingId);
10297        }
10298    }
10299
10300    @Override
10301    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10302        mContext.enforceCallingOrSelfPermission(
10303                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10304                "Only package verification agents can verify applications");
10305
10306        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10307        final PackageVerificationResponse response = new PackageVerificationResponse(
10308                verificationCode, Binder.getCallingUid());
10309        msg.arg1 = id;
10310        msg.obj = response;
10311        mHandler.sendMessage(msg);
10312    }
10313
10314    @Override
10315    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10316            long millisecondsToDelay) {
10317        mContext.enforceCallingOrSelfPermission(
10318                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10319                "Only package verification agents can extend verification timeouts");
10320
10321        final PackageVerificationState state = mPendingVerification.get(id);
10322        final PackageVerificationResponse response = new PackageVerificationResponse(
10323                verificationCodeAtTimeout, Binder.getCallingUid());
10324
10325        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10326            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10327        }
10328        if (millisecondsToDelay < 0) {
10329            millisecondsToDelay = 0;
10330        }
10331        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10332                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10333            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10334        }
10335
10336        if ((state != null) && !state.timeoutExtended()) {
10337            state.extendTimeout();
10338
10339            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10340            msg.arg1 = id;
10341            msg.obj = response;
10342            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10343        }
10344    }
10345
10346    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10347            int verificationCode, UserHandle user) {
10348        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10349        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10350        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10351        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10352        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10353
10354        mContext.sendBroadcastAsUser(intent, user,
10355                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10356    }
10357
10358    private ComponentName matchComponentForVerifier(String packageName,
10359            List<ResolveInfo> receivers) {
10360        ActivityInfo targetReceiver = null;
10361
10362        final int NR = receivers.size();
10363        for (int i = 0; i < NR; i++) {
10364            final ResolveInfo info = receivers.get(i);
10365            if (info.activityInfo == null) {
10366                continue;
10367            }
10368
10369            if (packageName.equals(info.activityInfo.packageName)) {
10370                targetReceiver = info.activityInfo;
10371                break;
10372            }
10373        }
10374
10375        if (targetReceiver == null) {
10376            return null;
10377        }
10378
10379        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10380    }
10381
10382    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10383            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10384        if (pkgInfo.verifiers.length == 0) {
10385            return null;
10386        }
10387
10388        final int N = pkgInfo.verifiers.length;
10389        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10390        for (int i = 0; i < N; i++) {
10391            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10392
10393            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10394                    receivers);
10395            if (comp == null) {
10396                continue;
10397            }
10398
10399            final int verifierUid = getUidForVerifier(verifierInfo);
10400            if (verifierUid == -1) {
10401                continue;
10402            }
10403
10404            if (DEBUG_VERIFY) {
10405                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10406                        + " with the correct signature");
10407            }
10408            sufficientVerifiers.add(comp);
10409            verificationState.addSufficientVerifier(verifierUid);
10410        }
10411
10412        return sufficientVerifiers;
10413    }
10414
10415    private int getUidForVerifier(VerifierInfo verifierInfo) {
10416        synchronized (mPackages) {
10417            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10418            if (pkg == null) {
10419                return -1;
10420            } else if (pkg.mSignatures.length != 1) {
10421                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10422                        + " has more than one signature; ignoring");
10423                return -1;
10424            }
10425
10426            /*
10427             * If the public key of the package's signature does not match
10428             * our expected public key, then this is a different package and
10429             * we should skip.
10430             */
10431
10432            final byte[] expectedPublicKey;
10433            try {
10434                final Signature verifierSig = pkg.mSignatures[0];
10435                final PublicKey publicKey = verifierSig.getPublicKey();
10436                expectedPublicKey = publicKey.getEncoded();
10437            } catch (CertificateException e) {
10438                return -1;
10439            }
10440
10441            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10442
10443            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10444                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10445                        + " does not have the expected public key; ignoring");
10446                return -1;
10447            }
10448
10449            return pkg.applicationInfo.uid;
10450        }
10451    }
10452
10453    @Override
10454    public void finishPackageInstall(int token) {
10455        enforceSystemOrRoot("Only the system is allowed to finish installs");
10456
10457        if (DEBUG_INSTALL) {
10458            Slog.v(TAG, "BM finishing package install for " + token);
10459        }
10460        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10461
10462        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10463        mHandler.sendMessage(msg);
10464    }
10465
10466    /**
10467     * Get the verification agent timeout.
10468     *
10469     * @return verification timeout in milliseconds
10470     */
10471    private long getVerificationTimeout() {
10472        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10473                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10474                DEFAULT_VERIFICATION_TIMEOUT);
10475    }
10476
10477    /**
10478     * Get the default verification agent response code.
10479     *
10480     * @return default verification response code
10481     */
10482    private int getDefaultVerificationResponse() {
10483        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10484                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10485                DEFAULT_VERIFICATION_RESPONSE);
10486    }
10487
10488    /**
10489     * Check whether or not package verification has been enabled.
10490     *
10491     * @return true if verification should be performed
10492     */
10493    private boolean isVerificationEnabled(int userId, int installFlags) {
10494        if (!DEFAULT_VERIFY_ENABLE) {
10495            return false;
10496        }
10497        // Ephemeral apps don't get the full verification treatment
10498        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10499            if (DEBUG_EPHEMERAL) {
10500                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10501            }
10502            return false;
10503        }
10504
10505        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10506
10507        // Check if installing from ADB
10508        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10509            // Do not run verification in a test harness environment
10510            if (ActivityManager.isRunningInTestHarness()) {
10511                return false;
10512            }
10513            if (ensureVerifyAppsEnabled) {
10514                return true;
10515            }
10516            // Check if the developer does not want package verification for ADB installs
10517            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10518                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10519                return false;
10520            }
10521        }
10522
10523        if (ensureVerifyAppsEnabled) {
10524            return true;
10525        }
10526
10527        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10528                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10529    }
10530
10531    @Override
10532    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10533            throws RemoteException {
10534        mContext.enforceCallingOrSelfPermission(
10535                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10536                "Only intentfilter verification agents can verify applications");
10537
10538        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10539        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10540                Binder.getCallingUid(), verificationCode, failedDomains);
10541        msg.arg1 = id;
10542        msg.obj = response;
10543        mHandler.sendMessage(msg);
10544    }
10545
10546    @Override
10547    public int getIntentVerificationStatus(String packageName, int userId) {
10548        synchronized (mPackages) {
10549            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10550        }
10551    }
10552
10553    @Override
10554    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10555        mContext.enforceCallingOrSelfPermission(
10556                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10557
10558        boolean result = false;
10559        synchronized (mPackages) {
10560            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10561        }
10562        if (result) {
10563            scheduleWritePackageRestrictionsLocked(userId);
10564        }
10565        return result;
10566    }
10567
10568    @Override
10569    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10570        synchronized (mPackages) {
10571            return mSettings.getIntentFilterVerificationsLPr(packageName);
10572        }
10573    }
10574
10575    @Override
10576    public List<IntentFilter> getAllIntentFilters(String packageName) {
10577        if (TextUtils.isEmpty(packageName)) {
10578            return Collections.<IntentFilter>emptyList();
10579        }
10580        synchronized (mPackages) {
10581            PackageParser.Package pkg = mPackages.get(packageName);
10582            if (pkg == null || pkg.activities == null) {
10583                return Collections.<IntentFilter>emptyList();
10584            }
10585            final int count = pkg.activities.size();
10586            ArrayList<IntentFilter> result = new ArrayList<>();
10587            for (int n=0; n<count; n++) {
10588                PackageParser.Activity activity = pkg.activities.get(n);
10589                if (activity.intents != null && activity.intents.size() > 0) {
10590                    result.addAll(activity.intents);
10591                }
10592            }
10593            return result;
10594        }
10595    }
10596
10597    @Override
10598    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10599        mContext.enforceCallingOrSelfPermission(
10600                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10601
10602        synchronized (mPackages) {
10603            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10604            if (packageName != null) {
10605                result |= updateIntentVerificationStatus(packageName,
10606                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10607                        userId);
10608                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10609                        packageName, userId);
10610            }
10611            return result;
10612        }
10613    }
10614
10615    @Override
10616    public String getDefaultBrowserPackageName(int userId) {
10617        synchronized (mPackages) {
10618            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10619        }
10620    }
10621
10622    /**
10623     * Get the "allow unknown sources" setting.
10624     *
10625     * @return the current "allow unknown sources" setting
10626     */
10627    private int getUnknownSourcesSettings() {
10628        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10629                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10630                -1);
10631    }
10632
10633    @Override
10634    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10635        final int uid = Binder.getCallingUid();
10636        // writer
10637        synchronized (mPackages) {
10638            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10639            if (targetPackageSetting == null) {
10640                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10641            }
10642
10643            PackageSetting installerPackageSetting;
10644            if (installerPackageName != null) {
10645                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10646                if (installerPackageSetting == null) {
10647                    throw new IllegalArgumentException("Unknown installer package: "
10648                            + installerPackageName);
10649                }
10650            } else {
10651                installerPackageSetting = null;
10652            }
10653
10654            Signature[] callerSignature;
10655            Object obj = mSettings.getUserIdLPr(uid);
10656            if (obj != null) {
10657                if (obj instanceof SharedUserSetting) {
10658                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10659                } else if (obj instanceof PackageSetting) {
10660                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10661                } else {
10662                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10663                }
10664            } else {
10665                throw new SecurityException("Unknown calling uid " + uid);
10666            }
10667
10668            // Verify: can't set installerPackageName to a package that is
10669            // not signed with the same cert as the caller.
10670            if (installerPackageSetting != null) {
10671                if (compareSignatures(callerSignature,
10672                        installerPackageSetting.signatures.mSignatures)
10673                        != PackageManager.SIGNATURE_MATCH) {
10674                    throw new SecurityException(
10675                            "Caller does not have same cert as new installer package "
10676                            + installerPackageName);
10677                }
10678            }
10679
10680            // Verify: if target already has an installer package, it must
10681            // be signed with the same cert as the caller.
10682            if (targetPackageSetting.installerPackageName != null) {
10683                PackageSetting setting = mSettings.mPackages.get(
10684                        targetPackageSetting.installerPackageName);
10685                // If the currently set package isn't valid, then it's always
10686                // okay to change it.
10687                if (setting != null) {
10688                    if (compareSignatures(callerSignature,
10689                            setting.signatures.mSignatures)
10690                            != PackageManager.SIGNATURE_MATCH) {
10691                        throw new SecurityException(
10692                                "Caller does not have same cert as old installer package "
10693                                + targetPackageSetting.installerPackageName);
10694                    }
10695                }
10696            }
10697
10698            // Okay!
10699            targetPackageSetting.installerPackageName = installerPackageName;
10700            scheduleWriteSettingsLocked();
10701        }
10702    }
10703
10704    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10705        // Queue up an async operation since the package installation may take a little while.
10706        mHandler.post(new Runnable() {
10707            public void run() {
10708                mHandler.removeCallbacks(this);
10709                 // Result object to be returned
10710                PackageInstalledInfo res = new PackageInstalledInfo();
10711                res.returnCode = currentStatus;
10712                res.uid = -1;
10713                res.pkg = null;
10714                res.removedInfo = new PackageRemovedInfo();
10715                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10716                    args.doPreInstall(res.returnCode);
10717                    synchronized (mInstallLock) {
10718                        installPackageTracedLI(args, res);
10719                    }
10720                    args.doPostInstall(res.returnCode, res.uid);
10721                }
10722
10723                // A restore should be performed at this point if (a) the install
10724                // succeeded, (b) the operation is not an update, and (c) the new
10725                // package has not opted out of backup participation.
10726                final boolean update = res.removedInfo.removedPackage != null;
10727                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10728                boolean doRestore = !update
10729                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10730
10731                // Set up the post-install work request bookkeeping.  This will be used
10732                // and cleaned up by the post-install event handling regardless of whether
10733                // there's a restore pass performed.  Token values are >= 1.
10734                int token;
10735                if (mNextInstallToken < 0) mNextInstallToken = 1;
10736                token = mNextInstallToken++;
10737
10738                PostInstallData data = new PostInstallData(args, res);
10739                mRunningInstalls.put(token, data);
10740                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10741
10742                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10743                    // Pass responsibility to the Backup Manager.  It will perform a
10744                    // restore if appropriate, then pass responsibility back to the
10745                    // Package Manager to run the post-install observer callbacks
10746                    // and broadcasts.
10747                    IBackupManager bm = IBackupManager.Stub.asInterface(
10748                            ServiceManager.getService(Context.BACKUP_SERVICE));
10749                    if (bm != null) {
10750                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10751                                + " to BM for possible restore");
10752                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10753                        try {
10754                            // TODO: http://b/22388012
10755                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10756                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10757                            } else {
10758                                doRestore = false;
10759                            }
10760                        } catch (RemoteException e) {
10761                            // can't happen; the backup manager is local
10762                        } catch (Exception e) {
10763                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10764                            doRestore = false;
10765                        }
10766                    } else {
10767                        Slog.e(TAG, "Backup Manager not found!");
10768                        doRestore = false;
10769                    }
10770                }
10771
10772                if (!doRestore) {
10773                    // No restore possible, or the Backup Manager was mysteriously not
10774                    // available -- just fire the post-install work request directly.
10775                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10776
10777                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10778
10779                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10780                    mHandler.sendMessage(msg);
10781                }
10782            }
10783        });
10784    }
10785
10786    private abstract class HandlerParams {
10787        private static final int MAX_RETRIES = 4;
10788
10789        /**
10790         * Number of times startCopy() has been attempted and had a non-fatal
10791         * error.
10792         */
10793        private int mRetries = 0;
10794
10795        /** User handle for the user requesting the information or installation. */
10796        private final UserHandle mUser;
10797        String traceMethod;
10798        int traceCookie;
10799
10800        HandlerParams(UserHandle user) {
10801            mUser = user;
10802        }
10803
10804        UserHandle getUser() {
10805            return mUser;
10806        }
10807
10808        HandlerParams setTraceMethod(String traceMethod) {
10809            this.traceMethod = traceMethod;
10810            return this;
10811        }
10812
10813        HandlerParams setTraceCookie(int traceCookie) {
10814            this.traceCookie = traceCookie;
10815            return this;
10816        }
10817
10818        final boolean startCopy() {
10819            boolean res;
10820            try {
10821                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10822
10823                if (++mRetries > MAX_RETRIES) {
10824                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10825                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10826                    handleServiceError();
10827                    return false;
10828                } else {
10829                    handleStartCopy();
10830                    res = true;
10831                }
10832            } catch (RemoteException e) {
10833                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10834                mHandler.sendEmptyMessage(MCS_RECONNECT);
10835                res = false;
10836            }
10837            handleReturnCode();
10838            return res;
10839        }
10840
10841        final void serviceError() {
10842            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10843            handleServiceError();
10844            handleReturnCode();
10845        }
10846
10847        abstract void handleStartCopy() throws RemoteException;
10848        abstract void handleServiceError();
10849        abstract void handleReturnCode();
10850    }
10851
10852    class MeasureParams extends HandlerParams {
10853        private final PackageStats mStats;
10854        private boolean mSuccess;
10855
10856        private final IPackageStatsObserver mObserver;
10857
10858        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10859            super(new UserHandle(stats.userHandle));
10860            mObserver = observer;
10861            mStats = stats;
10862        }
10863
10864        @Override
10865        public String toString() {
10866            return "MeasureParams{"
10867                + Integer.toHexString(System.identityHashCode(this))
10868                + " " + mStats.packageName + "}";
10869        }
10870
10871        @Override
10872        void handleStartCopy() throws RemoteException {
10873            synchronized (mInstallLock) {
10874                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10875            }
10876
10877            if (mSuccess) {
10878                final boolean mounted;
10879                if (Environment.isExternalStorageEmulated()) {
10880                    mounted = true;
10881                } else {
10882                    final String status = Environment.getExternalStorageState();
10883                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10884                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10885                }
10886
10887                if (mounted) {
10888                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10889
10890                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10891                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10892
10893                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10894                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10895
10896                    // Always subtract cache size, since it's a subdirectory
10897                    mStats.externalDataSize -= mStats.externalCacheSize;
10898
10899                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10900                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10901
10902                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10903                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10904                }
10905            }
10906        }
10907
10908        @Override
10909        void handleReturnCode() {
10910            if (mObserver != null) {
10911                try {
10912                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10913                } catch (RemoteException e) {
10914                    Slog.i(TAG, "Observer no longer exists.");
10915                }
10916            }
10917        }
10918
10919        @Override
10920        void handleServiceError() {
10921            Slog.e(TAG, "Could not measure application " + mStats.packageName
10922                            + " external storage");
10923        }
10924    }
10925
10926    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10927            throws RemoteException {
10928        long result = 0;
10929        for (File path : paths) {
10930            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10931        }
10932        return result;
10933    }
10934
10935    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10936        for (File path : paths) {
10937            try {
10938                mcs.clearDirectory(path.getAbsolutePath());
10939            } catch (RemoteException e) {
10940            }
10941        }
10942    }
10943
10944    static class OriginInfo {
10945        /**
10946         * Location where install is coming from, before it has been
10947         * copied/renamed into place. This could be a single monolithic APK
10948         * file, or a cluster directory. This location may be untrusted.
10949         */
10950        final File file;
10951        final String cid;
10952
10953        /**
10954         * Flag indicating that {@link #file} or {@link #cid} has already been
10955         * staged, meaning downstream users don't need to defensively copy the
10956         * contents.
10957         */
10958        final boolean staged;
10959
10960        /**
10961         * Flag indicating that {@link #file} or {@link #cid} is an already
10962         * installed app that is being moved.
10963         */
10964        final boolean existing;
10965
10966        final String resolvedPath;
10967        final File resolvedFile;
10968
10969        static OriginInfo fromNothing() {
10970            return new OriginInfo(null, null, false, false);
10971        }
10972
10973        static OriginInfo fromUntrustedFile(File file) {
10974            return new OriginInfo(file, null, false, false);
10975        }
10976
10977        static OriginInfo fromExistingFile(File file) {
10978            return new OriginInfo(file, null, false, true);
10979        }
10980
10981        static OriginInfo fromStagedFile(File file) {
10982            return new OriginInfo(file, null, true, false);
10983        }
10984
10985        static OriginInfo fromStagedContainer(String cid) {
10986            return new OriginInfo(null, cid, true, false);
10987        }
10988
10989        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10990            this.file = file;
10991            this.cid = cid;
10992            this.staged = staged;
10993            this.existing = existing;
10994
10995            if (cid != null) {
10996                resolvedPath = PackageHelper.getSdDir(cid);
10997                resolvedFile = new File(resolvedPath);
10998            } else if (file != null) {
10999                resolvedPath = file.getAbsolutePath();
11000                resolvedFile = file;
11001            } else {
11002                resolvedPath = null;
11003                resolvedFile = null;
11004            }
11005        }
11006    }
11007
11008    static class MoveInfo {
11009        final int moveId;
11010        final String fromUuid;
11011        final String toUuid;
11012        final String packageName;
11013        final String dataAppName;
11014        final int appId;
11015        final String seinfo;
11016
11017        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11018                String dataAppName, int appId, String seinfo) {
11019            this.moveId = moveId;
11020            this.fromUuid = fromUuid;
11021            this.toUuid = toUuid;
11022            this.packageName = packageName;
11023            this.dataAppName = dataAppName;
11024            this.appId = appId;
11025            this.seinfo = seinfo;
11026        }
11027    }
11028
11029    class InstallParams extends HandlerParams {
11030        final OriginInfo origin;
11031        final MoveInfo move;
11032        final IPackageInstallObserver2 observer;
11033        int installFlags;
11034        final String installerPackageName;
11035        final String volumeUuid;
11036        final VerificationParams verificationParams;
11037        private InstallArgs mArgs;
11038        private int mRet;
11039        final String packageAbiOverride;
11040        final String[] grantedRuntimePermissions;
11041
11042        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11043                int installFlags, String installerPackageName, String volumeUuid,
11044                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11045                String[] grantedPermissions) {
11046            super(user);
11047            this.origin = origin;
11048            this.move = move;
11049            this.observer = observer;
11050            this.installFlags = installFlags;
11051            this.installerPackageName = installerPackageName;
11052            this.volumeUuid = volumeUuid;
11053            this.verificationParams = verificationParams;
11054            this.packageAbiOverride = packageAbiOverride;
11055            this.grantedRuntimePermissions = grantedPermissions;
11056        }
11057
11058        @Override
11059        public String toString() {
11060            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11061                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11062        }
11063
11064        private int installLocationPolicy(PackageInfoLite pkgLite) {
11065            String packageName = pkgLite.packageName;
11066            int installLocation = pkgLite.installLocation;
11067            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11068            // reader
11069            synchronized (mPackages) {
11070                PackageParser.Package pkg = mPackages.get(packageName);
11071                if (pkg != null) {
11072                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11073                        // Check for downgrading.
11074                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11075                            try {
11076                                checkDowngrade(pkg, pkgLite);
11077                            } catch (PackageManagerException e) {
11078                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11079                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11080                            }
11081                        }
11082                        // Check for updated system application.
11083                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11084                            if (onSd) {
11085                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11086                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11087                            }
11088                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11089                        } else {
11090                            if (onSd) {
11091                                // Install flag overrides everything.
11092                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11093                            }
11094                            // If current upgrade specifies particular preference
11095                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11096                                // Application explicitly specified internal.
11097                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11098                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11099                                // App explictly prefers external. Let policy decide
11100                            } else {
11101                                // Prefer previous location
11102                                if (isExternal(pkg)) {
11103                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11104                                }
11105                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11106                            }
11107                        }
11108                    } else {
11109                        // Invalid install. Return error code
11110                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11111                    }
11112                }
11113            }
11114            // All the special cases have been taken care of.
11115            // Return result based on recommended install location.
11116            if (onSd) {
11117                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11118            }
11119            return pkgLite.recommendedInstallLocation;
11120        }
11121
11122        /*
11123         * Invoke remote method to get package information and install
11124         * location values. Override install location based on default
11125         * policy if needed and then create install arguments based
11126         * on the install location.
11127         */
11128        public void handleStartCopy() throws RemoteException {
11129            int ret = PackageManager.INSTALL_SUCCEEDED;
11130
11131            // If we're already staged, we've firmly committed to an install location
11132            if (origin.staged) {
11133                if (origin.file != null) {
11134                    installFlags |= PackageManager.INSTALL_INTERNAL;
11135                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11136                } else if (origin.cid != null) {
11137                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11138                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11139                } else {
11140                    throw new IllegalStateException("Invalid stage location");
11141                }
11142            }
11143
11144            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11145            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11146            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11147            PackageInfoLite pkgLite = null;
11148
11149            if (onInt && onSd) {
11150                // Check if both bits are set.
11151                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11152                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11153            } else if (onSd && ephemeral) {
11154                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11155                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11156            } else {
11157                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11158                        packageAbiOverride);
11159
11160                if (DEBUG_EPHEMERAL && ephemeral) {
11161                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11162                }
11163
11164                /*
11165                 * If we have too little free space, try to free cache
11166                 * before giving up.
11167                 */
11168                if (!origin.staged && pkgLite.recommendedInstallLocation
11169                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11170                    // TODO: focus freeing disk space on the target device
11171                    final StorageManager storage = StorageManager.from(mContext);
11172                    final long lowThreshold = storage.getStorageLowBytes(
11173                            Environment.getDataDirectory());
11174
11175                    final long sizeBytes = mContainerService.calculateInstalledSize(
11176                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11177
11178                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11179                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11180                                installFlags, packageAbiOverride);
11181                    }
11182
11183                    /*
11184                     * The cache free must have deleted the file we
11185                     * downloaded to install.
11186                     *
11187                     * TODO: fix the "freeCache" call to not delete
11188                     *       the file we care about.
11189                     */
11190                    if (pkgLite.recommendedInstallLocation
11191                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11192                        pkgLite.recommendedInstallLocation
11193                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11194                    }
11195                }
11196            }
11197
11198            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11199                int loc = pkgLite.recommendedInstallLocation;
11200                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11201                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11202                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11203                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11204                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11205                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11206                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11207                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11208                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11209                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11210                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11211                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11212                } else {
11213                    // Override with defaults if needed.
11214                    loc = installLocationPolicy(pkgLite);
11215                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11216                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11217                    } else if (!onSd && !onInt) {
11218                        // Override install location with flags
11219                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11220                            // Set the flag to install on external media.
11221                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11222                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11223                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11224                            if (DEBUG_EPHEMERAL) {
11225                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11226                            }
11227                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11228                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11229                                    |PackageManager.INSTALL_INTERNAL);
11230                        } else {
11231                            // Make sure the flag for installing on external
11232                            // media is unset
11233                            installFlags |= PackageManager.INSTALL_INTERNAL;
11234                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11235                        }
11236                    }
11237                }
11238            }
11239
11240            final InstallArgs args = createInstallArgs(this);
11241            mArgs = args;
11242
11243            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11244                // TODO: http://b/22976637
11245                // Apps installed for "all" users use the device owner to verify the app
11246                UserHandle verifierUser = getUser();
11247                if (verifierUser == UserHandle.ALL) {
11248                    verifierUser = UserHandle.SYSTEM;
11249                }
11250
11251                /*
11252                 * Determine if we have any installed package verifiers. If we
11253                 * do, then we'll defer to them to verify the packages.
11254                 */
11255                final int requiredUid = mRequiredVerifierPackage == null ? -1
11256                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11257                if (!origin.existing && requiredUid != -1
11258                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11259                    final Intent verification = new Intent(
11260                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11261                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11262                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11263                            PACKAGE_MIME_TYPE);
11264                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11265
11266                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11267                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11268                            verifierUser.getIdentifier());
11269
11270                    if (DEBUG_VERIFY) {
11271                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11272                                + verification.toString() + " with " + pkgLite.verifiers.length
11273                                + " optional verifiers");
11274                    }
11275
11276                    final int verificationId = mPendingVerificationToken++;
11277
11278                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11279
11280                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11281                            installerPackageName);
11282
11283                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11284                            installFlags);
11285
11286                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11287                            pkgLite.packageName);
11288
11289                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11290                            pkgLite.versionCode);
11291
11292                    if (verificationParams != null) {
11293                        if (verificationParams.getVerificationURI() != null) {
11294                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11295                                 verificationParams.getVerificationURI());
11296                        }
11297                        if (verificationParams.getOriginatingURI() != null) {
11298                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11299                                  verificationParams.getOriginatingURI());
11300                        }
11301                        if (verificationParams.getReferrer() != null) {
11302                            verification.putExtra(Intent.EXTRA_REFERRER,
11303                                  verificationParams.getReferrer());
11304                        }
11305                        if (verificationParams.getOriginatingUid() >= 0) {
11306                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11307                                  verificationParams.getOriginatingUid());
11308                        }
11309                        if (verificationParams.getInstallerUid() >= 0) {
11310                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11311                                  verificationParams.getInstallerUid());
11312                        }
11313                    }
11314
11315                    final PackageVerificationState verificationState = new PackageVerificationState(
11316                            requiredUid, args);
11317
11318                    mPendingVerification.append(verificationId, verificationState);
11319
11320                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11321                            receivers, verificationState);
11322
11323                    /*
11324                     * If any sufficient verifiers were listed in the package
11325                     * manifest, attempt to ask them.
11326                     */
11327                    if (sufficientVerifiers != null) {
11328                        final int N = sufficientVerifiers.size();
11329                        if (N == 0) {
11330                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11331                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11332                        } else {
11333                            for (int i = 0; i < N; i++) {
11334                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11335
11336                                final Intent sufficientIntent = new Intent(verification);
11337                                sufficientIntent.setComponent(verifierComponent);
11338                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11339                            }
11340                        }
11341                    }
11342
11343                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11344                            mRequiredVerifierPackage, receivers);
11345                    if (ret == PackageManager.INSTALL_SUCCEEDED
11346                            && mRequiredVerifierPackage != null) {
11347                        Trace.asyncTraceBegin(
11348                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11349                        /*
11350                         * Send the intent to the required verification agent,
11351                         * but only start the verification timeout after the
11352                         * target BroadcastReceivers have run.
11353                         */
11354                        verification.setComponent(requiredVerifierComponent);
11355                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11356                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11357                                new BroadcastReceiver() {
11358                                    @Override
11359                                    public void onReceive(Context context, Intent intent) {
11360                                        final Message msg = mHandler
11361                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11362                                        msg.arg1 = verificationId;
11363                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11364                                    }
11365                                }, null, 0, null, null);
11366
11367                        /*
11368                         * We don't want the copy to proceed until verification
11369                         * succeeds, so null out this field.
11370                         */
11371                        mArgs = null;
11372                    }
11373                } else {
11374                    /*
11375                     * No package verification is enabled, so immediately start
11376                     * the remote call to initiate copy using temporary file.
11377                     */
11378                    ret = args.copyApk(mContainerService, true);
11379                }
11380            }
11381
11382            mRet = ret;
11383        }
11384
11385        @Override
11386        void handleReturnCode() {
11387            // If mArgs is null, then MCS couldn't be reached. When it
11388            // reconnects, it will try again to install. At that point, this
11389            // will succeed.
11390            if (mArgs != null) {
11391                processPendingInstall(mArgs, mRet);
11392            }
11393        }
11394
11395        @Override
11396        void handleServiceError() {
11397            mArgs = createInstallArgs(this);
11398            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11399        }
11400
11401        public boolean isForwardLocked() {
11402            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11403        }
11404    }
11405
11406    /**
11407     * Used during creation of InstallArgs
11408     *
11409     * @param installFlags package installation flags
11410     * @return true if should be installed on external storage
11411     */
11412    private static boolean installOnExternalAsec(int installFlags) {
11413        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11414            return false;
11415        }
11416        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11417            return true;
11418        }
11419        return false;
11420    }
11421
11422    /**
11423     * Used during creation of InstallArgs
11424     *
11425     * @param installFlags package installation flags
11426     * @return true if should be installed as forward locked
11427     */
11428    private static boolean installForwardLocked(int installFlags) {
11429        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11430    }
11431
11432    private InstallArgs createInstallArgs(InstallParams params) {
11433        if (params.move != null) {
11434            return new MoveInstallArgs(params);
11435        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11436            return new AsecInstallArgs(params);
11437        } else {
11438            return new FileInstallArgs(params);
11439        }
11440    }
11441
11442    /**
11443     * Create args that describe an existing installed package. Typically used
11444     * when cleaning up old installs, or used as a move source.
11445     */
11446    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11447            String resourcePath, String[] instructionSets) {
11448        final boolean isInAsec;
11449        if (installOnExternalAsec(installFlags)) {
11450            /* Apps on SD card are always in ASEC containers. */
11451            isInAsec = true;
11452        } else if (installForwardLocked(installFlags)
11453                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11454            /*
11455             * Forward-locked apps are only in ASEC containers if they're the
11456             * new style
11457             */
11458            isInAsec = true;
11459        } else {
11460            isInAsec = false;
11461        }
11462
11463        if (isInAsec) {
11464            return new AsecInstallArgs(codePath, instructionSets,
11465                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11466        } else {
11467            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11468        }
11469    }
11470
11471    static abstract class InstallArgs {
11472        /** @see InstallParams#origin */
11473        final OriginInfo origin;
11474        /** @see InstallParams#move */
11475        final MoveInfo move;
11476
11477        final IPackageInstallObserver2 observer;
11478        // Always refers to PackageManager flags only
11479        final int installFlags;
11480        final String installerPackageName;
11481        final String volumeUuid;
11482        final UserHandle user;
11483        final String abiOverride;
11484        final String[] installGrantPermissions;
11485        /** If non-null, drop an async trace when the install completes */
11486        final String traceMethod;
11487        final int traceCookie;
11488
11489        // The list of instruction sets supported by this app. This is currently
11490        // only used during the rmdex() phase to clean up resources. We can get rid of this
11491        // if we move dex files under the common app path.
11492        /* nullable */ String[] instructionSets;
11493
11494        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11495                int installFlags, String installerPackageName, String volumeUuid,
11496                UserHandle user, String[] instructionSets,
11497                String abiOverride, String[] installGrantPermissions,
11498                String traceMethod, int traceCookie) {
11499            this.origin = origin;
11500            this.move = move;
11501            this.installFlags = installFlags;
11502            this.observer = observer;
11503            this.installerPackageName = installerPackageName;
11504            this.volumeUuid = volumeUuid;
11505            this.user = user;
11506            this.instructionSets = instructionSets;
11507            this.abiOverride = abiOverride;
11508            this.installGrantPermissions = installGrantPermissions;
11509            this.traceMethod = traceMethod;
11510            this.traceCookie = traceCookie;
11511        }
11512
11513        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11514        abstract int doPreInstall(int status);
11515
11516        /**
11517         * Rename package into final resting place. All paths on the given
11518         * scanned package should be updated to reflect the rename.
11519         */
11520        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11521        abstract int doPostInstall(int status, int uid);
11522
11523        /** @see PackageSettingBase#codePathString */
11524        abstract String getCodePath();
11525        /** @see PackageSettingBase#resourcePathString */
11526        abstract String getResourcePath();
11527
11528        // Need installer lock especially for dex file removal.
11529        abstract void cleanUpResourcesLI();
11530        abstract boolean doPostDeleteLI(boolean delete);
11531
11532        /**
11533         * Called before the source arguments are copied. This is used mostly
11534         * for MoveParams when it needs to read the source file to put it in the
11535         * destination.
11536         */
11537        int doPreCopy() {
11538            return PackageManager.INSTALL_SUCCEEDED;
11539        }
11540
11541        /**
11542         * Called after the source arguments are copied. This is used mostly for
11543         * MoveParams when it needs to read the source file to put it in the
11544         * destination.
11545         *
11546         * @return
11547         */
11548        int doPostCopy(int uid) {
11549            return PackageManager.INSTALL_SUCCEEDED;
11550        }
11551
11552        protected boolean isFwdLocked() {
11553            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11554        }
11555
11556        protected boolean isExternalAsec() {
11557            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11558        }
11559
11560        protected boolean isEphemeral() {
11561            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11562        }
11563
11564        UserHandle getUser() {
11565            return user;
11566        }
11567    }
11568
11569    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11570        if (!allCodePaths.isEmpty()) {
11571            if (instructionSets == null) {
11572                throw new IllegalStateException("instructionSet == null");
11573            }
11574            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11575            for (String codePath : allCodePaths) {
11576                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11577                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11578                    if (retCode < 0) {
11579                        Slog.w(TAG, "Couldn't remove dex file for package: "
11580                                + " at location " + codePath + ", retcode=" + retCode);
11581                        // we don't consider this to be a failure of the core package deletion
11582                    }
11583                }
11584            }
11585        }
11586    }
11587
11588    /**
11589     * Logic to handle installation of non-ASEC applications, including copying
11590     * and renaming logic.
11591     */
11592    class FileInstallArgs extends InstallArgs {
11593        private File codeFile;
11594        private File resourceFile;
11595
11596        // Example topology:
11597        // /data/app/com.example/base.apk
11598        // /data/app/com.example/split_foo.apk
11599        // /data/app/com.example/lib/arm/libfoo.so
11600        // /data/app/com.example/lib/arm64/libfoo.so
11601        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11602
11603        /** New install */
11604        FileInstallArgs(InstallParams params) {
11605            super(params.origin, params.move, params.observer, params.installFlags,
11606                    params.installerPackageName, params.volumeUuid,
11607                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11608                    params.grantedRuntimePermissions,
11609                    params.traceMethod, params.traceCookie);
11610            if (isFwdLocked()) {
11611                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11612            }
11613        }
11614
11615        /** Existing install */
11616        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11617            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11618                    null, null, null, 0);
11619            this.codeFile = (codePath != null) ? new File(codePath) : null;
11620            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11621        }
11622
11623        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11624            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11625            try {
11626                return doCopyApk(imcs, temp);
11627            } finally {
11628                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11629            }
11630        }
11631
11632        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11633            if (origin.staged) {
11634                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11635                codeFile = origin.file;
11636                resourceFile = origin.file;
11637                return PackageManager.INSTALL_SUCCEEDED;
11638            }
11639
11640            try {
11641                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11642                final File tempDir =
11643                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11644                codeFile = tempDir;
11645                resourceFile = tempDir;
11646            } catch (IOException e) {
11647                Slog.w(TAG, "Failed to create copy file: " + e);
11648                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11649            }
11650
11651            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11652                @Override
11653                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11654                    if (!FileUtils.isValidExtFilename(name)) {
11655                        throw new IllegalArgumentException("Invalid filename: " + name);
11656                    }
11657                    try {
11658                        final File file = new File(codeFile, name);
11659                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11660                                O_RDWR | O_CREAT, 0644);
11661                        Os.chmod(file.getAbsolutePath(), 0644);
11662                        return new ParcelFileDescriptor(fd);
11663                    } catch (ErrnoException e) {
11664                        throw new RemoteException("Failed to open: " + e.getMessage());
11665                    }
11666                }
11667            };
11668
11669            int ret = PackageManager.INSTALL_SUCCEEDED;
11670            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11671            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11672                Slog.e(TAG, "Failed to copy package");
11673                return ret;
11674            }
11675
11676            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11677            NativeLibraryHelper.Handle handle = null;
11678            try {
11679                handle = NativeLibraryHelper.Handle.create(codeFile);
11680                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11681                        abiOverride);
11682            } catch (IOException e) {
11683                Slog.e(TAG, "Copying native libraries failed", e);
11684                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11685            } finally {
11686                IoUtils.closeQuietly(handle);
11687            }
11688
11689            return ret;
11690        }
11691
11692        int doPreInstall(int status) {
11693            if (status != PackageManager.INSTALL_SUCCEEDED) {
11694                cleanUp();
11695            }
11696            return status;
11697        }
11698
11699        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11700            if (status != PackageManager.INSTALL_SUCCEEDED) {
11701                cleanUp();
11702                return false;
11703            }
11704
11705            final File targetDir = codeFile.getParentFile();
11706            final File beforeCodeFile = codeFile;
11707            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11708
11709            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11710            try {
11711                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11712            } catch (ErrnoException e) {
11713                Slog.w(TAG, "Failed to rename", e);
11714                return false;
11715            }
11716
11717            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11718                Slog.w(TAG, "Failed to restorecon");
11719                return false;
11720            }
11721
11722            // Reflect the rename internally
11723            codeFile = afterCodeFile;
11724            resourceFile = afterCodeFile;
11725
11726            // Reflect the rename in scanned details
11727            pkg.codePath = afterCodeFile.getAbsolutePath();
11728            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11729                    pkg.baseCodePath);
11730            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11731                    pkg.splitCodePaths);
11732
11733            // Reflect the rename in app info
11734            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11735            pkg.applicationInfo.setCodePath(pkg.codePath);
11736            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11737            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11738            pkg.applicationInfo.setResourcePath(pkg.codePath);
11739            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11740            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11741
11742            return true;
11743        }
11744
11745        int doPostInstall(int status, int uid) {
11746            if (status != PackageManager.INSTALL_SUCCEEDED) {
11747                cleanUp();
11748            }
11749            return status;
11750        }
11751
11752        @Override
11753        String getCodePath() {
11754            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11755        }
11756
11757        @Override
11758        String getResourcePath() {
11759            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11760        }
11761
11762        private boolean cleanUp() {
11763            if (codeFile == null || !codeFile.exists()) {
11764                return false;
11765            }
11766
11767            if (codeFile.isDirectory()) {
11768                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11769            } else {
11770                codeFile.delete();
11771            }
11772
11773            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11774                resourceFile.delete();
11775            }
11776
11777            return true;
11778        }
11779
11780        void cleanUpResourcesLI() {
11781            // Try enumerating all code paths before deleting
11782            List<String> allCodePaths = Collections.EMPTY_LIST;
11783            if (codeFile != null && codeFile.exists()) {
11784                try {
11785                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11786                    allCodePaths = pkg.getAllCodePaths();
11787                } catch (PackageParserException e) {
11788                    // Ignored; we tried our best
11789                }
11790            }
11791
11792            cleanUp();
11793            removeDexFiles(allCodePaths, instructionSets);
11794        }
11795
11796        boolean doPostDeleteLI(boolean delete) {
11797            // XXX err, shouldn't we respect the delete flag?
11798            cleanUpResourcesLI();
11799            return true;
11800        }
11801    }
11802
11803    private boolean isAsecExternal(String cid) {
11804        final String asecPath = PackageHelper.getSdFilesystem(cid);
11805        return !asecPath.startsWith(mAsecInternalPath);
11806    }
11807
11808    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11809            PackageManagerException {
11810        if (copyRet < 0) {
11811            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11812                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11813                throw new PackageManagerException(copyRet, message);
11814            }
11815        }
11816    }
11817
11818    /**
11819     * Extract the MountService "container ID" from the full code path of an
11820     * .apk.
11821     */
11822    static String cidFromCodePath(String fullCodePath) {
11823        int eidx = fullCodePath.lastIndexOf("/");
11824        String subStr1 = fullCodePath.substring(0, eidx);
11825        int sidx = subStr1.lastIndexOf("/");
11826        return subStr1.substring(sidx+1, eidx);
11827    }
11828
11829    /**
11830     * Logic to handle installation of ASEC applications, including copying and
11831     * renaming logic.
11832     */
11833    class AsecInstallArgs extends InstallArgs {
11834        static final String RES_FILE_NAME = "pkg.apk";
11835        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11836
11837        String cid;
11838        String packagePath;
11839        String resourcePath;
11840
11841        /** New install */
11842        AsecInstallArgs(InstallParams params) {
11843            super(params.origin, params.move, params.observer, params.installFlags,
11844                    params.installerPackageName, params.volumeUuid,
11845                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11846                    params.grantedRuntimePermissions,
11847                    params.traceMethod, params.traceCookie);
11848        }
11849
11850        /** Existing install */
11851        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11852                        boolean isExternal, boolean isForwardLocked) {
11853            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11854                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11855                    instructionSets, null, null, null, 0);
11856            // Hackily pretend we're still looking at a full code path
11857            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11858                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11859            }
11860
11861            // Extract cid from fullCodePath
11862            int eidx = fullCodePath.lastIndexOf("/");
11863            String subStr1 = fullCodePath.substring(0, eidx);
11864            int sidx = subStr1.lastIndexOf("/");
11865            cid = subStr1.substring(sidx+1, eidx);
11866            setMountPath(subStr1);
11867        }
11868
11869        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11870            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11871                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11872                    instructionSets, null, null, null, 0);
11873            this.cid = cid;
11874            setMountPath(PackageHelper.getSdDir(cid));
11875        }
11876
11877        void createCopyFile() {
11878            cid = mInstallerService.allocateExternalStageCidLegacy();
11879        }
11880
11881        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11882            if (origin.staged && origin.cid != null) {
11883                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11884                cid = origin.cid;
11885                setMountPath(PackageHelper.getSdDir(cid));
11886                return PackageManager.INSTALL_SUCCEEDED;
11887            }
11888
11889            if (temp) {
11890                createCopyFile();
11891            } else {
11892                /*
11893                 * Pre-emptively destroy the container since it's destroyed if
11894                 * copying fails due to it existing anyway.
11895                 */
11896                PackageHelper.destroySdDir(cid);
11897            }
11898
11899            final String newMountPath = imcs.copyPackageToContainer(
11900                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11901                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11902
11903            if (newMountPath != null) {
11904                setMountPath(newMountPath);
11905                return PackageManager.INSTALL_SUCCEEDED;
11906            } else {
11907                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11908            }
11909        }
11910
11911        @Override
11912        String getCodePath() {
11913            return packagePath;
11914        }
11915
11916        @Override
11917        String getResourcePath() {
11918            return resourcePath;
11919        }
11920
11921        int doPreInstall(int status) {
11922            if (status != PackageManager.INSTALL_SUCCEEDED) {
11923                // Destroy container
11924                PackageHelper.destroySdDir(cid);
11925            } else {
11926                boolean mounted = PackageHelper.isContainerMounted(cid);
11927                if (!mounted) {
11928                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11929                            Process.SYSTEM_UID);
11930                    if (newMountPath != null) {
11931                        setMountPath(newMountPath);
11932                    } else {
11933                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11934                    }
11935                }
11936            }
11937            return status;
11938        }
11939
11940        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11941            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11942            String newMountPath = null;
11943            if (PackageHelper.isContainerMounted(cid)) {
11944                // Unmount the container
11945                if (!PackageHelper.unMountSdDir(cid)) {
11946                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11947                    return false;
11948                }
11949            }
11950            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11951                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11952                        " which might be stale. Will try to clean up.");
11953                // Clean up the stale container and proceed to recreate.
11954                if (!PackageHelper.destroySdDir(newCacheId)) {
11955                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11956                    return false;
11957                }
11958                // Successfully cleaned up stale container. Try to rename again.
11959                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11960                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11961                            + " inspite of cleaning it up.");
11962                    return false;
11963                }
11964            }
11965            if (!PackageHelper.isContainerMounted(newCacheId)) {
11966                Slog.w(TAG, "Mounting container " + newCacheId);
11967                newMountPath = PackageHelper.mountSdDir(newCacheId,
11968                        getEncryptKey(), Process.SYSTEM_UID);
11969            } else {
11970                newMountPath = PackageHelper.getSdDir(newCacheId);
11971            }
11972            if (newMountPath == null) {
11973                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11974                return false;
11975            }
11976            Log.i(TAG, "Succesfully renamed " + cid +
11977                    " to " + newCacheId +
11978                    " at new path: " + newMountPath);
11979            cid = newCacheId;
11980
11981            final File beforeCodeFile = new File(packagePath);
11982            setMountPath(newMountPath);
11983            final File afterCodeFile = new File(packagePath);
11984
11985            // Reflect the rename in scanned details
11986            pkg.codePath = afterCodeFile.getAbsolutePath();
11987            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11988                    pkg.baseCodePath);
11989            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11990                    pkg.splitCodePaths);
11991
11992            // Reflect the rename in app info
11993            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11994            pkg.applicationInfo.setCodePath(pkg.codePath);
11995            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11996            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11997            pkg.applicationInfo.setResourcePath(pkg.codePath);
11998            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11999            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12000
12001            return true;
12002        }
12003
12004        private void setMountPath(String mountPath) {
12005            final File mountFile = new File(mountPath);
12006
12007            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12008            if (monolithicFile.exists()) {
12009                packagePath = monolithicFile.getAbsolutePath();
12010                if (isFwdLocked()) {
12011                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12012                } else {
12013                    resourcePath = packagePath;
12014                }
12015            } else {
12016                packagePath = mountFile.getAbsolutePath();
12017                resourcePath = packagePath;
12018            }
12019        }
12020
12021        int doPostInstall(int status, int uid) {
12022            if (status != PackageManager.INSTALL_SUCCEEDED) {
12023                cleanUp();
12024            } else {
12025                final int groupOwner;
12026                final String protectedFile;
12027                if (isFwdLocked()) {
12028                    groupOwner = UserHandle.getSharedAppGid(uid);
12029                    protectedFile = RES_FILE_NAME;
12030                } else {
12031                    groupOwner = -1;
12032                    protectedFile = null;
12033                }
12034
12035                if (uid < Process.FIRST_APPLICATION_UID
12036                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12037                    Slog.e(TAG, "Failed to finalize " + cid);
12038                    PackageHelper.destroySdDir(cid);
12039                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12040                }
12041
12042                boolean mounted = PackageHelper.isContainerMounted(cid);
12043                if (!mounted) {
12044                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12045                }
12046            }
12047            return status;
12048        }
12049
12050        private void cleanUp() {
12051            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12052
12053            // Destroy secure container
12054            PackageHelper.destroySdDir(cid);
12055        }
12056
12057        private List<String> getAllCodePaths() {
12058            final File codeFile = new File(getCodePath());
12059            if (codeFile != null && codeFile.exists()) {
12060                try {
12061                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12062                    return pkg.getAllCodePaths();
12063                } catch (PackageParserException e) {
12064                    // Ignored; we tried our best
12065                }
12066            }
12067            return Collections.EMPTY_LIST;
12068        }
12069
12070        void cleanUpResourcesLI() {
12071            // Enumerate all code paths before deleting
12072            cleanUpResourcesLI(getAllCodePaths());
12073        }
12074
12075        private void cleanUpResourcesLI(List<String> allCodePaths) {
12076            cleanUp();
12077            removeDexFiles(allCodePaths, instructionSets);
12078        }
12079
12080        String getPackageName() {
12081            return getAsecPackageName(cid);
12082        }
12083
12084        boolean doPostDeleteLI(boolean delete) {
12085            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12086            final List<String> allCodePaths = getAllCodePaths();
12087            boolean mounted = PackageHelper.isContainerMounted(cid);
12088            if (mounted) {
12089                // Unmount first
12090                if (PackageHelper.unMountSdDir(cid)) {
12091                    mounted = false;
12092                }
12093            }
12094            if (!mounted && delete) {
12095                cleanUpResourcesLI(allCodePaths);
12096            }
12097            return !mounted;
12098        }
12099
12100        @Override
12101        int doPreCopy() {
12102            if (isFwdLocked()) {
12103                if (!PackageHelper.fixSdPermissions(cid,
12104                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12105                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12106                }
12107            }
12108
12109            return PackageManager.INSTALL_SUCCEEDED;
12110        }
12111
12112        @Override
12113        int doPostCopy(int uid) {
12114            if (isFwdLocked()) {
12115                if (uid < Process.FIRST_APPLICATION_UID
12116                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12117                                RES_FILE_NAME)) {
12118                    Slog.e(TAG, "Failed to finalize " + cid);
12119                    PackageHelper.destroySdDir(cid);
12120                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12121                }
12122            }
12123
12124            return PackageManager.INSTALL_SUCCEEDED;
12125        }
12126    }
12127
12128    /**
12129     * Logic to handle movement of existing installed applications.
12130     */
12131    class MoveInstallArgs extends InstallArgs {
12132        private File codeFile;
12133        private File resourceFile;
12134
12135        /** New install */
12136        MoveInstallArgs(InstallParams params) {
12137            super(params.origin, params.move, params.observer, params.installFlags,
12138                    params.installerPackageName, params.volumeUuid,
12139                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12140                    params.grantedRuntimePermissions,
12141                    params.traceMethod, params.traceCookie);
12142        }
12143
12144        int copyApk(IMediaContainerService imcs, boolean temp) {
12145            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12146                    + move.fromUuid + " to " + move.toUuid);
12147            synchronized (mInstaller) {
12148                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12149                        move.dataAppName, move.appId, move.seinfo) != 0) {
12150                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12151                }
12152            }
12153
12154            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12155            resourceFile = codeFile;
12156            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12157
12158            return PackageManager.INSTALL_SUCCEEDED;
12159        }
12160
12161        int doPreInstall(int status) {
12162            if (status != PackageManager.INSTALL_SUCCEEDED) {
12163                cleanUp(move.toUuid);
12164            }
12165            return status;
12166        }
12167
12168        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12169            if (status != PackageManager.INSTALL_SUCCEEDED) {
12170                cleanUp(move.toUuid);
12171                return false;
12172            }
12173
12174            // Reflect the move in app info
12175            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12176            pkg.applicationInfo.setCodePath(pkg.codePath);
12177            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12178            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12179            pkg.applicationInfo.setResourcePath(pkg.codePath);
12180            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12181            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12182
12183            return true;
12184        }
12185
12186        int doPostInstall(int status, int uid) {
12187            if (status == PackageManager.INSTALL_SUCCEEDED) {
12188                cleanUp(move.fromUuid);
12189            } else {
12190                cleanUp(move.toUuid);
12191            }
12192            return status;
12193        }
12194
12195        @Override
12196        String getCodePath() {
12197            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12198        }
12199
12200        @Override
12201        String getResourcePath() {
12202            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12203        }
12204
12205        private boolean cleanUp(String volumeUuid) {
12206            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12207                    move.dataAppName);
12208            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12209            synchronized (mInstallLock) {
12210                // Clean up both app data and code
12211                removeDataDirsLI(volumeUuid, move.packageName);
12212                if (codeFile.isDirectory()) {
12213                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12214                } else {
12215                    codeFile.delete();
12216                }
12217            }
12218            return true;
12219        }
12220
12221        void cleanUpResourcesLI() {
12222            throw new UnsupportedOperationException();
12223        }
12224
12225        boolean doPostDeleteLI(boolean delete) {
12226            throw new UnsupportedOperationException();
12227        }
12228    }
12229
12230    static String getAsecPackageName(String packageCid) {
12231        int idx = packageCid.lastIndexOf("-");
12232        if (idx == -1) {
12233            return packageCid;
12234        }
12235        return packageCid.substring(0, idx);
12236    }
12237
12238    // Utility method used to create code paths based on package name and available index.
12239    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12240        String idxStr = "";
12241        int idx = 1;
12242        // Fall back to default value of idx=1 if prefix is not
12243        // part of oldCodePath
12244        if (oldCodePath != null) {
12245            String subStr = oldCodePath;
12246            // Drop the suffix right away
12247            if (suffix != null && subStr.endsWith(suffix)) {
12248                subStr = subStr.substring(0, subStr.length() - suffix.length());
12249            }
12250            // If oldCodePath already contains prefix find out the
12251            // ending index to either increment or decrement.
12252            int sidx = subStr.lastIndexOf(prefix);
12253            if (sidx != -1) {
12254                subStr = subStr.substring(sidx + prefix.length());
12255                if (subStr != null) {
12256                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12257                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12258                    }
12259                    try {
12260                        idx = Integer.parseInt(subStr);
12261                        if (idx <= 1) {
12262                            idx++;
12263                        } else {
12264                            idx--;
12265                        }
12266                    } catch(NumberFormatException e) {
12267                    }
12268                }
12269            }
12270        }
12271        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12272        return prefix + idxStr;
12273    }
12274
12275    private File getNextCodePath(File targetDir, String packageName) {
12276        int suffix = 1;
12277        File result;
12278        do {
12279            result = new File(targetDir, packageName + "-" + suffix);
12280            suffix++;
12281        } while (result.exists());
12282        return result;
12283    }
12284
12285    // Utility method that returns the relative package path with respect
12286    // to the installation directory. Like say for /data/data/com.test-1.apk
12287    // string com.test-1 is returned.
12288    static String deriveCodePathName(String codePath) {
12289        if (codePath == null) {
12290            return null;
12291        }
12292        final File codeFile = new File(codePath);
12293        final String name = codeFile.getName();
12294        if (codeFile.isDirectory()) {
12295            return name;
12296        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12297            final int lastDot = name.lastIndexOf('.');
12298            return name.substring(0, lastDot);
12299        } else {
12300            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12301            return null;
12302        }
12303    }
12304
12305    static class PackageInstalledInfo {
12306        String name;
12307        int uid;
12308        // The set of users that originally had this package installed.
12309        int[] origUsers;
12310        // The set of users that now have this package installed.
12311        int[] newUsers;
12312        PackageParser.Package pkg;
12313        int returnCode;
12314        String returnMsg;
12315        PackageRemovedInfo removedInfo;
12316
12317        public void setError(int code, String msg) {
12318            returnCode = code;
12319            returnMsg = msg;
12320            Slog.w(TAG, msg);
12321        }
12322
12323        public void setError(String msg, PackageParserException e) {
12324            returnCode = e.error;
12325            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12326            Slog.w(TAG, msg, e);
12327        }
12328
12329        public void setError(String msg, PackageManagerException e) {
12330            returnCode = e.error;
12331            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12332            Slog.w(TAG, msg, e);
12333        }
12334
12335        // In some error cases we want to convey more info back to the observer
12336        String origPackage;
12337        String origPermission;
12338    }
12339
12340    /*
12341     * Install a non-existing package.
12342     */
12343    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12344            UserHandle user, String installerPackageName, String volumeUuid,
12345            PackageInstalledInfo res) {
12346        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12347
12348        // Remember this for later, in case we need to rollback this install
12349        String pkgName = pkg.packageName;
12350
12351        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12352        // TODO: b/23350563
12353        final boolean dataDirExists = Environment
12354                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12355
12356        synchronized(mPackages) {
12357            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12358                // A package with the same name is already installed, though
12359                // it has been renamed to an older name.  The package we
12360                // are trying to install should be installed as an update to
12361                // the existing one, but that has not been requested, so bail.
12362                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12363                        + " without first uninstalling package running as "
12364                        + mSettings.mRenamedPackages.get(pkgName));
12365                return;
12366            }
12367            if (mPackages.containsKey(pkgName)) {
12368                // Don't allow installation over an existing package with the same name.
12369                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12370                        + " without first uninstalling.");
12371                return;
12372            }
12373        }
12374
12375        try {
12376            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12377                    System.currentTimeMillis(), user);
12378
12379            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12380            // delete the partially installed application. the data directory will have to be
12381            // restored if it was already existing
12382            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12383                // remove package from internal structures.  Note that we want deletePackageX to
12384                // delete the package data and cache directories that it created in
12385                // scanPackageLocked, unless those directories existed before we even tried to
12386                // install.
12387                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12388                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12389                                res.removedInfo, true);
12390            }
12391
12392        } catch (PackageManagerException e) {
12393            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12394        }
12395
12396        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12397    }
12398
12399    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12400        // Can't rotate keys during boot or if sharedUser.
12401        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12402                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12403            return false;
12404        }
12405        // app is using upgradeKeySets; make sure all are valid
12406        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12407        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12408        for (int i = 0; i < upgradeKeySets.length; i++) {
12409            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12410                Slog.wtf(TAG, "Package "
12411                         + (oldPs.name != null ? oldPs.name : "<null>")
12412                         + " contains upgrade-key-set reference to unknown key-set: "
12413                         + upgradeKeySets[i]
12414                         + " reverting to signatures check.");
12415                return false;
12416            }
12417        }
12418        return true;
12419    }
12420
12421    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12422        // Upgrade keysets are being used.  Determine if new package has a superset of the
12423        // required keys.
12424        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12425        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12426        for (int i = 0; i < upgradeKeySets.length; i++) {
12427            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12428            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12429                return true;
12430            }
12431        }
12432        return false;
12433    }
12434
12435    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12436            UserHandle user, String installerPackageName, String volumeUuid,
12437            PackageInstalledInfo res) {
12438        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12439
12440        final PackageParser.Package oldPackage;
12441        final String pkgName = pkg.packageName;
12442        final int[] allUsers;
12443        final boolean[] perUserInstalled;
12444
12445        // First find the old package info and check signatures
12446        synchronized(mPackages) {
12447            oldPackage = mPackages.get(pkgName);
12448            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12449            if (isEphemeral && !oldIsEphemeral) {
12450                // can't downgrade from full to ephemeral
12451                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12452                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12453                return;
12454            }
12455            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12456            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12457            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12458                if(!checkUpgradeKeySetLP(ps, pkg)) {
12459                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12460                            "New package not signed by keys specified by upgrade-keysets: "
12461                            + pkgName);
12462                    return;
12463                }
12464            } else {
12465                // default to original signature matching
12466                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12467                    != PackageManager.SIGNATURE_MATCH) {
12468                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12469                            "New package has a different signature: " + pkgName);
12470                    return;
12471                }
12472            }
12473
12474            // In case of rollback, remember per-user/profile install state
12475            allUsers = sUserManager.getUserIds();
12476            perUserInstalled = new boolean[allUsers.length];
12477            for (int i = 0; i < allUsers.length; i++) {
12478                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12479            }
12480        }
12481
12482        boolean sysPkg = (isSystemApp(oldPackage));
12483        if (sysPkg) {
12484            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12485                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12486        } else {
12487            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12488                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12489        }
12490    }
12491
12492    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12493            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12494            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12495            String volumeUuid, PackageInstalledInfo res) {
12496        String pkgName = deletedPackage.packageName;
12497        boolean deletedPkg = true;
12498        boolean updatedSettings = false;
12499
12500        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12501                + deletedPackage);
12502        long origUpdateTime;
12503        if (pkg.mExtras != null) {
12504            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12505        } else {
12506            origUpdateTime = 0;
12507        }
12508
12509        // First delete the existing package while retaining the data directory
12510        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12511                res.removedInfo, true)) {
12512            // If the existing package wasn't successfully deleted
12513            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12514            deletedPkg = false;
12515        } else {
12516            // Successfully deleted the old package; proceed with replace.
12517
12518            // If deleted package lived in a container, give users a chance to
12519            // relinquish resources before killing.
12520            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12521                if (DEBUG_INSTALL) {
12522                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12523                }
12524                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12525                final ArrayList<String> pkgList = new ArrayList<String>(1);
12526                pkgList.add(deletedPackage.applicationInfo.packageName);
12527                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12528            }
12529
12530            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12531            try {
12532                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12533                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12534                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12535                        perUserInstalled, res, user);
12536                updatedSettings = true;
12537            } catch (PackageManagerException e) {
12538                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12539            }
12540        }
12541
12542        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12543            // remove package from internal structures.  Note that we want deletePackageX to
12544            // delete the package data and cache directories that it created in
12545            // scanPackageLocked, unless those directories existed before we even tried to
12546            // install.
12547            if(updatedSettings) {
12548                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12549                deletePackageLI(
12550                        pkgName, null, true, allUsers, perUserInstalled,
12551                        PackageManager.DELETE_KEEP_DATA,
12552                                res.removedInfo, true);
12553            }
12554            // Since we failed to install the new package we need to restore the old
12555            // package that we deleted.
12556            if (deletedPkg) {
12557                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12558                File restoreFile = new File(deletedPackage.codePath);
12559                // Parse old package
12560                boolean oldExternal = isExternal(deletedPackage);
12561                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12562                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12563                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12564                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12565                try {
12566                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12567                            null);
12568                } catch (PackageManagerException e) {
12569                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12570                            + e.getMessage());
12571                    return;
12572                }
12573                // Restore of old package succeeded. Update permissions.
12574                // writer
12575                synchronized (mPackages) {
12576                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12577                            UPDATE_PERMISSIONS_ALL);
12578                    // can downgrade to reader
12579                    mSettings.writeLPr();
12580                }
12581                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12582            }
12583        }
12584    }
12585
12586    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12587            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12588            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12589            String volumeUuid, PackageInstalledInfo res) {
12590        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12591                + ", old=" + deletedPackage);
12592        boolean disabledSystem = false;
12593        boolean updatedSettings = false;
12594        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12595        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12596                != 0) {
12597            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12598        }
12599        String packageName = deletedPackage.packageName;
12600        if (packageName == null) {
12601            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12602                    "Attempt to delete null packageName.");
12603            return;
12604        }
12605        PackageParser.Package oldPkg;
12606        PackageSetting oldPkgSetting;
12607        // reader
12608        synchronized (mPackages) {
12609            oldPkg = mPackages.get(packageName);
12610            oldPkgSetting = mSettings.mPackages.get(packageName);
12611            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12612                    (oldPkgSetting == null)) {
12613                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12614                        "Couldn't find package:" + packageName + " information");
12615                return;
12616            }
12617        }
12618
12619        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12620
12621        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12622        res.removedInfo.removedPackage = packageName;
12623        // Remove existing system package
12624        removePackageLI(oldPkgSetting, true);
12625        // writer
12626        synchronized (mPackages) {
12627            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12628            if (!disabledSystem && deletedPackage != null) {
12629                // We didn't need to disable the .apk as a current system package,
12630                // which means we are replacing another update that is already
12631                // installed.  We need to make sure to delete the older one's .apk.
12632                res.removedInfo.args = createInstallArgsForExisting(0,
12633                        deletedPackage.applicationInfo.getCodePath(),
12634                        deletedPackage.applicationInfo.getResourcePath(),
12635                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12636            } else {
12637                res.removedInfo.args = null;
12638            }
12639        }
12640
12641        // Successfully disabled the old package. Now proceed with re-installation
12642        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12643
12644        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12645        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12646
12647        PackageParser.Package newPackage = null;
12648        try {
12649            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12650            if (newPackage.mExtras != null) {
12651                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12652                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12653                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12654
12655                // is the update attempting to change shared user? that isn't going to work...
12656                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12657                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12658                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12659                            + " to " + newPkgSetting.sharedUser);
12660                    updatedSettings = true;
12661                }
12662            }
12663
12664            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12665                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12666                        perUserInstalled, res, user);
12667                updatedSettings = true;
12668            }
12669
12670        } catch (PackageManagerException e) {
12671            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12672        }
12673
12674        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12675            // Re installation failed. Restore old information
12676            // Remove new pkg information
12677            if (newPackage != null) {
12678                removeInstalledPackageLI(newPackage, true);
12679            }
12680            // Add back the old system package
12681            try {
12682                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12683            } catch (PackageManagerException e) {
12684                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12685            }
12686            // Restore the old system information in Settings
12687            synchronized (mPackages) {
12688                if (disabledSystem) {
12689                    mSettings.enableSystemPackageLPw(packageName);
12690                }
12691                if (updatedSettings) {
12692                    mSettings.setInstallerPackageName(packageName,
12693                            oldPkgSetting.installerPackageName);
12694                }
12695                mSettings.writeLPr();
12696            }
12697        }
12698    }
12699
12700    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12701        // Collect all used permissions in the UID
12702        ArraySet<String> usedPermissions = new ArraySet<>();
12703        final int packageCount = su.packages.size();
12704        for (int i = 0; i < packageCount; i++) {
12705            PackageSetting ps = su.packages.valueAt(i);
12706            if (ps.pkg == null) {
12707                continue;
12708            }
12709            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12710            for (int j = 0; j < requestedPermCount; j++) {
12711                String permission = ps.pkg.requestedPermissions.get(j);
12712                BasePermission bp = mSettings.mPermissions.get(permission);
12713                if (bp != null) {
12714                    usedPermissions.add(permission);
12715                }
12716            }
12717        }
12718
12719        PermissionsState permissionsState = su.getPermissionsState();
12720        // Prune install permissions
12721        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12722        final int installPermCount = installPermStates.size();
12723        for (int i = installPermCount - 1; i >= 0;  i--) {
12724            PermissionState permissionState = installPermStates.get(i);
12725            if (!usedPermissions.contains(permissionState.getName())) {
12726                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12727                if (bp != null) {
12728                    permissionsState.revokeInstallPermission(bp);
12729                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12730                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12731                }
12732            }
12733        }
12734
12735        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12736
12737        // Prune runtime permissions
12738        for (int userId : allUserIds) {
12739            List<PermissionState> runtimePermStates = permissionsState
12740                    .getRuntimePermissionStates(userId);
12741            final int runtimePermCount = runtimePermStates.size();
12742            for (int i = runtimePermCount - 1; i >= 0; i--) {
12743                PermissionState permissionState = runtimePermStates.get(i);
12744                if (!usedPermissions.contains(permissionState.getName())) {
12745                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12746                    if (bp != null) {
12747                        permissionsState.revokeRuntimePermission(bp, userId);
12748                        permissionsState.updatePermissionFlags(bp, userId,
12749                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12750                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12751                                runtimePermissionChangedUserIds, userId);
12752                    }
12753                }
12754            }
12755        }
12756
12757        return runtimePermissionChangedUserIds;
12758    }
12759
12760    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12761            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12762            UserHandle user) {
12763        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12764
12765        String pkgName = newPackage.packageName;
12766        synchronized (mPackages) {
12767            //write settings. the installStatus will be incomplete at this stage.
12768            //note that the new package setting would have already been
12769            //added to mPackages. It hasn't been persisted yet.
12770            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12771            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12772            mSettings.writeLPr();
12773            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12774        }
12775
12776        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12777        synchronized (mPackages) {
12778            updatePermissionsLPw(newPackage.packageName, newPackage,
12779                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12780                            ? UPDATE_PERMISSIONS_ALL : 0));
12781            // For system-bundled packages, we assume that installing an upgraded version
12782            // of the package implies that the user actually wants to run that new code,
12783            // so we enable the package.
12784            PackageSetting ps = mSettings.mPackages.get(pkgName);
12785            if (ps != null) {
12786                if (isSystemApp(newPackage)) {
12787                    // NB: implicit assumption that system package upgrades apply to all users
12788                    if (DEBUG_INSTALL) {
12789                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12790                    }
12791                    if (res.origUsers != null) {
12792                        for (int userHandle : res.origUsers) {
12793                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12794                                    userHandle, installerPackageName);
12795                        }
12796                    }
12797                    // Also convey the prior install/uninstall state
12798                    if (allUsers != null && perUserInstalled != null) {
12799                        for (int i = 0; i < allUsers.length; i++) {
12800                            if (DEBUG_INSTALL) {
12801                                Slog.d(TAG, "    user " + allUsers[i]
12802                                        + " => " + perUserInstalled[i]);
12803                            }
12804                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12805                        }
12806                        // these install state changes will be persisted in the
12807                        // upcoming call to mSettings.writeLPr().
12808                    }
12809                }
12810                // It's implied that when a user requests installation, they want the app to be
12811                // installed and enabled.
12812                int userId = user.getIdentifier();
12813                if (userId != UserHandle.USER_ALL) {
12814                    ps.setInstalled(true, userId);
12815                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12816                }
12817            }
12818            res.name = pkgName;
12819            res.uid = newPackage.applicationInfo.uid;
12820            res.pkg = newPackage;
12821            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12822            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12823            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12824            //to update install status
12825            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12826            mSettings.writeLPr();
12827            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12828        }
12829
12830        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12831    }
12832
12833    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12834        try {
12835            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12836            installPackageLI(args, res);
12837        } finally {
12838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12839        }
12840    }
12841
12842    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12843        final int installFlags = args.installFlags;
12844        final String installerPackageName = args.installerPackageName;
12845        final String volumeUuid = args.volumeUuid;
12846        final File tmpPackageFile = new File(args.getCodePath());
12847        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12848        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12849                || (args.volumeUuid != null));
12850        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12851        boolean replace = false;
12852        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12853        if (args.move != null) {
12854            // moving a complete application; perfom an initial scan on the new install location
12855            scanFlags |= SCAN_INITIAL;
12856        }
12857        // Result object to be returned
12858        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12859
12860        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12861
12862        // Sanity check
12863        if (ephemeral && (forwardLocked || onExternal)) {
12864            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12865                    + " external=" + onExternal);
12866            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12867            return;
12868        }
12869
12870        // Retrieve PackageSettings and parse package
12871        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12872                | PackageParser.PARSE_ENFORCE_CODE
12873                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12874                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12875                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12876        PackageParser pp = new PackageParser();
12877        pp.setSeparateProcesses(mSeparateProcesses);
12878        pp.setDisplayMetrics(mMetrics);
12879
12880        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12881        final PackageParser.Package pkg;
12882        try {
12883            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12884        } catch (PackageParserException e) {
12885            res.setError("Failed parse during installPackageLI", e);
12886            return;
12887        } finally {
12888            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12889        }
12890
12891        // Mark that we have an install time CPU ABI override.
12892        pkg.cpuAbiOverride = args.abiOverride;
12893
12894        String pkgName = res.name = pkg.packageName;
12895        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12896            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12897                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12898                return;
12899            }
12900        }
12901
12902        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12903        try {
12904            pp.collectCertificates(pkg, parseFlags);
12905        } catch (PackageParserException e) {
12906            res.setError("Failed collect during installPackageLI", e);
12907            return;
12908        } finally {
12909            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12910        }
12911
12912        // Get rid of all references to package scan path via parser.
12913        pp = null;
12914        String oldCodePath = null;
12915        boolean systemApp = false;
12916        synchronized (mPackages) {
12917            // Check if installing already existing package
12918            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12919                String oldName = mSettings.mRenamedPackages.get(pkgName);
12920                if (pkg.mOriginalPackages != null
12921                        && pkg.mOriginalPackages.contains(oldName)
12922                        && mPackages.containsKey(oldName)) {
12923                    // This package is derived from an original package,
12924                    // and this device has been updating from that original
12925                    // name.  We must continue using the original name, so
12926                    // rename the new package here.
12927                    pkg.setPackageName(oldName);
12928                    pkgName = pkg.packageName;
12929                    replace = true;
12930                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12931                            + oldName + " pkgName=" + pkgName);
12932                } else if (mPackages.containsKey(pkgName)) {
12933                    // This package, under its official name, already exists
12934                    // on the device; we should replace it.
12935                    replace = true;
12936                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12937                }
12938
12939                // Prevent apps opting out from runtime permissions
12940                if (replace) {
12941                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12942                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12943                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12944                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12945                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12946                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12947                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12948                                        + " doesn't support runtime permissions but the old"
12949                                        + " target SDK " + oldTargetSdk + " does.");
12950                        return;
12951                    }
12952                }
12953            }
12954
12955            PackageSetting ps = mSettings.mPackages.get(pkgName);
12956            if (ps != null) {
12957                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12958
12959                // Quick sanity check that we're signed correctly if updating;
12960                // we'll check this again later when scanning, but we want to
12961                // bail early here before tripping over redefined permissions.
12962                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12963                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12964                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12965                                + pkg.packageName + " upgrade keys do not match the "
12966                                + "previously installed version");
12967                        return;
12968                    }
12969                } else {
12970                    try {
12971                        verifySignaturesLP(ps, pkg);
12972                    } catch (PackageManagerException e) {
12973                        res.setError(e.error, e.getMessage());
12974                        return;
12975                    }
12976                }
12977
12978                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12979                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12980                    systemApp = (ps.pkg.applicationInfo.flags &
12981                            ApplicationInfo.FLAG_SYSTEM) != 0;
12982                }
12983                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12984            }
12985
12986            // Check whether the newly-scanned package wants to define an already-defined perm
12987            int N = pkg.permissions.size();
12988            for (int i = N-1; i >= 0; i--) {
12989                PackageParser.Permission perm = pkg.permissions.get(i);
12990                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12991                if (bp != null) {
12992                    // If the defining package is signed with our cert, it's okay.  This
12993                    // also includes the "updating the same package" case, of course.
12994                    // "updating same package" could also involve key-rotation.
12995                    final boolean sigsOk;
12996                    if (bp.sourcePackage.equals(pkg.packageName)
12997                            && (bp.packageSetting instanceof PackageSetting)
12998                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12999                                    scanFlags))) {
13000                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13001                    } else {
13002                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13003                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13004                    }
13005                    if (!sigsOk) {
13006                        // If the owning package is the system itself, we log but allow
13007                        // install to proceed; we fail the install on all other permission
13008                        // redefinitions.
13009                        if (!bp.sourcePackage.equals("android")) {
13010                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13011                                    + pkg.packageName + " attempting to redeclare permission "
13012                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13013                            res.origPermission = perm.info.name;
13014                            res.origPackage = bp.sourcePackage;
13015                            return;
13016                        } else {
13017                            Slog.w(TAG, "Package " + pkg.packageName
13018                                    + " attempting to redeclare system permission "
13019                                    + perm.info.name + "; ignoring new declaration");
13020                            pkg.permissions.remove(i);
13021                        }
13022                    }
13023                }
13024            }
13025
13026        }
13027
13028        if (systemApp) {
13029            if (onExternal) {
13030                // Abort update; system app can't be replaced with app on sdcard
13031                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13032                        "Cannot install updates to system apps on sdcard");
13033                return;
13034            } else if (ephemeral) {
13035                // Abort update; system app can't be replaced with an ephemeral app
13036                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13037                        "Cannot update a system app with an ephemeral app");
13038                return;
13039            }
13040        }
13041
13042        if (args.move != null) {
13043            // We did an in-place move, so dex is ready to roll
13044            scanFlags |= SCAN_NO_DEX;
13045            scanFlags |= SCAN_MOVE;
13046
13047            synchronized (mPackages) {
13048                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13049                if (ps == null) {
13050                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13051                            "Missing settings for moved package " + pkgName);
13052                }
13053
13054                // We moved the entire application as-is, so bring over the
13055                // previously derived ABI information.
13056                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13057                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13058            }
13059
13060        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13061            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13062            scanFlags |= SCAN_NO_DEX;
13063
13064            try {
13065                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13066                        true /* extract libs */);
13067            } catch (PackageManagerException pme) {
13068                Slog.e(TAG, "Error deriving application ABI", pme);
13069                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13070                return;
13071            }
13072        }
13073
13074        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13075            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13076            return;
13077        }
13078
13079        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13080
13081        if (replace) {
13082            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13083                    installerPackageName, volumeUuid, res);
13084        } else {
13085            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13086                    args.user, installerPackageName, volumeUuid, res);
13087        }
13088        synchronized (mPackages) {
13089            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13090            if (ps != null) {
13091                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13092            }
13093        }
13094    }
13095
13096    private void startIntentFilterVerifications(int userId, boolean replacing,
13097            PackageParser.Package pkg) {
13098        if (mIntentFilterVerifierComponent == null) {
13099            Slog.w(TAG, "No IntentFilter verification will not be done as "
13100                    + "there is no IntentFilterVerifier available!");
13101            return;
13102        }
13103
13104        final int verifierUid = getPackageUid(
13105                mIntentFilterVerifierComponent.getPackageName(),
13106                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13107
13108        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13109        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13110        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13111        mHandler.sendMessage(msg);
13112    }
13113
13114    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13115            PackageParser.Package pkg) {
13116        int size = pkg.activities.size();
13117        if (size == 0) {
13118            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13119                    "No activity, so no need to verify any IntentFilter!");
13120            return;
13121        }
13122
13123        final boolean hasDomainURLs = hasDomainURLs(pkg);
13124        if (!hasDomainURLs) {
13125            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13126                    "No domain URLs, so no need to verify any IntentFilter!");
13127            return;
13128        }
13129
13130        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13131                + " if any IntentFilter from the " + size
13132                + " Activities needs verification ...");
13133
13134        int count = 0;
13135        final String packageName = pkg.packageName;
13136
13137        synchronized (mPackages) {
13138            // If this is a new install and we see that we've already run verification for this
13139            // package, we have nothing to do: it means the state was restored from backup.
13140            if (!replacing) {
13141                IntentFilterVerificationInfo ivi =
13142                        mSettings.getIntentFilterVerificationLPr(packageName);
13143                if (ivi != null) {
13144                    if (DEBUG_DOMAIN_VERIFICATION) {
13145                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13146                                + ivi.getStatusString());
13147                    }
13148                    return;
13149                }
13150            }
13151
13152            // If any filters need to be verified, then all need to be.
13153            boolean needToVerify = false;
13154            for (PackageParser.Activity a : pkg.activities) {
13155                for (ActivityIntentInfo filter : a.intents) {
13156                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13157                        if (DEBUG_DOMAIN_VERIFICATION) {
13158                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13159                        }
13160                        needToVerify = true;
13161                        break;
13162                    }
13163                }
13164            }
13165
13166            if (needToVerify) {
13167                final int verificationId = mIntentFilterVerificationToken++;
13168                for (PackageParser.Activity a : pkg.activities) {
13169                    for (ActivityIntentInfo filter : a.intents) {
13170                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13171                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13172                                    "Verification needed for IntentFilter:" + filter.toString());
13173                            mIntentFilterVerifier.addOneIntentFilterVerification(
13174                                    verifierUid, userId, verificationId, filter, packageName);
13175                            count++;
13176                        }
13177                    }
13178                }
13179            }
13180        }
13181
13182        if (count > 0) {
13183            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13184                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13185                    +  " for userId:" + userId);
13186            mIntentFilterVerifier.startVerifications(userId);
13187        } else {
13188            if (DEBUG_DOMAIN_VERIFICATION) {
13189                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13190            }
13191        }
13192    }
13193
13194    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13195        final ComponentName cn  = filter.activity.getComponentName();
13196        final String packageName = cn.getPackageName();
13197
13198        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13199                packageName);
13200        if (ivi == null) {
13201            return true;
13202        }
13203        int status = ivi.getStatus();
13204        switch (status) {
13205            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13206            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13207                return true;
13208
13209            default:
13210                // Nothing to do
13211                return false;
13212        }
13213    }
13214
13215    private static boolean isMultiArch(ApplicationInfo info) {
13216        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13217    }
13218
13219    private static boolean isExternal(PackageParser.Package pkg) {
13220        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13221    }
13222
13223    private static boolean isExternal(PackageSetting ps) {
13224        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13225    }
13226
13227    private static boolean isEphemeral(PackageParser.Package pkg) {
13228        return pkg.applicationInfo.isEphemeralApp();
13229    }
13230
13231    private static boolean isEphemeral(PackageSetting ps) {
13232        return ps.pkg != null && isEphemeral(ps.pkg);
13233    }
13234
13235    private static boolean isSystemApp(PackageParser.Package pkg) {
13236        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13237    }
13238
13239    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13240        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13241    }
13242
13243    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13244        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13245    }
13246
13247    private static boolean isSystemApp(PackageSetting ps) {
13248        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13249    }
13250
13251    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13252        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13253    }
13254
13255    private int packageFlagsToInstallFlags(PackageSetting ps) {
13256        int installFlags = 0;
13257        if (isEphemeral(ps)) {
13258            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13259        }
13260        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13261            // This existing package was an external ASEC install when we have
13262            // the external flag without a UUID
13263            installFlags |= PackageManager.INSTALL_EXTERNAL;
13264        }
13265        if (ps.isForwardLocked()) {
13266            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13267        }
13268        return installFlags;
13269    }
13270
13271    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13272        if (isExternal(pkg)) {
13273            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13274                return StorageManager.UUID_PRIMARY_PHYSICAL;
13275            } else {
13276                return pkg.volumeUuid;
13277            }
13278        } else {
13279            return StorageManager.UUID_PRIVATE_INTERNAL;
13280        }
13281    }
13282
13283    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13284        if (isExternal(pkg)) {
13285            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13286                return mSettings.getExternalVersion();
13287            } else {
13288                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13289            }
13290        } else {
13291            return mSettings.getInternalVersion();
13292        }
13293    }
13294
13295    private void deleteTempPackageFiles() {
13296        final FilenameFilter filter = new FilenameFilter() {
13297            public boolean accept(File dir, String name) {
13298                return name.startsWith("vmdl") && name.endsWith(".tmp");
13299            }
13300        };
13301        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13302            file.delete();
13303        }
13304    }
13305
13306    @Override
13307    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13308            int flags) {
13309        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13310                flags);
13311    }
13312
13313    @Override
13314    public void deletePackage(final String packageName,
13315            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13316        mContext.enforceCallingOrSelfPermission(
13317                android.Manifest.permission.DELETE_PACKAGES, null);
13318        Preconditions.checkNotNull(packageName);
13319        Preconditions.checkNotNull(observer);
13320        final int uid = Binder.getCallingUid();
13321        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13322        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13323        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13324            mContext.enforceCallingOrSelfPermission(
13325                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13326                    "deletePackage for user " + userId);
13327        }
13328
13329        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13330            try {
13331                observer.onPackageDeleted(packageName,
13332                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13333            } catch (RemoteException re) {
13334            }
13335            return;
13336        }
13337
13338        for (int currentUserId : users) {
13339            if (getBlockUninstallForUser(packageName, currentUserId)) {
13340                try {
13341                    observer.onPackageDeleted(packageName,
13342                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13343                } catch (RemoteException re) {
13344                }
13345                return;
13346            }
13347        }
13348
13349        if (DEBUG_REMOVE) {
13350            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13351        }
13352        // Queue up an async operation since the package deletion may take a little while.
13353        mHandler.post(new Runnable() {
13354            public void run() {
13355                mHandler.removeCallbacks(this);
13356                final int returnCode = deletePackageX(packageName, userId, flags);
13357                try {
13358                    observer.onPackageDeleted(packageName, returnCode, null);
13359                } catch (RemoteException e) {
13360                    Log.i(TAG, "Observer no longer exists.");
13361                } //end catch
13362            } //end run
13363        });
13364    }
13365
13366    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13367        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13368                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13369        try {
13370            if (dpm != null) {
13371                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13372                        /* callingUserOnly =*/ false);
13373                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13374                        : deviceOwnerComponentName.getPackageName();
13375                // Does the package contains the device owner?
13376                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13377                // this check is probably not needed, since DO should be registered as a device
13378                // admin on some user too. (Original bug for this: b/17657954)
13379                if (packageName.equals(deviceOwnerPackageName)) {
13380                    return true;
13381                }
13382                // Does it contain a device admin for any user?
13383                int[] users;
13384                if (userId == UserHandle.USER_ALL) {
13385                    users = sUserManager.getUserIds();
13386                } else {
13387                    users = new int[]{userId};
13388                }
13389                for (int i = 0; i < users.length; ++i) {
13390                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13391                        return true;
13392                    }
13393                }
13394            }
13395        } catch (RemoteException e) {
13396        }
13397        return false;
13398    }
13399
13400    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13401        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13402    }
13403
13404    /**
13405     *  This method is an internal method that could be get invoked either
13406     *  to delete an installed package or to clean up a failed installation.
13407     *  After deleting an installed package, a broadcast is sent to notify any
13408     *  listeners that the package has been installed. For cleaning up a failed
13409     *  installation, the broadcast is not necessary since the package's
13410     *  installation wouldn't have sent the initial broadcast either
13411     *  The key steps in deleting a package are
13412     *  deleting the package information in internal structures like mPackages,
13413     *  deleting the packages base directories through installd
13414     *  updating mSettings to reflect current status
13415     *  persisting settings for later use
13416     *  sending a broadcast if necessary
13417     */
13418    private int deletePackageX(String packageName, int userId, int flags) {
13419        final PackageRemovedInfo info = new PackageRemovedInfo();
13420        final boolean res;
13421
13422        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13423                ? UserHandle.ALL : new UserHandle(userId);
13424
13425        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13426            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13427            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13428        }
13429
13430        boolean removedForAllUsers = false;
13431        boolean systemUpdate = false;
13432
13433        PackageParser.Package uninstalledPkg;
13434
13435        // for the uninstall-updates case and restricted profiles, remember the per-
13436        // userhandle installed state
13437        int[] allUsers;
13438        boolean[] perUserInstalled;
13439        synchronized (mPackages) {
13440            uninstalledPkg = mPackages.get(packageName);
13441            PackageSetting ps = mSettings.mPackages.get(packageName);
13442            allUsers = sUserManager.getUserIds();
13443            perUserInstalled = new boolean[allUsers.length];
13444            for (int i = 0; i < allUsers.length; i++) {
13445                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13446            }
13447        }
13448
13449        synchronized (mInstallLock) {
13450            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13451            res = deletePackageLI(packageName, removeForUser,
13452                    true, allUsers, perUserInstalled,
13453                    flags | REMOVE_CHATTY, info, true);
13454            systemUpdate = info.isRemovedPackageSystemUpdate;
13455            synchronized (mPackages) {
13456                if (res) {
13457                    if (!systemUpdate && mPackages.get(packageName) == null) {
13458                        removedForAllUsers = true;
13459                    }
13460                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13461                }
13462            }
13463            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13464                    + " removedForAllUsers=" + removedForAllUsers);
13465        }
13466
13467        if (res) {
13468            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13469
13470            // If the removed package was a system update, the old system package
13471            // was re-enabled; we need to broadcast this information
13472            if (systemUpdate) {
13473                Bundle extras = new Bundle(1);
13474                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13475                        ? info.removedAppId : info.uid);
13476                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13477
13478                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13479                        extras, 0, null, null, null);
13480                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13481                        extras, 0, null, null, null);
13482                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13483                        null, 0, packageName, null, null);
13484            }
13485        }
13486        // Force a gc here.
13487        Runtime.getRuntime().gc();
13488        // Delete the resources here after sending the broadcast to let
13489        // other processes clean up before deleting resources.
13490        if (info.args != null) {
13491            synchronized (mInstallLock) {
13492                info.args.doPostDeleteLI(true);
13493            }
13494        }
13495
13496        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13497    }
13498
13499    class PackageRemovedInfo {
13500        String removedPackage;
13501        int uid = -1;
13502        int removedAppId = -1;
13503        int[] removedUsers = null;
13504        boolean isRemovedPackageSystemUpdate = false;
13505        // Clean up resources deleted packages.
13506        InstallArgs args = null;
13507
13508        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13509            Bundle extras = new Bundle(1);
13510            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13511            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13512            if (replacing) {
13513                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13514            }
13515            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13516            if (removedPackage != null) {
13517                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13518                        extras, 0, null, null, removedUsers);
13519                if (fullRemove && !replacing) {
13520                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13521                            extras, 0, null, null, removedUsers);
13522                }
13523            }
13524            if (removedAppId >= 0) {
13525                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13526                        removedUsers);
13527            }
13528        }
13529    }
13530
13531    /*
13532     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13533     * flag is not set, the data directory is removed as well.
13534     * make sure this flag is set for partially installed apps. If not its meaningless to
13535     * delete a partially installed application.
13536     */
13537    private void removePackageDataLI(PackageSetting ps,
13538            int[] allUserHandles, boolean[] perUserInstalled,
13539            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13540        String packageName = ps.name;
13541        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13542        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13543        // Retrieve object to delete permissions for shared user later on
13544        final PackageSetting deletedPs;
13545        // reader
13546        synchronized (mPackages) {
13547            deletedPs = mSettings.mPackages.get(packageName);
13548            if (outInfo != null) {
13549                outInfo.removedPackage = packageName;
13550                outInfo.removedUsers = deletedPs != null
13551                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13552                        : null;
13553            }
13554        }
13555        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13556            removeDataDirsLI(ps.volumeUuid, packageName);
13557            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13558        }
13559        // writer
13560        synchronized (mPackages) {
13561            if (deletedPs != null) {
13562                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13563                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13564                    clearDefaultBrowserIfNeeded(packageName);
13565                    if (outInfo != null) {
13566                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13567                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13568                    }
13569                    updatePermissionsLPw(deletedPs.name, null, 0);
13570                    if (deletedPs.sharedUser != null) {
13571                        // Remove permissions associated with package. Since runtime
13572                        // permissions are per user we have to kill the removed package
13573                        // or packages running under the shared user of the removed
13574                        // package if revoking the permissions requested only by the removed
13575                        // package is successful and this causes a change in gids.
13576                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13577                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13578                                    userId);
13579                            if (userIdToKill == UserHandle.USER_ALL
13580                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13581                                // If gids changed for this user, kill all affected packages.
13582                                mHandler.post(new Runnable() {
13583                                    @Override
13584                                    public void run() {
13585                                        // This has to happen with no lock held.
13586                                        killApplication(deletedPs.name, deletedPs.appId,
13587                                                KILL_APP_REASON_GIDS_CHANGED);
13588                                    }
13589                                });
13590                                break;
13591                            }
13592                        }
13593                    }
13594                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13595                }
13596                // make sure to preserve per-user disabled state if this removal was just
13597                // a downgrade of a system app to the factory package
13598                if (allUserHandles != null && perUserInstalled != null) {
13599                    if (DEBUG_REMOVE) {
13600                        Slog.d(TAG, "Propagating install state across downgrade");
13601                    }
13602                    for (int i = 0; i < allUserHandles.length; i++) {
13603                        if (DEBUG_REMOVE) {
13604                            Slog.d(TAG, "    user " + allUserHandles[i]
13605                                    + " => " + perUserInstalled[i]);
13606                        }
13607                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13608                    }
13609                }
13610            }
13611            // can downgrade to reader
13612            if (writeSettings) {
13613                // Save settings now
13614                mSettings.writeLPr();
13615            }
13616        }
13617        if (outInfo != null) {
13618            // A user ID was deleted here. Go through all users and remove it
13619            // from KeyStore.
13620            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13621        }
13622    }
13623
13624    static boolean locationIsPrivileged(File path) {
13625        try {
13626            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13627                    .getCanonicalPath();
13628            return path.getCanonicalPath().startsWith(privilegedAppDir);
13629        } catch (IOException e) {
13630            Slog.e(TAG, "Unable to access code path " + path);
13631        }
13632        return false;
13633    }
13634
13635    /*
13636     * Tries to delete system package.
13637     */
13638    private boolean deleteSystemPackageLI(PackageSetting newPs,
13639            int[] allUserHandles, boolean[] perUserInstalled,
13640            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13641        final boolean applyUserRestrictions
13642                = (allUserHandles != null) && (perUserInstalled != null);
13643        PackageSetting disabledPs = null;
13644        // Confirm if the system package has been updated
13645        // An updated system app can be deleted. This will also have to restore
13646        // the system pkg from system partition
13647        // reader
13648        synchronized (mPackages) {
13649            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13650        }
13651        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13652                + " disabledPs=" + disabledPs);
13653        if (disabledPs == null) {
13654            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13655            return false;
13656        } else if (DEBUG_REMOVE) {
13657            Slog.d(TAG, "Deleting system pkg from data partition");
13658        }
13659        if (DEBUG_REMOVE) {
13660            if (applyUserRestrictions) {
13661                Slog.d(TAG, "Remembering install states:");
13662                for (int i = 0; i < allUserHandles.length; i++) {
13663                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13664                }
13665            }
13666        }
13667        // Delete the updated package
13668        outInfo.isRemovedPackageSystemUpdate = true;
13669        if (disabledPs.versionCode < newPs.versionCode) {
13670            // Delete data for downgrades
13671            flags &= ~PackageManager.DELETE_KEEP_DATA;
13672        } else {
13673            // Preserve data by setting flag
13674            flags |= PackageManager.DELETE_KEEP_DATA;
13675        }
13676        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13677                allUserHandles, perUserInstalled, outInfo, writeSettings);
13678        if (!ret) {
13679            return false;
13680        }
13681        // writer
13682        synchronized (mPackages) {
13683            // Reinstate the old system package
13684            mSettings.enableSystemPackageLPw(newPs.name);
13685            // Remove any native libraries from the upgraded package.
13686            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13687        }
13688        // Install the system package
13689        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13690        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13691        if (locationIsPrivileged(disabledPs.codePath)) {
13692            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13693        }
13694
13695        final PackageParser.Package newPkg;
13696        try {
13697            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13698        } catch (PackageManagerException e) {
13699            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13700            return false;
13701        }
13702
13703        // writer
13704        synchronized (mPackages) {
13705            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13706
13707            // Propagate the permissions state as we do not want to drop on the floor
13708            // runtime permissions. The update permissions method below will take
13709            // care of removing obsolete permissions and grant install permissions.
13710            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13711            updatePermissionsLPw(newPkg.packageName, newPkg,
13712                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13713
13714            if (applyUserRestrictions) {
13715                if (DEBUG_REMOVE) {
13716                    Slog.d(TAG, "Propagating install state across reinstall");
13717                }
13718                for (int i = 0; i < allUserHandles.length; i++) {
13719                    if (DEBUG_REMOVE) {
13720                        Slog.d(TAG, "    user " + allUserHandles[i]
13721                                + " => " + perUserInstalled[i]);
13722                    }
13723                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13724
13725                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13726                }
13727                // Regardless of writeSettings we need to ensure that this restriction
13728                // state propagation is persisted
13729                mSettings.writeAllUsersPackageRestrictionsLPr();
13730            }
13731            // can downgrade to reader here
13732            if (writeSettings) {
13733                mSettings.writeLPr();
13734            }
13735        }
13736        return true;
13737    }
13738
13739    private boolean deleteInstalledPackageLI(PackageSetting ps,
13740            boolean deleteCodeAndResources, int flags,
13741            int[] allUserHandles, boolean[] perUserInstalled,
13742            PackageRemovedInfo outInfo, boolean writeSettings) {
13743        if (outInfo != null) {
13744            outInfo.uid = ps.appId;
13745        }
13746
13747        // Delete package data from internal structures and also remove data if flag is set
13748        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13749
13750        // Delete application code and resources
13751        if (deleteCodeAndResources && (outInfo != null)) {
13752            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13753                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13754            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13755        }
13756        return true;
13757    }
13758
13759    @Override
13760    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13761            int userId) {
13762        mContext.enforceCallingOrSelfPermission(
13763                android.Manifest.permission.DELETE_PACKAGES, null);
13764        synchronized (mPackages) {
13765            PackageSetting ps = mSettings.mPackages.get(packageName);
13766            if (ps == null) {
13767                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13768                return false;
13769            }
13770            if (!ps.getInstalled(userId)) {
13771                // Can't block uninstall for an app that is not installed or enabled.
13772                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13773                return false;
13774            }
13775            ps.setBlockUninstall(blockUninstall, userId);
13776            mSettings.writePackageRestrictionsLPr(userId);
13777        }
13778        return true;
13779    }
13780
13781    @Override
13782    public boolean getBlockUninstallForUser(String packageName, int userId) {
13783        synchronized (mPackages) {
13784            PackageSetting ps = mSettings.mPackages.get(packageName);
13785            if (ps == null) {
13786                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13787                return false;
13788            }
13789            return ps.getBlockUninstall(userId);
13790        }
13791    }
13792
13793    @Override
13794    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13795        int callingUid = Binder.getCallingUid();
13796        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13797            throw new SecurityException(
13798                    "setRequiredForSystemUser can only be run by the system or root");
13799        }
13800        synchronized (mPackages) {
13801            PackageSetting ps = mSettings.mPackages.get(packageName);
13802            if (ps == null) {
13803                Log.w(TAG, "Package doesn't exist: " + packageName);
13804                return false;
13805            }
13806            if (systemUserApp) {
13807                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13808            } else {
13809                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13810            }
13811            mSettings.writeLPr();
13812        }
13813        return true;
13814    }
13815
13816    /*
13817     * This method handles package deletion in general
13818     */
13819    private boolean deletePackageLI(String packageName, UserHandle user,
13820            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13821            int flags, PackageRemovedInfo outInfo,
13822            boolean writeSettings) {
13823        if (packageName == null) {
13824            Slog.w(TAG, "Attempt to delete null packageName.");
13825            return false;
13826        }
13827        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13828        PackageSetting ps;
13829        boolean dataOnly = false;
13830        int removeUser = -1;
13831        int appId = -1;
13832        synchronized (mPackages) {
13833            ps = mSettings.mPackages.get(packageName);
13834            if (ps == null) {
13835                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13836                return false;
13837            }
13838            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13839                    && user.getIdentifier() != UserHandle.USER_ALL) {
13840                // The caller is asking that the package only be deleted for a single
13841                // user.  To do this, we just mark its uninstalled state and delete
13842                // its data.  If this is a system app, we only allow this to happen if
13843                // they have set the special DELETE_SYSTEM_APP which requests different
13844                // semantics than normal for uninstalling system apps.
13845                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13846                final int userId = user.getIdentifier();
13847                ps.setUserState(userId,
13848                        COMPONENT_ENABLED_STATE_DEFAULT,
13849                        false, //installed
13850                        true,  //stopped
13851                        true,  //notLaunched
13852                        false, //hidden
13853                        false, //suspended
13854                        null, null, null,
13855                        false, // blockUninstall
13856                        ps.readUserState(userId).domainVerificationStatus, 0);
13857                if (!isSystemApp(ps)) {
13858                    // Do not uninstall the APK if an app should be cached
13859                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13860                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13861                        // Other user still have this package installed, so all
13862                        // we need to do is clear this user's data and save that
13863                        // it is uninstalled.
13864                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13865                        removeUser = user.getIdentifier();
13866                        appId = ps.appId;
13867                        scheduleWritePackageRestrictionsLocked(removeUser);
13868                    } else {
13869                        // We need to set it back to 'installed' so the uninstall
13870                        // broadcasts will be sent correctly.
13871                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13872                        ps.setInstalled(true, user.getIdentifier());
13873                    }
13874                } else {
13875                    // This is a system app, so we assume that the
13876                    // other users still have this package installed, so all
13877                    // we need to do is clear this user's data and save that
13878                    // it is uninstalled.
13879                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13880                    removeUser = user.getIdentifier();
13881                    appId = ps.appId;
13882                    scheduleWritePackageRestrictionsLocked(removeUser);
13883                }
13884            }
13885        }
13886
13887        if (removeUser >= 0) {
13888            // From above, we determined that we are deleting this only
13889            // for a single user.  Continue the work here.
13890            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13891            if (outInfo != null) {
13892                outInfo.removedPackage = packageName;
13893                outInfo.removedAppId = appId;
13894                outInfo.removedUsers = new int[] {removeUser};
13895            }
13896            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13897            removeKeystoreDataIfNeeded(removeUser, appId);
13898            schedulePackageCleaning(packageName, removeUser, false);
13899            synchronized (mPackages) {
13900                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13901                    scheduleWritePackageRestrictionsLocked(removeUser);
13902                }
13903                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13904            }
13905            return true;
13906        }
13907
13908        if (dataOnly) {
13909            // Delete application data first
13910            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13911            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13912            return true;
13913        }
13914
13915        boolean ret = false;
13916        if (isSystemApp(ps)) {
13917            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13918            // When an updated system application is deleted we delete the existing resources as well and
13919            // fall back to existing code in system partition
13920            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13921                    flags, outInfo, writeSettings);
13922        } else {
13923            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13924            // Kill application pre-emptively especially for apps on sd.
13925            killApplication(packageName, ps.appId, "uninstall pkg");
13926            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13927                    allUserHandles, perUserInstalled,
13928                    outInfo, writeSettings);
13929        }
13930
13931        return ret;
13932    }
13933
13934    private final static class ClearStorageConnection implements ServiceConnection {
13935        IMediaContainerService mContainerService;
13936
13937        @Override
13938        public void onServiceConnected(ComponentName name, IBinder service) {
13939            synchronized (this) {
13940                mContainerService = IMediaContainerService.Stub.asInterface(service);
13941                notifyAll();
13942            }
13943        }
13944
13945        @Override
13946        public void onServiceDisconnected(ComponentName name) {
13947        }
13948    }
13949
13950    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13951        final boolean mounted;
13952        if (Environment.isExternalStorageEmulated()) {
13953            mounted = true;
13954        } else {
13955            final String status = Environment.getExternalStorageState();
13956
13957            mounted = status.equals(Environment.MEDIA_MOUNTED)
13958                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13959        }
13960
13961        if (!mounted) {
13962            return;
13963        }
13964
13965        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13966        int[] users;
13967        if (userId == UserHandle.USER_ALL) {
13968            users = sUserManager.getUserIds();
13969        } else {
13970            users = new int[] { userId };
13971        }
13972        final ClearStorageConnection conn = new ClearStorageConnection();
13973        if (mContext.bindServiceAsUser(
13974                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13975            try {
13976                for (int curUser : users) {
13977                    long timeout = SystemClock.uptimeMillis() + 5000;
13978                    synchronized (conn) {
13979                        long now = SystemClock.uptimeMillis();
13980                        while (conn.mContainerService == null && now < timeout) {
13981                            try {
13982                                conn.wait(timeout - now);
13983                            } catch (InterruptedException e) {
13984                            }
13985                        }
13986                    }
13987                    if (conn.mContainerService == null) {
13988                        return;
13989                    }
13990
13991                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13992                    clearDirectory(conn.mContainerService,
13993                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13994                    if (allData) {
13995                        clearDirectory(conn.mContainerService,
13996                                userEnv.buildExternalStorageAppDataDirs(packageName));
13997                        clearDirectory(conn.mContainerService,
13998                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13999                    }
14000                }
14001            } finally {
14002                mContext.unbindService(conn);
14003            }
14004        }
14005    }
14006
14007    @Override
14008    public void clearApplicationUserData(final String packageName,
14009            final IPackageDataObserver observer, final int userId) {
14010        mContext.enforceCallingOrSelfPermission(
14011                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
14012        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
14013        // Queue up an async operation since the package deletion may take a little while.
14014        mHandler.post(new Runnable() {
14015            public void run() {
14016                mHandler.removeCallbacks(this);
14017                final boolean succeeded;
14018                synchronized (mInstallLock) {
14019                    succeeded = clearApplicationUserDataLI(packageName, userId);
14020                }
14021                clearExternalStorageDataSync(packageName, userId, true);
14022                if (succeeded) {
14023                    // invoke DeviceStorageMonitor's update method to clear any notifications
14024                    DeviceStorageMonitorInternal
14025                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14026                    if (dsm != null) {
14027                        dsm.checkMemory();
14028                    }
14029                }
14030                if(observer != null) {
14031                    try {
14032                        observer.onRemoveCompleted(packageName, succeeded);
14033                    } catch (RemoteException e) {
14034                        Log.i(TAG, "Observer no longer exists.");
14035                    }
14036                } //end if observer
14037            } //end run
14038        });
14039    }
14040
14041    private boolean clearApplicationUserDataLI(String packageName, int userId) {
14042        if (packageName == null) {
14043            Slog.w(TAG, "Attempt to delete null packageName.");
14044            return false;
14045        }
14046
14047        // Try finding details about the requested package
14048        PackageParser.Package pkg;
14049        synchronized (mPackages) {
14050            pkg = mPackages.get(packageName);
14051            if (pkg == null) {
14052                final PackageSetting ps = mSettings.mPackages.get(packageName);
14053                if (ps != null) {
14054                    pkg = ps.pkg;
14055                }
14056            }
14057
14058            if (pkg == null) {
14059                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14060                return false;
14061            }
14062
14063            PackageSetting ps = (PackageSetting) pkg.mExtras;
14064            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14065        }
14066
14067        // Always delete data directories for package, even if we found no other
14068        // record of app. This helps users recover from UID mismatches without
14069        // resorting to a full data wipe.
14070        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14071        if (retCode < 0) {
14072            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
14073            return false;
14074        }
14075
14076        final int appId = pkg.applicationInfo.uid;
14077        removeKeystoreDataIfNeeded(userId, appId);
14078
14079        // Create a native library symlink only if we have native libraries
14080        // and if the native libraries are 32 bit libraries. We do not provide
14081        // this symlink for 64 bit libraries.
14082        if (pkg.applicationInfo.primaryCpuAbi != null &&
14083                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14084            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14085            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14086                    nativeLibPath, userId) < 0) {
14087                Slog.w(TAG, "Failed linking native library dir");
14088                return false;
14089            }
14090        }
14091
14092        return true;
14093    }
14094
14095    /**
14096     * Reverts user permission state changes (permissions and flags) in
14097     * all packages for a given user.
14098     *
14099     * @param userId The device user for which to do a reset.
14100     */
14101    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14102        final int packageCount = mPackages.size();
14103        for (int i = 0; i < packageCount; i++) {
14104            PackageParser.Package pkg = mPackages.valueAt(i);
14105            PackageSetting ps = (PackageSetting) pkg.mExtras;
14106            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14107        }
14108    }
14109
14110    /**
14111     * Reverts user permission state changes (permissions and flags).
14112     *
14113     * @param ps The package for which to reset.
14114     * @param userId The device user for which to do a reset.
14115     */
14116    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14117            final PackageSetting ps, final int userId) {
14118        if (ps.pkg == null) {
14119            return;
14120        }
14121
14122        // These are flags that can change base on user actions.
14123        final int userSettableMask = FLAG_PERMISSION_USER_SET
14124                | FLAG_PERMISSION_USER_FIXED
14125                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14126                | FLAG_PERMISSION_REVIEW_REQUIRED;
14127
14128        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14129                | FLAG_PERMISSION_POLICY_FIXED;
14130
14131        boolean writeInstallPermissions = false;
14132        boolean writeRuntimePermissions = false;
14133
14134        final int permissionCount = ps.pkg.requestedPermissions.size();
14135        for (int i = 0; i < permissionCount; i++) {
14136            String permission = ps.pkg.requestedPermissions.get(i);
14137
14138            BasePermission bp = mSettings.mPermissions.get(permission);
14139            if (bp == null) {
14140                continue;
14141            }
14142
14143            // If shared user we just reset the state to which only this app contributed.
14144            if (ps.sharedUser != null) {
14145                boolean used = false;
14146                final int packageCount = ps.sharedUser.packages.size();
14147                for (int j = 0; j < packageCount; j++) {
14148                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14149                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14150                            && pkg.pkg.requestedPermissions.contains(permission)) {
14151                        used = true;
14152                        break;
14153                    }
14154                }
14155                if (used) {
14156                    continue;
14157                }
14158            }
14159
14160            PermissionsState permissionsState = ps.getPermissionsState();
14161
14162            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14163
14164            // Always clear the user settable flags.
14165            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14166                    bp.name) != null;
14167            // If permission review is enabled and this is a legacy app, mark the
14168            // permission as requiring a review as this is the initial state.
14169            int flags = 0;
14170            if (Build.PERMISSIONS_REVIEW_REQUIRED
14171                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14172                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14173            }
14174            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14175                if (hasInstallState) {
14176                    writeInstallPermissions = true;
14177                } else {
14178                    writeRuntimePermissions = true;
14179                }
14180            }
14181
14182            // Below is only runtime permission handling.
14183            if (!bp.isRuntime()) {
14184                continue;
14185            }
14186
14187            // Never clobber system or policy.
14188            if ((oldFlags & policyOrSystemFlags) != 0) {
14189                continue;
14190            }
14191
14192            // If this permission was granted by default, make sure it is.
14193            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14194                if (permissionsState.grantRuntimePermission(bp, userId)
14195                        != PERMISSION_OPERATION_FAILURE) {
14196                    writeRuntimePermissions = true;
14197                }
14198            // If permission review is enabled the permissions for a legacy apps
14199            // are represented as constantly granted runtime ones, so don't revoke.
14200            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14201                // Otherwise, reset the permission.
14202                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14203                switch (revokeResult) {
14204                    case PERMISSION_OPERATION_SUCCESS: {
14205                        writeRuntimePermissions = true;
14206                    } break;
14207
14208                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14209                        writeRuntimePermissions = true;
14210                        final int appId = ps.appId;
14211                        mHandler.post(new Runnable() {
14212                            @Override
14213                            public void run() {
14214                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14215                            }
14216                        });
14217                    } break;
14218                }
14219            }
14220        }
14221
14222        // Synchronously write as we are taking permissions away.
14223        if (writeRuntimePermissions) {
14224            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14225        }
14226
14227        // Synchronously write as we are taking permissions away.
14228        if (writeInstallPermissions) {
14229            mSettings.writeLPr();
14230        }
14231    }
14232
14233    /**
14234     * Remove entries from the keystore daemon. Will only remove it if the
14235     * {@code appId} is valid.
14236     */
14237    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14238        if (appId < 0) {
14239            return;
14240        }
14241
14242        final KeyStore keyStore = KeyStore.getInstance();
14243        if (keyStore != null) {
14244            if (userId == UserHandle.USER_ALL) {
14245                for (final int individual : sUserManager.getUserIds()) {
14246                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14247                }
14248            } else {
14249                keyStore.clearUid(UserHandle.getUid(userId, appId));
14250            }
14251        } else {
14252            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14253        }
14254    }
14255
14256    @Override
14257    public void deleteApplicationCacheFiles(final String packageName,
14258            final IPackageDataObserver observer) {
14259        mContext.enforceCallingOrSelfPermission(
14260                android.Manifest.permission.DELETE_CACHE_FILES, null);
14261        // Queue up an async operation since the package deletion may take a little while.
14262        final int userId = UserHandle.getCallingUserId();
14263        mHandler.post(new Runnable() {
14264            public void run() {
14265                mHandler.removeCallbacks(this);
14266                final boolean succeded;
14267                synchronized (mInstallLock) {
14268                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14269                }
14270                clearExternalStorageDataSync(packageName, userId, false);
14271                if (observer != null) {
14272                    try {
14273                        observer.onRemoveCompleted(packageName, succeded);
14274                    } catch (RemoteException e) {
14275                        Log.i(TAG, "Observer no longer exists.");
14276                    }
14277                } //end if observer
14278            } //end run
14279        });
14280    }
14281
14282    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14283        if (packageName == null) {
14284            Slog.w(TAG, "Attempt to delete null packageName.");
14285            return false;
14286        }
14287        PackageParser.Package p;
14288        synchronized (mPackages) {
14289            p = mPackages.get(packageName);
14290        }
14291        if (p == null) {
14292            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14293            return false;
14294        }
14295        final ApplicationInfo applicationInfo = p.applicationInfo;
14296        if (applicationInfo == null) {
14297            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14298            return false;
14299        }
14300        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14301        if (retCode < 0) {
14302            Slog.w(TAG, "Couldn't remove cache files for package: "
14303                       + packageName + " u" + userId);
14304            return false;
14305        }
14306        return true;
14307    }
14308
14309    @Override
14310    public void getPackageSizeInfo(final String packageName, int userHandle,
14311            final IPackageStatsObserver observer) {
14312        mContext.enforceCallingOrSelfPermission(
14313                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14314        if (packageName == null) {
14315            throw new IllegalArgumentException("Attempt to get size of null packageName");
14316        }
14317
14318        PackageStats stats = new PackageStats(packageName, userHandle);
14319
14320        /*
14321         * Queue up an async operation since the package measurement may take a
14322         * little while.
14323         */
14324        Message msg = mHandler.obtainMessage(INIT_COPY);
14325        msg.obj = new MeasureParams(stats, observer);
14326        mHandler.sendMessage(msg);
14327    }
14328
14329    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14330            PackageStats pStats) {
14331        if (packageName == null) {
14332            Slog.w(TAG, "Attempt to get size of null packageName.");
14333            return false;
14334        }
14335        PackageParser.Package p;
14336        boolean dataOnly = false;
14337        String libDirRoot = null;
14338        String asecPath = null;
14339        PackageSetting ps = null;
14340        synchronized (mPackages) {
14341            p = mPackages.get(packageName);
14342            ps = mSettings.mPackages.get(packageName);
14343            if(p == null) {
14344                dataOnly = true;
14345                if((ps == null) || (ps.pkg == null)) {
14346                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14347                    return false;
14348                }
14349                p = ps.pkg;
14350            }
14351            if (ps != null) {
14352                libDirRoot = ps.legacyNativeLibraryPathString;
14353            }
14354            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14355                final long token = Binder.clearCallingIdentity();
14356                try {
14357                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14358                    if (secureContainerId != null) {
14359                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14360                    }
14361                } finally {
14362                    Binder.restoreCallingIdentity(token);
14363                }
14364            }
14365        }
14366        String publicSrcDir = null;
14367        if(!dataOnly) {
14368            final ApplicationInfo applicationInfo = p.applicationInfo;
14369            if (applicationInfo == null) {
14370                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14371                return false;
14372            }
14373            if (p.isForwardLocked()) {
14374                publicSrcDir = applicationInfo.getBaseResourcePath();
14375            }
14376        }
14377        // TODO: extend to measure size of split APKs
14378        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14379        // not just the first level.
14380        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14381        // just the primary.
14382        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14383
14384        String apkPath;
14385        File packageDir = new File(p.codePath);
14386
14387        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14388            apkPath = packageDir.getAbsolutePath();
14389            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14390            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14391                libDirRoot = null;
14392            }
14393        } else {
14394            apkPath = p.baseCodePath;
14395        }
14396
14397        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14398                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14399        if (res < 0) {
14400            return false;
14401        }
14402
14403        // Fix-up for forward-locked applications in ASEC containers.
14404        if (!isExternal(p)) {
14405            pStats.codeSize += pStats.externalCodeSize;
14406            pStats.externalCodeSize = 0L;
14407        }
14408
14409        return true;
14410    }
14411
14412
14413    @Override
14414    public void addPackageToPreferred(String packageName) {
14415        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14416    }
14417
14418    @Override
14419    public void removePackageFromPreferred(String packageName) {
14420        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14421    }
14422
14423    @Override
14424    public List<PackageInfo> getPreferredPackages(int flags) {
14425        return new ArrayList<PackageInfo>();
14426    }
14427
14428    private int getUidTargetSdkVersionLockedLPr(int uid) {
14429        Object obj = mSettings.getUserIdLPr(uid);
14430        if (obj instanceof SharedUserSetting) {
14431            final SharedUserSetting sus = (SharedUserSetting) obj;
14432            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14433            final Iterator<PackageSetting> it = sus.packages.iterator();
14434            while (it.hasNext()) {
14435                final PackageSetting ps = it.next();
14436                if (ps.pkg != null) {
14437                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14438                    if (v < vers) vers = v;
14439                }
14440            }
14441            return vers;
14442        } else if (obj instanceof PackageSetting) {
14443            final PackageSetting ps = (PackageSetting) obj;
14444            if (ps.pkg != null) {
14445                return ps.pkg.applicationInfo.targetSdkVersion;
14446            }
14447        }
14448        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14449    }
14450
14451    @Override
14452    public void addPreferredActivity(IntentFilter filter, int match,
14453            ComponentName[] set, ComponentName activity, int userId) {
14454        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14455                "Adding preferred");
14456    }
14457
14458    private void addPreferredActivityInternal(IntentFilter filter, int match,
14459            ComponentName[] set, ComponentName activity, boolean always, int userId,
14460            String opname) {
14461        // writer
14462        int callingUid = Binder.getCallingUid();
14463        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14464        if (filter.countActions() == 0) {
14465            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14466            return;
14467        }
14468        synchronized (mPackages) {
14469            if (mContext.checkCallingOrSelfPermission(
14470                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14471                    != PackageManager.PERMISSION_GRANTED) {
14472                if (getUidTargetSdkVersionLockedLPr(callingUid)
14473                        < Build.VERSION_CODES.FROYO) {
14474                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14475                            + callingUid);
14476                    return;
14477                }
14478                mContext.enforceCallingOrSelfPermission(
14479                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14480            }
14481
14482            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14483            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14484                    + userId + ":");
14485            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14486            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14487            scheduleWritePackageRestrictionsLocked(userId);
14488        }
14489    }
14490
14491    @Override
14492    public void replacePreferredActivity(IntentFilter filter, int match,
14493            ComponentName[] set, ComponentName activity, int userId) {
14494        if (filter.countActions() != 1) {
14495            throw new IllegalArgumentException(
14496                    "replacePreferredActivity expects filter to have only 1 action.");
14497        }
14498        if (filter.countDataAuthorities() != 0
14499                || filter.countDataPaths() != 0
14500                || filter.countDataSchemes() > 1
14501                || filter.countDataTypes() != 0) {
14502            throw new IllegalArgumentException(
14503                    "replacePreferredActivity expects filter to have no data authorities, " +
14504                    "paths, or types; and at most one scheme.");
14505        }
14506
14507        final int callingUid = Binder.getCallingUid();
14508        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14509        synchronized (mPackages) {
14510            if (mContext.checkCallingOrSelfPermission(
14511                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14512                    != PackageManager.PERMISSION_GRANTED) {
14513                if (getUidTargetSdkVersionLockedLPr(callingUid)
14514                        < Build.VERSION_CODES.FROYO) {
14515                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14516                            + Binder.getCallingUid());
14517                    return;
14518                }
14519                mContext.enforceCallingOrSelfPermission(
14520                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14521            }
14522
14523            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14524            if (pir != null) {
14525                // Get all of the existing entries that exactly match this filter.
14526                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14527                if (existing != null && existing.size() == 1) {
14528                    PreferredActivity cur = existing.get(0);
14529                    if (DEBUG_PREFERRED) {
14530                        Slog.i(TAG, "Checking replace of preferred:");
14531                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14532                        if (!cur.mPref.mAlways) {
14533                            Slog.i(TAG, "  -- CUR; not mAlways!");
14534                        } else {
14535                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14536                            Slog.i(TAG, "  -- CUR: mSet="
14537                                    + Arrays.toString(cur.mPref.mSetComponents));
14538                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14539                            Slog.i(TAG, "  -- NEW: mMatch="
14540                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14541                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14542                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14543                        }
14544                    }
14545                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14546                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14547                            && cur.mPref.sameSet(set)) {
14548                        // Setting the preferred activity to what it happens to be already
14549                        if (DEBUG_PREFERRED) {
14550                            Slog.i(TAG, "Replacing with same preferred activity "
14551                                    + cur.mPref.mShortComponent + " for user "
14552                                    + userId + ":");
14553                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14554                        }
14555                        return;
14556                    }
14557                }
14558
14559                if (existing != null) {
14560                    if (DEBUG_PREFERRED) {
14561                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14562                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14563                    }
14564                    for (int i = 0; i < existing.size(); i++) {
14565                        PreferredActivity pa = existing.get(i);
14566                        if (DEBUG_PREFERRED) {
14567                            Slog.i(TAG, "Removing existing preferred activity "
14568                                    + pa.mPref.mComponent + ":");
14569                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14570                        }
14571                        pir.removeFilter(pa);
14572                    }
14573                }
14574            }
14575            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14576                    "Replacing preferred");
14577        }
14578    }
14579
14580    @Override
14581    public void clearPackagePreferredActivities(String packageName) {
14582        final int uid = Binder.getCallingUid();
14583        // writer
14584        synchronized (mPackages) {
14585            PackageParser.Package pkg = mPackages.get(packageName);
14586            if (pkg == null || pkg.applicationInfo.uid != uid) {
14587                if (mContext.checkCallingOrSelfPermission(
14588                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14589                        != PackageManager.PERMISSION_GRANTED) {
14590                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14591                            < Build.VERSION_CODES.FROYO) {
14592                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14593                                + Binder.getCallingUid());
14594                        return;
14595                    }
14596                    mContext.enforceCallingOrSelfPermission(
14597                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14598                }
14599            }
14600
14601            int user = UserHandle.getCallingUserId();
14602            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14603                scheduleWritePackageRestrictionsLocked(user);
14604            }
14605        }
14606    }
14607
14608    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14609    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14610        ArrayList<PreferredActivity> removed = null;
14611        boolean changed = false;
14612        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14613            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14614            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14615            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14616                continue;
14617            }
14618            Iterator<PreferredActivity> it = pir.filterIterator();
14619            while (it.hasNext()) {
14620                PreferredActivity pa = it.next();
14621                // Mark entry for removal only if it matches the package name
14622                // and the entry is of type "always".
14623                if (packageName == null ||
14624                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14625                                && pa.mPref.mAlways)) {
14626                    if (removed == null) {
14627                        removed = new ArrayList<PreferredActivity>();
14628                    }
14629                    removed.add(pa);
14630                }
14631            }
14632            if (removed != null) {
14633                for (int j=0; j<removed.size(); j++) {
14634                    PreferredActivity pa = removed.get(j);
14635                    pir.removeFilter(pa);
14636                }
14637                changed = true;
14638            }
14639        }
14640        return changed;
14641    }
14642
14643    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14644    private void clearIntentFilterVerificationsLPw(int userId) {
14645        final int packageCount = mPackages.size();
14646        for (int i = 0; i < packageCount; i++) {
14647            PackageParser.Package pkg = mPackages.valueAt(i);
14648            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14649        }
14650    }
14651
14652    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14653    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14654        if (userId == UserHandle.USER_ALL) {
14655            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14656                    sUserManager.getUserIds())) {
14657                for (int oneUserId : sUserManager.getUserIds()) {
14658                    scheduleWritePackageRestrictionsLocked(oneUserId);
14659                }
14660            }
14661        } else {
14662            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14663                scheduleWritePackageRestrictionsLocked(userId);
14664            }
14665        }
14666    }
14667
14668    void clearDefaultBrowserIfNeeded(String packageName) {
14669        for (int oneUserId : sUserManager.getUserIds()) {
14670            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14671            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14672            if (packageName.equals(defaultBrowserPackageName)) {
14673                setDefaultBrowserPackageName(null, oneUserId);
14674            }
14675        }
14676    }
14677
14678    @Override
14679    public void resetApplicationPreferences(int userId) {
14680        mContext.enforceCallingOrSelfPermission(
14681                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14682        // writer
14683        synchronized (mPackages) {
14684            final long identity = Binder.clearCallingIdentity();
14685            try {
14686                clearPackagePreferredActivitiesLPw(null, userId);
14687                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14688                // TODO: We have to reset the default SMS and Phone. This requires
14689                // significant refactoring to keep all default apps in the package
14690                // manager (cleaner but more work) or have the services provide
14691                // callbacks to the package manager to request a default app reset.
14692                applyFactoryDefaultBrowserLPw(userId);
14693                clearIntentFilterVerificationsLPw(userId);
14694                primeDomainVerificationsLPw(userId);
14695                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14696                scheduleWritePackageRestrictionsLocked(userId);
14697            } finally {
14698                Binder.restoreCallingIdentity(identity);
14699            }
14700        }
14701    }
14702
14703    @Override
14704    public int getPreferredActivities(List<IntentFilter> outFilters,
14705            List<ComponentName> outActivities, String packageName) {
14706
14707        int num = 0;
14708        final int userId = UserHandle.getCallingUserId();
14709        // reader
14710        synchronized (mPackages) {
14711            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14712            if (pir != null) {
14713                final Iterator<PreferredActivity> it = pir.filterIterator();
14714                while (it.hasNext()) {
14715                    final PreferredActivity pa = it.next();
14716                    if (packageName == null
14717                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14718                                    && pa.mPref.mAlways)) {
14719                        if (outFilters != null) {
14720                            outFilters.add(new IntentFilter(pa));
14721                        }
14722                        if (outActivities != null) {
14723                            outActivities.add(pa.mPref.mComponent);
14724                        }
14725                    }
14726                }
14727            }
14728        }
14729
14730        return num;
14731    }
14732
14733    @Override
14734    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14735            int userId) {
14736        int callingUid = Binder.getCallingUid();
14737        if (callingUid != Process.SYSTEM_UID) {
14738            throw new SecurityException(
14739                    "addPersistentPreferredActivity can only be run by the system");
14740        }
14741        if (filter.countActions() == 0) {
14742            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14743            return;
14744        }
14745        synchronized (mPackages) {
14746            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14747                    " :");
14748            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14749            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14750                    new PersistentPreferredActivity(filter, activity));
14751            scheduleWritePackageRestrictionsLocked(userId);
14752        }
14753    }
14754
14755    @Override
14756    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14757        int callingUid = Binder.getCallingUid();
14758        if (callingUid != Process.SYSTEM_UID) {
14759            throw new SecurityException(
14760                    "clearPackagePersistentPreferredActivities can only be run by the system");
14761        }
14762        ArrayList<PersistentPreferredActivity> removed = null;
14763        boolean changed = false;
14764        synchronized (mPackages) {
14765            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14766                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14767                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14768                        .valueAt(i);
14769                if (userId != thisUserId) {
14770                    continue;
14771                }
14772                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14773                while (it.hasNext()) {
14774                    PersistentPreferredActivity ppa = it.next();
14775                    // Mark entry for removal only if it matches the package name.
14776                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14777                        if (removed == null) {
14778                            removed = new ArrayList<PersistentPreferredActivity>();
14779                        }
14780                        removed.add(ppa);
14781                    }
14782                }
14783                if (removed != null) {
14784                    for (int j=0; j<removed.size(); j++) {
14785                        PersistentPreferredActivity ppa = removed.get(j);
14786                        ppir.removeFilter(ppa);
14787                    }
14788                    changed = true;
14789                }
14790            }
14791
14792            if (changed) {
14793                scheduleWritePackageRestrictionsLocked(userId);
14794            }
14795        }
14796    }
14797
14798    /**
14799     * Common machinery for picking apart a restored XML blob and passing
14800     * it to a caller-supplied functor to be applied to the running system.
14801     */
14802    private void restoreFromXml(XmlPullParser parser, int userId,
14803            String expectedStartTag, BlobXmlRestorer functor)
14804            throws IOException, XmlPullParserException {
14805        int type;
14806        while ((type = parser.next()) != XmlPullParser.START_TAG
14807                && type != XmlPullParser.END_DOCUMENT) {
14808        }
14809        if (type != XmlPullParser.START_TAG) {
14810            // oops didn't find a start tag?!
14811            if (DEBUG_BACKUP) {
14812                Slog.e(TAG, "Didn't find start tag during restore");
14813            }
14814            return;
14815        }
14816
14817        // this is supposed to be TAG_PREFERRED_BACKUP
14818        if (!expectedStartTag.equals(parser.getName())) {
14819            if (DEBUG_BACKUP) {
14820                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14821            }
14822            return;
14823        }
14824
14825        // skip interfering stuff, then we're aligned with the backing implementation
14826        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14827        functor.apply(parser, userId);
14828    }
14829
14830    private interface BlobXmlRestorer {
14831        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14832    }
14833
14834    /**
14835     * Non-Binder method, support for the backup/restore mechanism: write the
14836     * full set of preferred activities in its canonical XML format.  Returns the
14837     * XML output as a byte array, or null if there is none.
14838     */
14839    @Override
14840    public byte[] getPreferredActivityBackup(int userId) {
14841        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14842            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14843        }
14844
14845        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14846        try {
14847            final XmlSerializer serializer = new FastXmlSerializer();
14848            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14849            serializer.startDocument(null, true);
14850            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14851
14852            synchronized (mPackages) {
14853                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14854            }
14855
14856            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14857            serializer.endDocument();
14858            serializer.flush();
14859        } catch (Exception e) {
14860            if (DEBUG_BACKUP) {
14861                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14862            }
14863            return null;
14864        }
14865
14866        return dataStream.toByteArray();
14867    }
14868
14869    @Override
14870    public void restorePreferredActivities(byte[] backup, int userId) {
14871        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14872            throw new SecurityException("Only the system may call restorePreferredActivities()");
14873        }
14874
14875        try {
14876            final XmlPullParser parser = Xml.newPullParser();
14877            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14878            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14879                    new BlobXmlRestorer() {
14880                        @Override
14881                        public void apply(XmlPullParser parser, int userId)
14882                                throws XmlPullParserException, IOException {
14883                            synchronized (mPackages) {
14884                                mSettings.readPreferredActivitiesLPw(parser, userId);
14885                            }
14886                        }
14887                    } );
14888        } catch (Exception e) {
14889            if (DEBUG_BACKUP) {
14890                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14891            }
14892        }
14893    }
14894
14895    /**
14896     * Non-Binder method, support for the backup/restore mechanism: write the
14897     * default browser (etc) settings in its canonical XML format.  Returns the default
14898     * browser XML representation as a byte array, or null if there is none.
14899     */
14900    @Override
14901    public byte[] getDefaultAppsBackup(int userId) {
14902        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14903            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14904        }
14905
14906        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14907        try {
14908            final XmlSerializer serializer = new FastXmlSerializer();
14909            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14910            serializer.startDocument(null, true);
14911            serializer.startTag(null, TAG_DEFAULT_APPS);
14912
14913            synchronized (mPackages) {
14914                mSettings.writeDefaultAppsLPr(serializer, userId);
14915            }
14916
14917            serializer.endTag(null, TAG_DEFAULT_APPS);
14918            serializer.endDocument();
14919            serializer.flush();
14920        } catch (Exception e) {
14921            if (DEBUG_BACKUP) {
14922                Slog.e(TAG, "Unable to write default apps for backup", e);
14923            }
14924            return null;
14925        }
14926
14927        return dataStream.toByteArray();
14928    }
14929
14930    @Override
14931    public void restoreDefaultApps(byte[] backup, int userId) {
14932        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14933            throw new SecurityException("Only the system may call restoreDefaultApps()");
14934        }
14935
14936        try {
14937            final XmlPullParser parser = Xml.newPullParser();
14938            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14939            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14940                    new BlobXmlRestorer() {
14941                        @Override
14942                        public void apply(XmlPullParser parser, int userId)
14943                                throws XmlPullParserException, IOException {
14944                            synchronized (mPackages) {
14945                                mSettings.readDefaultAppsLPw(parser, userId);
14946                            }
14947                        }
14948                    } );
14949        } catch (Exception e) {
14950            if (DEBUG_BACKUP) {
14951                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14952            }
14953        }
14954    }
14955
14956    @Override
14957    public byte[] getIntentFilterVerificationBackup(int userId) {
14958        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14959            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14960        }
14961
14962        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14963        try {
14964            final XmlSerializer serializer = new FastXmlSerializer();
14965            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14966            serializer.startDocument(null, true);
14967            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14968
14969            synchronized (mPackages) {
14970                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14971            }
14972
14973            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14974            serializer.endDocument();
14975            serializer.flush();
14976        } catch (Exception e) {
14977            if (DEBUG_BACKUP) {
14978                Slog.e(TAG, "Unable to write default apps for backup", e);
14979            }
14980            return null;
14981        }
14982
14983        return dataStream.toByteArray();
14984    }
14985
14986    @Override
14987    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14988        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14989            throw new SecurityException("Only the system may call restorePreferredActivities()");
14990        }
14991
14992        try {
14993            final XmlPullParser parser = Xml.newPullParser();
14994            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14995            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14996                    new BlobXmlRestorer() {
14997                        @Override
14998                        public void apply(XmlPullParser parser, int userId)
14999                                throws XmlPullParserException, IOException {
15000                            synchronized (mPackages) {
15001                                mSettings.readAllDomainVerificationsLPr(parser, userId);
15002                                mSettings.writeLPr();
15003                            }
15004                        }
15005                    } );
15006        } catch (Exception e) {
15007            if (DEBUG_BACKUP) {
15008                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
15009            }
15010        }
15011    }
15012
15013    @Override
15014    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
15015            int sourceUserId, int targetUserId, int flags) {
15016        mContext.enforceCallingOrSelfPermission(
15017                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15018        int callingUid = Binder.getCallingUid();
15019        enforceOwnerRights(ownerPackage, callingUid);
15020        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15021        if (intentFilter.countActions() == 0) {
15022            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
15023            return;
15024        }
15025        synchronized (mPackages) {
15026            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
15027                    ownerPackage, targetUserId, flags);
15028            CrossProfileIntentResolver resolver =
15029                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15030            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
15031            // We have all those whose filter is equal. Now checking if the rest is equal as well.
15032            if (existing != null) {
15033                int size = existing.size();
15034                for (int i = 0; i < size; i++) {
15035                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
15036                        return;
15037                    }
15038                }
15039            }
15040            resolver.addFilter(newFilter);
15041            scheduleWritePackageRestrictionsLocked(sourceUserId);
15042        }
15043    }
15044
15045    @Override
15046    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15047        mContext.enforceCallingOrSelfPermission(
15048                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15049        int callingUid = Binder.getCallingUid();
15050        enforceOwnerRights(ownerPackage, callingUid);
15051        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15052        synchronized (mPackages) {
15053            CrossProfileIntentResolver resolver =
15054                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15055            ArraySet<CrossProfileIntentFilter> set =
15056                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15057            for (CrossProfileIntentFilter filter : set) {
15058                if (filter.getOwnerPackage().equals(ownerPackage)) {
15059                    resolver.removeFilter(filter);
15060                }
15061            }
15062            scheduleWritePackageRestrictionsLocked(sourceUserId);
15063        }
15064    }
15065
15066    // Enforcing that callingUid is owning pkg on userId
15067    private void enforceOwnerRights(String pkg, int callingUid) {
15068        // The system owns everything.
15069        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15070            return;
15071        }
15072        int callingUserId = UserHandle.getUserId(callingUid);
15073        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15074        if (pi == null) {
15075            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15076                    + callingUserId);
15077        }
15078        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15079            throw new SecurityException("Calling uid " + callingUid
15080                    + " does not own package " + pkg);
15081        }
15082    }
15083
15084    @Override
15085    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15086        Intent intent = new Intent(Intent.ACTION_MAIN);
15087        intent.addCategory(Intent.CATEGORY_HOME);
15088
15089        final int callingUserId = UserHandle.getCallingUserId();
15090        List<ResolveInfo> list = queryIntentActivities(intent, null,
15091                PackageManager.GET_META_DATA, callingUserId);
15092        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15093                true, false, false, callingUserId);
15094
15095        allHomeCandidates.clear();
15096        if (list != null) {
15097            for (ResolveInfo ri : list) {
15098                allHomeCandidates.add(ri);
15099            }
15100        }
15101        return (preferred == null || preferred.activityInfo == null)
15102                ? null
15103                : new ComponentName(preferred.activityInfo.packageName,
15104                        preferred.activityInfo.name);
15105    }
15106
15107    @Override
15108    public void setApplicationEnabledSetting(String appPackageName,
15109            int newState, int flags, int userId, String callingPackage) {
15110        if (!sUserManager.exists(userId)) return;
15111        if (callingPackage == null) {
15112            callingPackage = Integer.toString(Binder.getCallingUid());
15113        }
15114        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15115    }
15116
15117    @Override
15118    public void setComponentEnabledSetting(ComponentName componentName,
15119            int newState, int flags, int userId) {
15120        if (!sUserManager.exists(userId)) return;
15121        setEnabledSetting(componentName.getPackageName(),
15122                componentName.getClassName(), newState, flags, userId, null);
15123    }
15124
15125    private void setEnabledSetting(final String packageName, String className, int newState,
15126            final int flags, int userId, String callingPackage) {
15127        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15128              || newState == COMPONENT_ENABLED_STATE_ENABLED
15129              || newState == COMPONENT_ENABLED_STATE_DISABLED
15130              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15131              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15132            throw new IllegalArgumentException("Invalid new component state: "
15133                    + newState);
15134        }
15135        PackageSetting pkgSetting;
15136        final int uid = Binder.getCallingUid();
15137        final int permission = mContext.checkCallingOrSelfPermission(
15138                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15139        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15140        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15141        boolean sendNow = false;
15142        boolean isApp = (className == null);
15143        String componentName = isApp ? packageName : className;
15144        int packageUid = -1;
15145        ArrayList<String> components;
15146
15147        // writer
15148        synchronized (mPackages) {
15149            pkgSetting = mSettings.mPackages.get(packageName);
15150            if (pkgSetting == null) {
15151                if (className == null) {
15152                    throw new IllegalArgumentException(
15153                            "Unknown package: " + packageName);
15154                }
15155                throw new IllegalArgumentException(
15156                        "Unknown component: " + packageName
15157                        + "/" + className);
15158            }
15159            // Allow root and verify that userId is not being specified by a different user
15160            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15161                throw new SecurityException(
15162                        "Permission Denial: attempt to change component state from pid="
15163                        + Binder.getCallingPid()
15164                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15165            }
15166            if (className == null) {
15167                // We're dealing with an application/package level state change
15168                if (pkgSetting.getEnabled(userId) == newState) {
15169                    // Nothing to do
15170                    return;
15171                }
15172                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15173                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15174                    // Don't care about who enables an app.
15175                    callingPackage = null;
15176                }
15177                pkgSetting.setEnabled(newState, userId, callingPackage);
15178                // pkgSetting.pkg.mSetEnabled = newState;
15179            } else {
15180                // We're dealing with a component level state change
15181                // First, verify that this is a valid class name.
15182                PackageParser.Package pkg = pkgSetting.pkg;
15183                if (pkg == null || !pkg.hasComponentClassName(className)) {
15184                    if (pkg != null &&
15185                            pkg.applicationInfo.targetSdkVersion >=
15186                                    Build.VERSION_CODES.JELLY_BEAN) {
15187                        throw new IllegalArgumentException("Component class " + className
15188                                + " does not exist in " + packageName);
15189                    } else {
15190                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15191                                + className + " does not exist in " + packageName);
15192                    }
15193                }
15194                switch (newState) {
15195                case COMPONENT_ENABLED_STATE_ENABLED:
15196                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15197                        return;
15198                    }
15199                    break;
15200                case COMPONENT_ENABLED_STATE_DISABLED:
15201                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15202                        return;
15203                    }
15204                    break;
15205                case COMPONENT_ENABLED_STATE_DEFAULT:
15206                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15207                        return;
15208                    }
15209                    break;
15210                default:
15211                    Slog.e(TAG, "Invalid new component state: " + newState);
15212                    return;
15213                }
15214            }
15215            scheduleWritePackageRestrictionsLocked(userId);
15216            components = mPendingBroadcasts.get(userId, packageName);
15217            final boolean newPackage = components == null;
15218            if (newPackage) {
15219                components = new ArrayList<String>();
15220            }
15221            if (!components.contains(componentName)) {
15222                components.add(componentName);
15223            }
15224            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15225                sendNow = true;
15226                // Purge entry from pending broadcast list if another one exists already
15227                // since we are sending one right away.
15228                mPendingBroadcasts.remove(userId, packageName);
15229            } else {
15230                if (newPackage) {
15231                    mPendingBroadcasts.put(userId, packageName, components);
15232                }
15233                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15234                    // Schedule a message
15235                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15236                }
15237            }
15238        }
15239
15240        long callingId = Binder.clearCallingIdentity();
15241        try {
15242            if (sendNow) {
15243                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15244                sendPackageChangedBroadcast(packageName,
15245                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15246            }
15247        } finally {
15248            Binder.restoreCallingIdentity(callingId);
15249        }
15250    }
15251
15252    private void sendPackageChangedBroadcast(String packageName,
15253            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15254        if (DEBUG_INSTALL)
15255            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15256                    + componentNames);
15257        Bundle extras = new Bundle(4);
15258        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15259        String nameList[] = new String[componentNames.size()];
15260        componentNames.toArray(nameList);
15261        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15262        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15263        extras.putInt(Intent.EXTRA_UID, packageUid);
15264        // If this is not reporting a change of the overall package, then only send it
15265        // to registered receivers.  We don't want to launch a swath of apps for every
15266        // little component state change.
15267        final int flags = !componentNames.contains(packageName)
15268                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15269        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15270                new int[] {UserHandle.getUserId(packageUid)});
15271    }
15272
15273    @Override
15274    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15275        if (!sUserManager.exists(userId)) return;
15276        final int uid = Binder.getCallingUid();
15277        final int permission = mContext.checkCallingOrSelfPermission(
15278                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15279        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15280        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15281        // writer
15282        synchronized (mPackages) {
15283            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15284                    allowedByPermission, uid, userId)) {
15285                scheduleWritePackageRestrictionsLocked(userId);
15286            }
15287        }
15288    }
15289
15290    @Override
15291    public String getInstallerPackageName(String packageName) {
15292        // reader
15293        synchronized (mPackages) {
15294            return mSettings.getInstallerPackageNameLPr(packageName);
15295        }
15296    }
15297
15298    @Override
15299    public int getApplicationEnabledSetting(String packageName, int userId) {
15300        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15301        int uid = Binder.getCallingUid();
15302        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15303        // reader
15304        synchronized (mPackages) {
15305            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15306        }
15307    }
15308
15309    @Override
15310    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15311        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15312        int uid = Binder.getCallingUid();
15313        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15314        // reader
15315        synchronized (mPackages) {
15316            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15317        }
15318    }
15319
15320    @Override
15321    public void enterSafeMode() {
15322        enforceSystemOrRoot("Only the system can request entering safe mode");
15323
15324        if (!mSystemReady) {
15325            mSafeMode = true;
15326        }
15327    }
15328
15329    @Override
15330    public void systemReady() {
15331        mSystemReady = true;
15332
15333        // Read the compatibilty setting when the system is ready.
15334        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15335                mContext.getContentResolver(),
15336                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15337        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15338        if (DEBUG_SETTINGS) {
15339            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15340        }
15341
15342        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15343
15344        synchronized (mPackages) {
15345            // Verify that all of the preferred activity components actually
15346            // exist.  It is possible for applications to be updated and at
15347            // that point remove a previously declared activity component that
15348            // had been set as a preferred activity.  We try to clean this up
15349            // the next time we encounter that preferred activity, but it is
15350            // possible for the user flow to never be able to return to that
15351            // situation so here we do a sanity check to make sure we haven't
15352            // left any junk around.
15353            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15354            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15355                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15356                removed.clear();
15357                for (PreferredActivity pa : pir.filterSet()) {
15358                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15359                        removed.add(pa);
15360                    }
15361                }
15362                if (removed.size() > 0) {
15363                    for (int r=0; r<removed.size(); r++) {
15364                        PreferredActivity pa = removed.get(r);
15365                        Slog.w(TAG, "Removing dangling preferred activity: "
15366                                + pa.mPref.mComponent);
15367                        pir.removeFilter(pa);
15368                    }
15369                    mSettings.writePackageRestrictionsLPr(
15370                            mSettings.mPreferredActivities.keyAt(i));
15371                }
15372            }
15373
15374            for (int userId : UserManagerService.getInstance().getUserIds()) {
15375                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15376                    grantPermissionsUserIds = ArrayUtils.appendInt(
15377                            grantPermissionsUserIds, userId);
15378                }
15379            }
15380        }
15381        sUserManager.systemReady();
15382
15383        // If we upgraded grant all default permissions before kicking off.
15384        for (int userId : grantPermissionsUserIds) {
15385            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15386        }
15387
15388        // Kick off any messages waiting for system ready
15389        if (mPostSystemReadyMessages != null) {
15390            for (Message msg : mPostSystemReadyMessages) {
15391                msg.sendToTarget();
15392            }
15393            mPostSystemReadyMessages = null;
15394        }
15395
15396        // Watch for external volumes that come and go over time
15397        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15398        storage.registerListener(mStorageListener);
15399
15400        mInstallerService.systemReady();
15401        mPackageDexOptimizer.systemReady();
15402
15403        MountServiceInternal mountServiceInternal = LocalServices.getService(
15404                MountServiceInternal.class);
15405        mountServiceInternal.addExternalStoragePolicy(
15406                new MountServiceInternal.ExternalStorageMountPolicy() {
15407            @Override
15408            public int getMountMode(int uid, String packageName) {
15409                if (Process.isIsolated(uid)) {
15410                    return Zygote.MOUNT_EXTERNAL_NONE;
15411                }
15412                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15413                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15414                }
15415                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15416                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15417                }
15418                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15419                    return Zygote.MOUNT_EXTERNAL_READ;
15420                }
15421                return Zygote.MOUNT_EXTERNAL_WRITE;
15422            }
15423
15424            @Override
15425            public boolean hasExternalStorage(int uid, String packageName) {
15426                return true;
15427            }
15428        });
15429    }
15430
15431    @Override
15432    public boolean isSafeMode() {
15433        return mSafeMode;
15434    }
15435
15436    @Override
15437    public boolean hasSystemUidErrors() {
15438        return mHasSystemUidErrors;
15439    }
15440
15441    static String arrayToString(int[] array) {
15442        StringBuffer buf = new StringBuffer(128);
15443        buf.append('[');
15444        if (array != null) {
15445            for (int i=0; i<array.length; i++) {
15446                if (i > 0) buf.append(", ");
15447                buf.append(array[i]);
15448            }
15449        }
15450        buf.append(']');
15451        return buf.toString();
15452    }
15453
15454    static class DumpState {
15455        public static final int DUMP_LIBS = 1 << 0;
15456        public static final int DUMP_FEATURES = 1 << 1;
15457        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15458        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15459        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15460        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15461        public static final int DUMP_PERMISSIONS = 1 << 6;
15462        public static final int DUMP_PACKAGES = 1 << 7;
15463        public static final int DUMP_SHARED_USERS = 1 << 8;
15464        public static final int DUMP_MESSAGES = 1 << 9;
15465        public static final int DUMP_PROVIDERS = 1 << 10;
15466        public static final int DUMP_VERIFIERS = 1 << 11;
15467        public static final int DUMP_PREFERRED = 1 << 12;
15468        public static final int DUMP_PREFERRED_XML = 1 << 13;
15469        public static final int DUMP_KEYSETS = 1 << 14;
15470        public static final int DUMP_VERSION = 1 << 15;
15471        public static final int DUMP_INSTALLS = 1 << 16;
15472        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15473        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15474
15475        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15476
15477        private int mTypes;
15478
15479        private int mOptions;
15480
15481        private boolean mTitlePrinted;
15482
15483        private SharedUserSetting mSharedUser;
15484
15485        public boolean isDumping(int type) {
15486            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15487                return true;
15488            }
15489
15490            return (mTypes & type) != 0;
15491        }
15492
15493        public void setDump(int type) {
15494            mTypes |= type;
15495        }
15496
15497        public boolean isOptionEnabled(int option) {
15498            return (mOptions & option) != 0;
15499        }
15500
15501        public void setOptionEnabled(int option) {
15502            mOptions |= option;
15503        }
15504
15505        public boolean onTitlePrinted() {
15506            final boolean printed = mTitlePrinted;
15507            mTitlePrinted = true;
15508            return printed;
15509        }
15510
15511        public boolean getTitlePrinted() {
15512            return mTitlePrinted;
15513        }
15514
15515        public void setTitlePrinted(boolean enabled) {
15516            mTitlePrinted = enabled;
15517        }
15518
15519        public SharedUserSetting getSharedUser() {
15520            return mSharedUser;
15521        }
15522
15523        public void setSharedUser(SharedUserSetting user) {
15524            mSharedUser = user;
15525        }
15526    }
15527
15528    @Override
15529    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15530            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15531        (new PackageManagerShellCommand(this)).exec(
15532                this, in, out, err, args, resultReceiver);
15533    }
15534
15535    @Override
15536    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15537        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15538                != PackageManager.PERMISSION_GRANTED) {
15539            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15540                    + Binder.getCallingPid()
15541                    + ", uid=" + Binder.getCallingUid()
15542                    + " without permission "
15543                    + android.Manifest.permission.DUMP);
15544            return;
15545        }
15546
15547        DumpState dumpState = new DumpState();
15548        boolean fullPreferred = false;
15549        boolean checkin = false;
15550
15551        String packageName = null;
15552        ArraySet<String> permissionNames = null;
15553
15554        int opti = 0;
15555        while (opti < args.length) {
15556            String opt = args[opti];
15557            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15558                break;
15559            }
15560            opti++;
15561
15562            if ("-a".equals(opt)) {
15563                // Right now we only know how to print all.
15564            } else if ("-h".equals(opt)) {
15565                pw.println("Package manager dump options:");
15566                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15567                pw.println("    --checkin: dump for a checkin");
15568                pw.println("    -f: print details of intent filters");
15569                pw.println("    -h: print this help");
15570                pw.println("  cmd may be one of:");
15571                pw.println("    l[ibraries]: list known shared libraries");
15572                pw.println("    f[eatures]: list device features");
15573                pw.println("    k[eysets]: print known keysets");
15574                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15575                pw.println("    perm[issions]: dump permissions");
15576                pw.println("    permission [name ...]: dump declaration and use of given permission");
15577                pw.println("    pref[erred]: print preferred package settings");
15578                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15579                pw.println("    prov[iders]: dump content providers");
15580                pw.println("    p[ackages]: dump installed packages");
15581                pw.println("    s[hared-users]: dump shared user IDs");
15582                pw.println("    m[essages]: print collected runtime messages");
15583                pw.println("    v[erifiers]: print package verifier info");
15584                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15585                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15586                pw.println("    version: print database version info");
15587                pw.println("    write: write current settings now");
15588                pw.println("    installs: details about install sessions");
15589                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15590                pw.println("    <package.name>: info about given package");
15591                return;
15592            } else if ("--checkin".equals(opt)) {
15593                checkin = true;
15594            } else if ("-f".equals(opt)) {
15595                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15596            } else {
15597                pw.println("Unknown argument: " + opt + "; use -h for help");
15598            }
15599        }
15600
15601        // Is the caller requesting to dump a particular piece of data?
15602        if (opti < args.length) {
15603            String cmd = args[opti];
15604            opti++;
15605            // Is this a package name?
15606            if ("android".equals(cmd) || cmd.contains(".")) {
15607                packageName = cmd;
15608                // When dumping a single package, we always dump all of its
15609                // filter information since the amount of data will be reasonable.
15610                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15611            } else if ("check-permission".equals(cmd)) {
15612                if (opti >= args.length) {
15613                    pw.println("Error: check-permission missing permission argument");
15614                    return;
15615                }
15616                String perm = args[opti];
15617                opti++;
15618                if (opti >= args.length) {
15619                    pw.println("Error: check-permission missing package argument");
15620                    return;
15621                }
15622                String pkg = args[opti];
15623                opti++;
15624                int user = UserHandle.getUserId(Binder.getCallingUid());
15625                if (opti < args.length) {
15626                    try {
15627                        user = Integer.parseInt(args[opti]);
15628                    } catch (NumberFormatException e) {
15629                        pw.println("Error: check-permission user argument is not a number: "
15630                                + args[opti]);
15631                        return;
15632                    }
15633                }
15634                pw.println(checkPermission(perm, pkg, user));
15635                return;
15636            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15637                dumpState.setDump(DumpState.DUMP_LIBS);
15638            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15639                dumpState.setDump(DumpState.DUMP_FEATURES);
15640            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15641                if (opti >= args.length) {
15642                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15643                            | DumpState.DUMP_SERVICE_RESOLVERS
15644                            | DumpState.DUMP_RECEIVER_RESOLVERS
15645                            | DumpState.DUMP_CONTENT_RESOLVERS);
15646                } else {
15647                    while (opti < args.length) {
15648                        String name = args[opti];
15649                        if ("a".equals(name) || "activity".equals(name)) {
15650                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15651                        } else if ("s".equals(name) || "service".equals(name)) {
15652                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15653                        } else if ("r".equals(name) || "receiver".equals(name)) {
15654                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15655                        } else if ("c".equals(name) || "content".equals(name)) {
15656                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15657                        } else {
15658                            pw.println("Error: unknown resolver table type: " + name);
15659                            return;
15660                        }
15661                        opti++;
15662                    }
15663                }
15664            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15665                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15666            } else if ("permission".equals(cmd)) {
15667                if (opti >= args.length) {
15668                    pw.println("Error: permission requires permission name");
15669                    return;
15670                }
15671                permissionNames = new ArraySet<>();
15672                while (opti < args.length) {
15673                    permissionNames.add(args[opti]);
15674                    opti++;
15675                }
15676                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15677                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15678            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15679                dumpState.setDump(DumpState.DUMP_PREFERRED);
15680            } else if ("preferred-xml".equals(cmd)) {
15681                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15682                if (opti < args.length && "--full".equals(args[opti])) {
15683                    fullPreferred = true;
15684                    opti++;
15685                }
15686            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15687                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15688            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15689                dumpState.setDump(DumpState.DUMP_PACKAGES);
15690            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15691                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15692            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15693                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15694            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15695                dumpState.setDump(DumpState.DUMP_MESSAGES);
15696            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15697                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15698            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15699                    || "intent-filter-verifiers".equals(cmd)) {
15700                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15701            } else if ("version".equals(cmd)) {
15702                dumpState.setDump(DumpState.DUMP_VERSION);
15703            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15704                dumpState.setDump(DumpState.DUMP_KEYSETS);
15705            } else if ("installs".equals(cmd)) {
15706                dumpState.setDump(DumpState.DUMP_INSTALLS);
15707            } else if ("write".equals(cmd)) {
15708                synchronized (mPackages) {
15709                    mSettings.writeLPr();
15710                    pw.println("Settings written.");
15711                    return;
15712                }
15713            }
15714        }
15715
15716        if (checkin) {
15717            pw.println("vers,1");
15718        }
15719
15720        // reader
15721        synchronized (mPackages) {
15722            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15723                if (!checkin) {
15724                    if (dumpState.onTitlePrinted())
15725                        pw.println();
15726                    pw.println("Database versions:");
15727                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15728                }
15729            }
15730
15731            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15732                if (!checkin) {
15733                    if (dumpState.onTitlePrinted())
15734                        pw.println();
15735                    pw.println("Verifiers:");
15736                    pw.print("  Required: ");
15737                    pw.print(mRequiredVerifierPackage);
15738                    pw.print(" (uid=");
15739                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15740                    pw.println(")");
15741                } else if (mRequiredVerifierPackage != null) {
15742                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15743                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15744                }
15745            }
15746
15747            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15748                    packageName == null) {
15749                if (mIntentFilterVerifierComponent != null) {
15750                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15751                    if (!checkin) {
15752                        if (dumpState.onTitlePrinted())
15753                            pw.println();
15754                        pw.println("Intent Filter Verifier:");
15755                        pw.print("  Using: ");
15756                        pw.print(verifierPackageName);
15757                        pw.print(" (uid=");
15758                        pw.print(getPackageUid(verifierPackageName, 0));
15759                        pw.println(")");
15760                    } else if (verifierPackageName != null) {
15761                        pw.print("ifv,"); pw.print(verifierPackageName);
15762                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15763                    }
15764                } else {
15765                    pw.println();
15766                    pw.println("No Intent Filter Verifier available!");
15767                }
15768            }
15769
15770            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15771                boolean printedHeader = false;
15772                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15773                while (it.hasNext()) {
15774                    String name = it.next();
15775                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15776                    if (!checkin) {
15777                        if (!printedHeader) {
15778                            if (dumpState.onTitlePrinted())
15779                                pw.println();
15780                            pw.println("Libraries:");
15781                            printedHeader = true;
15782                        }
15783                        pw.print("  ");
15784                    } else {
15785                        pw.print("lib,");
15786                    }
15787                    pw.print(name);
15788                    if (!checkin) {
15789                        pw.print(" -> ");
15790                    }
15791                    if (ent.path != null) {
15792                        if (!checkin) {
15793                            pw.print("(jar) ");
15794                            pw.print(ent.path);
15795                        } else {
15796                            pw.print(",jar,");
15797                            pw.print(ent.path);
15798                        }
15799                    } else {
15800                        if (!checkin) {
15801                            pw.print("(apk) ");
15802                            pw.print(ent.apk);
15803                        } else {
15804                            pw.print(",apk,");
15805                            pw.print(ent.apk);
15806                        }
15807                    }
15808                    pw.println();
15809                }
15810            }
15811
15812            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15813                if (dumpState.onTitlePrinted())
15814                    pw.println();
15815                if (!checkin) {
15816                    pw.println("Features:");
15817                }
15818                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15819                while (it.hasNext()) {
15820                    String name = it.next();
15821                    if (!checkin) {
15822                        pw.print("  ");
15823                    } else {
15824                        pw.print("feat,");
15825                    }
15826                    pw.println(name);
15827                }
15828            }
15829
15830            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15831                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15832                        : "Activity Resolver Table:", "  ", packageName,
15833                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15834                    dumpState.setTitlePrinted(true);
15835                }
15836            }
15837            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15838                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15839                        : "Receiver Resolver Table:", "  ", packageName,
15840                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15841                    dumpState.setTitlePrinted(true);
15842                }
15843            }
15844            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15845                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15846                        : "Service Resolver Table:", "  ", packageName,
15847                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15848                    dumpState.setTitlePrinted(true);
15849                }
15850            }
15851            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15852                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15853                        : "Provider Resolver Table:", "  ", packageName,
15854                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15855                    dumpState.setTitlePrinted(true);
15856                }
15857            }
15858
15859            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15860                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15861                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15862                    int user = mSettings.mPreferredActivities.keyAt(i);
15863                    if (pir.dump(pw,
15864                            dumpState.getTitlePrinted()
15865                                ? "\nPreferred Activities User " + user + ":"
15866                                : "Preferred Activities User " + user + ":", "  ",
15867                            packageName, true, false)) {
15868                        dumpState.setTitlePrinted(true);
15869                    }
15870                }
15871            }
15872
15873            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15874                pw.flush();
15875                FileOutputStream fout = new FileOutputStream(fd);
15876                BufferedOutputStream str = new BufferedOutputStream(fout);
15877                XmlSerializer serializer = new FastXmlSerializer();
15878                try {
15879                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15880                    serializer.startDocument(null, true);
15881                    serializer.setFeature(
15882                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15883                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15884                    serializer.endDocument();
15885                    serializer.flush();
15886                } catch (IllegalArgumentException e) {
15887                    pw.println("Failed writing: " + e);
15888                } catch (IllegalStateException e) {
15889                    pw.println("Failed writing: " + e);
15890                } catch (IOException e) {
15891                    pw.println("Failed writing: " + e);
15892                }
15893            }
15894
15895            if (!checkin
15896                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15897                    && packageName == null) {
15898                pw.println();
15899                int count = mSettings.mPackages.size();
15900                if (count == 0) {
15901                    pw.println("No applications!");
15902                    pw.println();
15903                } else {
15904                    final String prefix = "  ";
15905                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15906                    if (allPackageSettings.size() == 0) {
15907                        pw.println("No domain preferred apps!");
15908                        pw.println();
15909                    } else {
15910                        pw.println("App verification status:");
15911                        pw.println();
15912                        count = 0;
15913                        for (PackageSetting ps : allPackageSettings) {
15914                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15915                            if (ivi == null || ivi.getPackageName() == null) continue;
15916                            pw.println(prefix + "Package: " + ivi.getPackageName());
15917                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15918                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15919                            pw.println();
15920                            count++;
15921                        }
15922                        if (count == 0) {
15923                            pw.println(prefix + "No app verification established.");
15924                            pw.println();
15925                        }
15926                        for (int userId : sUserManager.getUserIds()) {
15927                            pw.println("App linkages for user " + userId + ":");
15928                            pw.println();
15929                            count = 0;
15930                            for (PackageSetting ps : allPackageSettings) {
15931                                final long status = ps.getDomainVerificationStatusForUser(userId);
15932                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15933                                    continue;
15934                                }
15935                                pw.println(prefix + "Package: " + ps.name);
15936                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15937                                String statusStr = IntentFilterVerificationInfo.
15938                                        getStatusStringFromValue(status);
15939                                pw.println(prefix + "Status:  " + statusStr);
15940                                pw.println();
15941                                count++;
15942                            }
15943                            if (count == 0) {
15944                                pw.println(prefix + "No configured app linkages.");
15945                                pw.println();
15946                            }
15947                        }
15948                    }
15949                }
15950            }
15951
15952            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15953                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15954                if (packageName == null && permissionNames == null) {
15955                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15956                        if (iperm == 0) {
15957                            if (dumpState.onTitlePrinted())
15958                                pw.println();
15959                            pw.println("AppOp Permissions:");
15960                        }
15961                        pw.print("  AppOp Permission ");
15962                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15963                        pw.println(":");
15964                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15965                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15966                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15967                        }
15968                    }
15969                }
15970            }
15971
15972            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15973                boolean printedSomething = false;
15974                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15975                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15976                        continue;
15977                    }
15978                    if (!printedSomething) {
15979                        if (dumpState.onTitlePrinted())
15980                            pw.println();
15981                        pw.println("Registered ContentProviders:");
15982                        printedSomething = true;
15983                    }
15984                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15985                    pw.print("    "); pw.println(p.toString());
15986                }
15987                printedSomething = false;
15988                for (Map.Entry<String, PackageParser.Provider> entry :
15989                        mProvidersByAuthority.entrySet()) {
15990                    PackageParser.Provider p = entry.getValue();
15991                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15992                        continue;
15993                    }
15994                    if (!printedSomething) {
15995                        if (dumpState.onTitlePrinted())
15996                            pw.println();
15997                        pw.println("ContentProvider Authorities:");
15998                        printedSomething = true;
15999                    }
16000                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
16001                    pw.print("    "); pw.println(p.toString());
16002                    if (p.info != null && p.info.applicationInfo != null) {
16003                        final String appInfo = p.info.applicationInfo.toString();
16004                        pw.print("      applicationInfo="); pw.println(appInfo);
16005                    }
16006                }
16007            }
16008
16009            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
16010                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
16011            }
16012
16013            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
16014                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
16015            }
16016
16017            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
16018                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
16019            }
16020
16021            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
16022                // XXX should handle packageName != null by dumping only install data that
16023                // the given package is involved with.
16024                if (dumpState.onTitlePrinted()) pw.println();
16025                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
16026            }
16027
16028            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
16029                if (dumpState.onTitlePrinted()) pw.println();
16030                mSettings.dumpReadMessagesLPr(pw, dumpState);
16031
16032                pw.println();
16033                pw.println("Package warning messages:");
16034                BufferedReader in = null;
16035                String line = null;
16036                try {
16037                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16038                    while ((line = in.readLine()) != null) {
16039                        if (line.contains("ignored: updated version")) continue;
16040                        pw.println(line);
16041                    }
16042                } catch (IOException ignored) {
16043                } finally {
16044                    IoUtils.closeQuietly(in);
16045                }
16046            }
16047
16048            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16049                BufferedReader in = null;
16050                String line = null;
16051                try {
16052                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16053                    while ((line = in.readLine()) != null) {
16054                        if (line.contains("ignored: updated version")) continue;
16055                        pw.print("msg,");
16056                        pw.println(line);
16057                    }
16058                } catch (IOException ignored) {
16059                } finally {
16060                    IoUtils.closeQuietly(in);
16061                }
16062            }
16063        }
16064    }
16065
16066    private String dumpDomainString(String packageName) {
16067        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16068        List<IntentFilter> filters = getAllIntentFilters(packageName);
16069
16070        ArraySet<String> result = new ArraySet<>();
16071        if (iviList.size() > 0) {
16072            for (IntentFilterVerificationInfo ivi : iviList) {
16073                for (String host : ivi.getDomains()) {
16074                    result.add(host);
16075                }
16076            }
16077        }
16078        if (filters != null && filters.size() > 0) {
16079            for (IntentFilter filter : filters) {
16080                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16081                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16082                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16083                    result.addAll(filter.getHostsList());
16084                }
16085            }
16086        }
16087
16088        StringBuilder sb = new StringBuilder(result.size() * 16);
16089        for (String domain : result) {
16090            if (sb.length() > 0) sb.append(" ");
16091            sb.append(domain);
16092        }
16093        return sb.toString();
16094    }
16095
16096    // ------- apps on sdcard specific code -------
16097    static final boolean DEBUG_SD_INSTALL = false;
16098
16099    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16100
16101    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16102
16103    private boolean mMediaMounted = false;
16104
16105    static String getEncryptKey() {
16106        try {
16107            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16108                    SD_ENCRYPTION_KEYSTORE_NAME);
16109            if (sdEncKey == null) {
16110                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16111                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16112                if (sdEncKey == null) {
16113                    Slog.e(TAG, "Failed to create encryption keys");
16114                    return null;
16115                }
16116            }
16117            return sdEncKey;
16118        } catch (NoSuchAlgorithmException nsae) {
16119            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16120            return null;
16121        } catch (IOException ioe) {
16122            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16123            return null;
16124        }
16125    }
16126
16127    /*
16128     * Update media status on PackageManager.
16129     */
16130    @Override
16131    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16132        int callingUid = Binder.getCallingUid();
16133        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16134            throw new SecurityException("Media status can only be updated by the system");
16135        }
16136        // reader; this apparently protects mMediaMounted, but should probably
16137        // be a different lock in that case.
16138        synchronized (mPackages) {
16139            Log.i(TAG, "Updating external media status from "
16140                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16141                    + (mediaStatus ? "mounted" : "unmounted"));
16142            if (DEBUG_SD_INSTALL)
16143                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16144                        + ", mMediaMounted=" + mMediaMounted);
16145            if (mediaStatus == mMediaMounted) {
16146                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16147                        : 0, -1);
16148                mHandler.sendMessage(msg);
16149                return;
16150            }
16151            mMediaMounted = mediaStatus;
16152        }
16153        // Queue up an async operation since the package installation may take a
16154        // little while.
16155        mHandler.post(new Runnable() {
16156            public void run() {
16157                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16158            }
16159        });
16160    }
16161
16162    /**
16163     * Called by MountService when the initial ASECs to scan are available.
16164     * Should block until all the ASEC containers are finished being scanned.
16165     */
16166    public void scanAvailableAsecs() {
16167        updateExternalMediaStatusInner(true, false, false);
16168        if (mShouldRestoreconData) {
16169            SELinuxMMAC.setRestoreconDone();
16170            mShouldRestoreconData = false;
16171        }
16172    }
16173
16174    /*
16175     * Collect information of applications on external media, map them against
16176     * existing containers and update information based on current mount status.
16177     * Please note that we always have to report status if reportStatus has been
16178     * set to true especially when unloading packages.
16179     */
16180    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16181            boolean externalStorage) {
16182        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16183        int[] uidArr = EmptyArray.INT;
16184
16185        final String[] list = PackageHelper.getSecureContainerList();
16186        if (ArrayUtils.isEmpty(list)) {
16187            Log.i(TAG, "No secure containers found");
16188        } else {
16189            // Process list of secure containers and categorize them
16190            // as active or stale based on their package internal state.
16191
16192            // reader
16193            synchronized (mPackages) {
16194                for (String cid : list) {
16195                    // Leave stages untouched for now; installer service owns them
16196                    if (PackageInstallerService.isStageName(cid)) continue;
16197
16198                    if (DEBUG_SD_INSTALL)
16199                        Log.i(TAG, "Processing container " + cid);
16200                    String pkgName = getAsecPackageName(cid);
16201                    if (pkgName == null) {
16202                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16203                        continue;
16204                    }
16205                    if (DEBUG_SD_INSTALL)
16206                        Log.i(TAG, "Looking for pkg : " + pkgName);
16207
16208                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16209                    if (ps == null) {
16210                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16211                        continue;
16212                    }
16213
16214                    /*
16215                     * Skip packages that are not external if we're unmounting
16216                     * external storage.
16217                     */
16218                    if (externalStorage && !isMounted && !isExternal(ps)) {
16219                        continue;
16220                    }
16221
16222                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16223                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16224                    // The package status is changed only if the code path
16225                    // matches between settings and the container id.
16226                    if (ps.codePathString != null
16227                            && ps.codePathString.startsWith(args.getCodePath())) {
16228                        if (DEBUG_SD_INSTALL) {
16229                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16230                                    + " at code path: " + ps.codePathString);
16231                        }
16232
16233                        // We do have a valid package installed on sdcard
16234                        processCids.put(args, ps.codePathString);
16235                        final int uid = ps.appId;
16236                        if (uid != -1) {
16237                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16238                        }
16239                    } else {
16240                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16241                                + ps.codePathString);
16242                    }
16243                }
16244            }
16245
16246            Arrays.sort(uidArr);
16247        }
16248
16249        // Process packages with valid entries.
16250        if (isMounted) {
16251            if (DEBUG_SD_INSTALL)
16252                Log.i(TAG, "Loading packages");
16253            loadMediaPackages(processCids, uidArr, externalStorage);
16254            startCleaningPackages();
16255            mInstallerService.onSecureContainersAvailable();
16256        } else {
16257            if (DEBUG_SD_INSTALL)
16258                Log.i(TAG, "Unloading packages");
16259            unloadMediaPackages(processCids, uidArr, reportStatus);
16260        }
16261    }
16262
16263    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16264            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16265        final int size = infos.size();
16266        final String[] packageNames = new String[size];
16267        final int[] packageUids = new int[size];
16268        for (int i = 0; i < size; i++) {
16269            final ApplicationInfo info = infos.get(i);
16270            packageNames[i] = info.packageName;
16271            packageUids[i] = info.uid;
16272        }
16273        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16274                finishedReceiver);
16275    }
16276
16277    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16278            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16279        sendResourcesChangedBroadcast(mediaStatus, replacing,
16280                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16281    }
16282
16283    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16284            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16285        int size = pkgList.length;
16286        if (size > 0) {
16287            // Send broadcasts here
16288            Bundle extras = new Bundle();
16289            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16290            if (uidArr != null) {
16291                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16292            }
16293            if (replacing) {
16294                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16295            }
16296            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16297                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16298            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16299        }
16300    }
16301
16302   /*
16303     * Look at potentially valid container ids from processCids If package
16304     * information doesn't match the one on record or package scanning fails,
16305     * the cid is added to list of removeCids. We currently don't delete stale
16306     * containers.
16307     */
16308    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16309            boolean externalStorage) {
16310        ArrayList<String> pkgList = new ArrayList<String>();
16311        Set<AsecInstallArgs> keys = processCids.keySet();
16312
16313        for (AsecInstallArgs args : keys) {
16314            String codePath = processCids.get(args);
16315            if (DEBUG_SD_INSTALL)
16316                Log.i(TAG, "Loading container : " + args.cid);
16317            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16318            try {
16319                // Make sure there are no container errors first.
16320                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16321                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16322                            + " when installing from sdcard");
16323                    continue;
16324                }
16325                // Check code path here.
16326                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16327                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16328                            + " does not match one in settings " + codePath);
16329                    continue;
16330                }
16331                // Parse package
16332                int parseFlags = mDefParseFlags;
16333                if (args.isExternalAsec()) {
16334                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16335                }
16336                if (args.isFwdLocked()) {
16337                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16338                }
16339
16340                synchronized (mInstallLock) {
16341                    PackageParser.Package pkg = null;
16342                    try {
16343                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16344                    } catch (PackageManagerException e) {
16345                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16346                    }
16347                    // Scan the package
16348                    if (pkg != null) {
16349                        /*
16350                         * TODO why is the lock being held? doPostInstall is
16351                         * called in other places without the lock. This needs
16352                         * to be straightened out.
16353                         */
16354                        // writer
16355                        synchronized (mPackages) {
16356                            retCode = PackageManager.INSTALL_SUCCEEDED;
16357                            pkgList.add(pkg.packageName);
16358                            // Post process args
16359                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16360                                    pkg.applicationInfo.uid);
16361                        }
16362                    } else {
16363                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16364                    }
16365                }
16366
16367            } finally {
16368                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16369                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16370                }
16371            }
16372        }
16373        // writer
16374        synchronized (mPackages) {
16375            // If the platform SDK has changed since the last time we booted,
16376            // we need to re-grant app permission to catch any new ones that
16377            // appear. This is really a hack, and means that apps can in some
16378            // cases get permissions that the user didn't initially explicitly
16379            // allow... it would be nice to have some better way to handle
16380            // this situation.
16381            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16382                    : mSettings.getInternalVersion();
16383            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16384                    : StorageManager.UUID_PRIVATE_INTERNAL;
16385
16386            int updateFlags = UPDATE_PERMISSIONS_ALL;
16387            if (ver.sdkVersion != mSdkVersion) {
16388                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16389                        + mSdkVersion + "; regranting permissions for external");
16390                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16391            }
16392            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16393
16394            // Yay, everything is now upgraded
16395            ver.forceCurrent();
16396
16397            // can downgrade to reader
16398            // Persist settings
16399            mSettings.writeLPr();
16400        }
16401        // Send a broadcast to let everyone know we are done processing
16402        if (pkgList.size() > 0) {
16403            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16404        }
16405    }
16406
16407   /*
16408     * Utility method to unload a list of specified containers
16409     */
16410    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16411        // Just unmount all valid containers.
16412        for (AsecInstallArgs arg : cidArgs) {
16413            synchronized (mInstallLock) {
16414                arg.doPostDeleteLI(false);
16415           }
16416       }
16417   }
16418
16419    /*
16420     * Unload packages mounted on external media. This involves deleting package
16421     * data from internal structures, sending broadcasts about diabled packages,
16422     * gc'ing to free up references, unmounting all secure containers
16423     * corresponding to packages on external media, and posting a
16424     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16425     * that we always have to post this message if status has been requested no
16426     * matter what.
16427     */
16428    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16429            final boolean reportStatus) {
16430        if (DEBUG_SD_INSTALL)
16431            Log.i(TAG, "unloading media packages");
16432        ArrayList<String> pkgList = new ArrayList<String>();
16433        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16434        final Set<AsecInstallArgs> keys = processCids.keySet();
16435        for (AsecInstallArgs args : keys) {
16436            String pkgName = args.getPackageName();
16437            if (DEBUG_SD_INSTALL)
16438                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16439            // Delete package internally
16440            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16441            synchronized (mInstallLock) {
16442                boolean res = deletePackageLI(pkgName, null, false, null, null,
16443                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16444                if (res) {
16445                    pkgList.add(pkgName);
16446                } else {
16447                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16448                    failedList.add(args);
16449                }
16450            }
16451        }
16452
16453        // reader
16454        synchronized (mPackages) {
16455            // We didn't update the settings after removing each package;
16456            // write them now for all packages.
16457            mSettings.writeLPr();
16458        }
16459
16460        // We have to absolutely send UPDATED_MEDIA_STATUS only
16461        // after confirming that all the receivers processed the ordered
16462        // broadcast when packages get disabled, force a gc to clean things up.
16463        // and unload all the containers.
16464        if (pkgList.size() > 0) {
16465            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16466                    new IIntentReceiver.Stub() {
16467                public void performReceive(Intent intent, int resultCode, String data,
16468                        Bundle extras, boolean ordered, boolean sticky,
16469                        int sendingUser) throws RemoteException {
16470                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16471                            reportStatus ? 1 : 0, 1, keys);
16472                    mHandler.sendMessage(msg);
16473                }
16474            });
16475        } else {
16476            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16477                    keys);
16478            mHandler.sendMessage(msg);
16479        }
16480    }
16481
16482    private void loadPrivatePackages(final VolumeInfo vol) {
16483        mHandler.post(new Runnable() {
16484            @Override
16485            public void run() {
16486                loadPrivatePackagesInner(vol);
16487            }
16488        });
16489    }
16490
16491    private void loadPrivatePackagesInner(VolumeInfo vol) {
16492        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16493        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16494
16495        final VersionInfo ver;
16496        final List<PackageSetting> packages;
16497        synchronized (mPackages) {
16498            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16499            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16500        }
16501
16502        for (PackageSetting ps : packages) {
16503            synchronized (mInstallLock) {
16504                final PackageParser.Package pkg;
16505                try {
16506                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16507                    loaded.add(pkg.applicationInfo);
16508                } catch (PackageManagerException e) {
16509                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16510                }
16511
16512                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16513                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16514                }
16515            }
16516        }
16517
16518        synchronized (mPackages) {
16519            int updateFlags = UPDATE_PERMISSIONS_ALL;
16520            if (ver.sdkVersion != mSdkVersion) {
16521                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16522                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16523                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16524            }
16525            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16526
16527            // Yay, everything is now upgraded
16528            ver.forceCurrent();
16529
16530            mSettings.writeLPr();
16531        }
16532
16533        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16534        sendResourcesChangedBroadcast(true, false, loaded, null);
16535    }
16536
16537    private void unloadPrivatePackages(final VolumeInfo vol) {
16538        mHandler.post(new Runnable() {
16539            @Override
16540            public void run() {
16541                unloadPrivatePackagesInner(vol);
16542            }
16543        });
16544    }
16545
16546    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16547        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16548        synchronized (mInstallLock) {
16549        synchronized (mPackages) {
16550            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16551            for (PackageSetting ps : packages) {
16552                if (ps.pkg == null) continue;
16553
16554                final ApplicationInfo info = ps.pkg.applicationInfo;
16555                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16556                if (deletePackageLI(ps.name, null, false, null, null,
16557                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16558                    unloaded.add(info);
16559                } else {
16560                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16561                }
16562            }
16563
16564            mSettings.writeLPr();
16565        }
16566        }
16567
16568        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16569        sendResourcesChangedBroadcast(false, false, unloaded, null);
16570    }
16571
16572    /**
16573     * Examine all users present on given mounted volume, and destroy data
16574     * belonging to users that are no longer valid, or whose user ID has been
16575     * recycled.
16576     */
16577    private void reconcileUsers(String volumeUuid) {
16578        final File[] files = FileUtils
16579                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16580        for (File file : files) {
16581            if (!file.isDirectory()) continue;
16582
16583            final int userId;
16584            final UserInfo info;
16585            try {
16586                userId = Integer.parseInt(file.getName());
16587                info = sUserManager.getUserInfo(userId);
16588            } catch (NumberFormatException e) {
16589                Slog.w(TAG, "Invalid user directory " + file);
16590                continue;
16591            }
16592
16593            boolean destroyUser = false;
16594            if (info == null) {
16595                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16596                        + " because no matching user was found");
16597                destroyUser = true;
16598            } else {
16599                try {
16600                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16601                } catch (IOException e) {
16602                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16603                            + " because we failed to enforce serial number: " + e);
16604                    destroyUser = true;
16605                }
16606            }
16607
16608            if (destroyUser) {
16609                synchronized (mInstallLock) {
16610                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16611                }
16612            }
16613        }
16614
16615        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16616        final UserManager um = mContext.getSystemService(UserManager.class);
16617        for (UserInfo user : um.getUsers()) {
16618            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16619            if (userDir.exists()) continue;
16620
16621            try {
16622                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16623                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16624            } catch (IOException e) {
16625                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16626            }
16627        }
16628    }
16629
16630    /**
16631     * Examine all apps present on given mounted volume, and destroy apps that
16632     * aren't expected, either due to uninstallation or reinstallation on
16633     * another volume.
16634     */
16635    private void reconcileApps(String volumeUuid) {
16636        final File[] files = FileUtils
16637                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16638        for (File file : files) {
16639            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16640                    && !PackageInstallerService.isStageName(file.getName());
16641            if (!isPackage) {
16642                // Ignore entries which are not packages
16643                continue;
16644            }
16645
16646            boolean destroyApp = false;
16647            String packageName = null;
16648            try {
16649                final PackageLite pkg = PackageParser.parsePackageLite(file,
16650                        PackageParser.PARSE_MUST_BE_APK);
16651                packageName = pkg.packageName;
16652
16653                synchronized (mPackages) {
16654                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16655                    if (ps == null) {
16656                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16657                                + volumeUuid + " because we found no install record");
16658                        destroyApp = true;
16659                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16660                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16661                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16662                        destroyApp = true;
16663                    }
16664                }
16665
16666            } catch (PackageParserException e) {
16667                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16668                destroyApp = true;
16669            }
16670
16671            if (destroyApp) {
16672                synchronized (mInstallLock) {
16673                    if (packageName != null) {
16674                        removeDataDirsLI(volumeUuid, packageName);
16675                    }
16676                    if (file.isDirectory()) {
16677                        mInstaller.rmPackageDir(file.getAbsolutePath());
16678                    } else {
16679                        file.delete();
16680                    }
16681                }
16682            }
16683        }
16684    }
16685
16686    private void unfreezePackage(String packageName) {
16687        synchronized (mPackages) {
16688            final PackageSetting ps = mSettings.mPackages.get(packageName);
16689            if (ps != null) {
16690                ps.frozen = false;
16691            }
16692        }
16693    }
16694
16695    @Override
16696    public int movePackage(final String packageName, final String volumeUuid) {
16697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16698
16699        final int moveId = mNextMoveId.getAndIncrement();
16700        mHandler.post(new Runnable() {
16701            @Override
16702            public void run() {
16703                try {
16704                    movePackageInternal(packageName, volumeUuid, moveId);
16705                } catch (PackageManagerException e) {
16706                    Slog.w(TAG, "Failed to move " + packageName, e);
16707                    mMoveCallbacks.notifyStatusChanged(moveId,
16708                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16709                }
16710            }
16711        });
16712        return moveId;
16713    }
16714
16715    private void movePackageInternal(final String packageName, final String volumeUuid,
16716            final int moveId) throws PackageManagerException {
16717        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16718        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16719        final PackageManager pm = mContext.getPackageManager();
16720
16721        final boolean currentAsec;
16722        final String currentVolumeUuid;
16723        final File codeFile;
16724        final String installerPackageName;
16725        final String packageAbiOverride;
16726        final int appId;
16727        final String seinfo;
16728        final String label;
16729
16730        // reader
16731        synchronized (mPackages) {
16732            final PackageParser.Package pkg = mPackages.get(packageName);
16733            final PackageSetting ps = mSettings.mPackages.get(packageName);
16734            if (pkg == null || ps == null) {
16735                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16736            }
16737
16738            if (pkg.applicationInfo.isSystemApp()) {
16739                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16740                        "Cannot move system application");
16741            }
16742
16743            if (pkg.applicationInfo.isExternalAsec()) {
16744                currentAsec = true;
16745                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16746            } else if (pkg.applicationInfo.isForwardLocked()) {
16747                currentAsec = true;
16748                currentVolumeUuid = "forward_locked";
16749            } else {
16750                currentAsec = false;
16751                currentVolumeUuid = ps.volumeUuid;
16752
16753                final File probe = new File(pkg.codePath);
16754                final File probeOat = new File(probe, "oat");
16755                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16756                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16757                            "Move only supported for modern cluster style installs");
16758                }
16759            }
16760
16761            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16762                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16763                        "Package already moved to " + volumeUuid);
16764            }
16765
16766            if (ps.frozen) {
16767                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16768                        "Failed to move already frozen package");
16769            }
16770            ps.frozen = true;
16771
16772            codeFile = new File(pkg.codePath);
16773            installerPackageName = ps.installerPackageName;
16774            packageAbiOverride = ps.cpuAbiOverrideString;
16775            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16776            seinfo = pkg.applicationInfo.seinfo;
16777            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16778        }
16779
16780        // Now that we're guarded by frozen state, kill app during move
16781        final long token = Binder.clearCallingIdentity();
16782        try {
16783            killApplication(packageName, appId, "move pkg");
16784        } finally {
16785            Binder.restoreCallingIdentity(token);
16786        }
16787
16788        final Bundle extras = new Bundle();
16789        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16790        extras.putString(Intent.EXTRA_TITLE, label);
16791        mMoveCallbacks.notifyCreated(moveId, extras);
16792
16793        int installFlags;
16794        final boolean moveCompleteApp;
16795        final File measurePath;
16796
16797        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16798            installFlags = INSTALL_INTERNAL;
16799            moveCompleteApp = !currentAsec;
16800            measurePath = Environment.getDataAppDirectory(volumeUuid);
16801        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16802            installFlags = INSTALL_EXTERNAL;
16803            moveCompleteApp = false;
16804            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16805        } else {
16806            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16807            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16808                    || !volume.isMountedWritable()) {
16809                unfreezePackage(packageName);
16810                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16811                        "Move location not mounted private volume");
16812            }
16813
16814            Preconditions.checkState(!currentAsec);
16815
16816            installFlags = INSTALL_INTERNAL;
16817            moveCompleteApp = true;
16818            measurePath = Environment.getDataAppDirectory(volumeUuid);
16819        }
16820
16821        final PackageStats stats = new PackageStats(null, -1);
16822        synchronized (mInstaller) {
16823            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16824                unfreezePackage(packageName);
16825                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16826                        "Failed to measure package size");
16827            }
16828        }
16829
16830        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16831                + stats.dataSize);
16832
16833        final long startFreeBytes = measurePath.getFreeSpace();
16834        final long sizeBytes;
16835        if (moveCompleteApp) {
16836            sizeBytes = stats.codeSize + stats.dataSize;
16837        } else {
16838            sizeBytes = stats.codeSize;
16839        }
16840
16841        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16842            unfreezePackage(packageName);
16843            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16844                    "Not enough free space to move");
16845        }
16846
16847        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16848
16849        final CountDownLatch installedLatch = new CountDownLatch(1);
16850        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16851            @Override
16852            public void onUserActionRequired(Intent intent) throws RemoteException {
16853                throw new IllegalStateException();
16854            }
16855
16856            @Override
16857            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16858                    Bundle extras) throws RemoteException {
16859                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16860                        + PackageManager.installStatusToString(returnCode, msg));
16861
16862                installedLatch.countDown();
16863
16864                // Regardless of success or failure of the move operation,
16865                // always unfreeze the package
16866                unfreezePackage(packageName);
16867
16868                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16869                switch (status) {
16870                    case PackageInstaller.STATUS_SUCCESS:
16871                        mMoveCallbacks.notifyStatusChanged(moveId,
16872                                PackageManager.MOVE_SUCCEEDED);
16873                        break;
16874                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16875                        mMoveCallbacks.notifyStatusChanged(moveId,
16876                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16877                        break;
16878                    default:
16879                        mMoveCallbacks.notifyStatusChanged(moveId,
16880                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16881                        break;
16882                }
16883            }
16884        };
16885
16886        final MoveInfo move;
16887        if (moveCompleteApp) {
16888            // Kick off a thread to report progress estimates
16889            new Thread() {
16890                @Override
16891                public void run() {
16892                    while (true) {
16893                        try {
16894                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16895                                break;
16896                            }
16897                        } catch (InterruptedException ignored) {
16898                        }
16899
16900                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16901                        final int progress = 10 + (int) MathUtils.constrain(
16902                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16903                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16904                    }
16905                }
16906            }.start();
16907
16908            final String dataAppName = codeFile.getName();
16909            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16910                    dataAppName, appId, seinfo);
16911        } else {
16912            move = null;
16913        }
16914
16915        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16916
16917        final Message msg = mHandler.obtainMessage(INIT_COPY);
16918        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16919        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16920                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16921        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16922        msg.obj = params;
16923
16924        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16925                System.identityHashCode(msg.obj));
16926        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16927                System.identityHashCode(msg.obj));
16928
16929        mHandler.sendMessage(msg);
16930    }
16931
16932    @Override
16933    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16934        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16935
16936        final int realMoveId = mNextMoveId.getAndIncrement();
16937        final Bundle extras = new Bundle();
16938        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16939        mMoveCallbacks.notifyCreated(realMoveId, extras);
16940
16941        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16942            @Override
16943            public void onCreated(int moveId, Bundle extras) {
16944                // Ignored
16945            }
16946
16947            @Override
16948            public void onStatusChanged(int moveId, int status, long estMillis) {
16949                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16950            }
16951        };
16952
16953        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16954        storage.setPrimaryStorageUuid(volumeUuid, callback);
16955        return realMoveId;
16956    }
16957
16958    @Override
16959    public int getMoveStatus(int moveId) {
16960        mContext.enforceCallingOrSelfPermission(
16961                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16962        return mMoveCallbacks.mLastStatus.get(moveId);
16963    }
16964
16965    @Override
16966    public void registerMoveCallback(IPackageMoveObserver callback) {
16967        mContext.enforceCallingOrSelfPermission(
16968                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16969        mMoveCallbacks.register(callback);
16970    }
16971
16972    @Override
16973    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16974        mContext.enforceCallingOrSelfPermission(
16975                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16976        mMoveCallbacks.unregister(callback);
16977    }
16978
16979    @Override
16980    public boolean setInstallLocation(int loc) {
16981        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16982                null);
16983        if (getInstallLocation() == loc) {
16984            return true;
16985        }
16986        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16987                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16988            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16989                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16990            return true;
16991        }
16992        return false;
16993   }
16994
16995    @Override
16996    public int getInstallLocation() {
16997        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16998                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16999                PackageHelper.APP_INSTALL_AUTO);
17000    }
17001
17002    /** Called by UserManagerService */
17003    void cleanUpUser(UserManagerService userManager, int userHandle) {
17004        synchronized (mPackages) {
17005            mDirtyUsers.remove(userHandle);
17006            mUserNeedsBadging.delete(userHandle);
17007            mSettings.removeUserLPw(userHandle);
17008            mPendingBroadcasts.remove(userHandle);
17009            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
17010        }
17011        synchronized (mInstallLock) {
17012            final StorageManager storage = mContext.getSystemService(StorageManager.class);
17013            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
17014                final String volumeUuid = vol.getFsUuid();
17015                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
17016                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
17017            }
17018            synchronized (mPackages) {
17019                removeUnusedPackagesLILPw(userManager, userHandle);
17020            }
17021        }
17022    }
17023
17024    /**
17025     * We're removing userHandle and would like to remove any downloaded packages
17026     * that are no longer in use by any other user.
17027     * @param userHandle the user being removed
17028     */
17029    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
17030        final boolean DEBUG_CLEAN_APKS = false;
17031        int [] users = userManager.getUserIds();
17032        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
17033        while (psit.hasNext()) {
17034            PackageSetting ps = psit.next();
17035            if (ps.pkg == null) {
17036                continue;
17037            }
17038            final String packageName = ps.pkg.packageName;
17039            // Skip over if system app
17040            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
17041                continue;
17042            }
17043            if (DEBUG_CLEAN_APKS) {
17044                Slog.i(TAG, "Checking package " + packageName);
17045            }
17046            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17047            if (keep) {
17048                if (DEBUG_CLEAN_APKS) {
17049                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17050                }
17051            } else {
17052                for (int i = 0; i < users.length; i++) {
17053                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17054                        keep = true;
17055                        if (DEBUG_CLEAN_APKS) {
17056                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17057                                    + users[i]);
17058                        }
17059                        break;
17060                    }
17061                }
17062            }
17063            if (!keep) {
17064                if (DEBUG_CLEAN_APKS) {
17065                    Slog.i(TAG, "  Removing package " + packageName);
17066                }
17067                mHandler.post(new Runnable() {
17068                    public void run() {
17069                        deletePackageX(packageName, userHandle, 0);
17070                    } //end run
17071                });
17072            }
17073        }
17074    }
17075
17076    /** Called by UserManagerService */
17077    void createNewUser(int userHandle) {
17078        synchronized (mInstallLock) {
17079            mInstaller.createUserConfig(userHandle);
17080            mSettings.createNewUserLI(this, mInstaller, userHandle);
17081        }
17082        synchronized (mPackages) {
17083            applyFactoryDefaultBrowserLPw(userHandle);
17084            primeDomainVerificationsLPw(userHandle);
17085        }
17086    }
17087
17088    void newUserCreated(final int userHandle) {
17089        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17090        // If permission review for legacy apps is required, we represent
17091        // dagerous permissions for such apps as always granted runtime
17092        // permissions to keep per user flag state whether review is needed.
17093        // Hence, if a new user is added we have to propagate dangerous
17094        // permission grants for these legacy apps.
17095        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17096            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17097                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17098        }
17099    }
17100
17101    @Override
17102    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17103        mContext.enforceCallingOrSelfPermission(
17104                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17105                "Only package verification agents can read the verifier device identity");
17106
17107        synchronized (mPackages) {
17108            return mSettings.getVerifierDeviceIdentityLPw();
17109        }
17110    }
17111
17112    @Override
17113    public void setPermissionEnforced(String permission, boolean enforced) {
17114        // TODO: Now that we no longer change GID for storage, this should to away.
17115        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17116                "setPermissionEnforced");
17117        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17118            synchronized (mPackages) {
17119                if (mSettings.mReadExternalStorageEnforced == null
17120                        || mSettings.mReadExternalStorageEnforced != enforced) {
17121                    mSettings.mReadExternalStorageEnforced = enforced;
17122                    mSettings.writeLPr();
17123                }
17124            }
17125            // kill any non-foreground processes so we restart them and
17126            // grant/revoke the GID.
17127            final IActivityManager am = ActivityManagerNative.getDefault();
17128            if (am != null) {
17129                final long token = Binder.clearCallingIdentity();
17130                try {
17131                    am.killProcessesBelowForeground("setPermissionEnforcement");
17132                } catch (RemoteException e) {
17133                } finally {
17134                    Binder.restoreCallingIdentity(token);
17135                }
17136            }
17137        } else {
17138            throw new IllegalArgumentException("No selective enforcement for " + permission);
17139        }
17140    }
17141
17142    @Override
17143    @Deprecated
17144    public boolean isPermissionEnforced(String permission) {
17145        return true;
17146    }
17147
17148    @Override
17149    public boolean isStorageLow() {
17150        final long token = Binder.clearCallingIdentity();
17151        try {
17152            final DeviceStorageMonitorInternal
17153                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17154            if (dsm != null) {
17155                return dsm.isMemoryLow();
17156            } else {
17157                return false;
17158            }
17159        } finally {
17160            Binder.restoreCallingIdentity(token);
17161        }
17162    }
17163
17164    @Override
17165    public IPackageInstaller getPackageInstaller() {
17166        return mInstallerService;
17167    }
17168
17169    private boolean userNeedsBadging(int userId) {
17170        int index = mUserNeedsBadging.indexOfKey(userId);
17171        if (index < 0) {
17172            final UserInfo userInfo;
17173            final long token = Binder.clearCallingIdentity();
17174            try {
17175                userInfo = sUserManager.getUserInfo(userId);
17176            } finally {
17177                Binder.restoreCallingIdentity(token);
17178            }
17179            final boolean b;
17180            if (userInfo != null && userInfo.isManagedProfile()) {
17181                b = true;
17182            } else {
17183                b = false;
17184            }
17185            mUserNeedsBadging.put(userId, b);
17186            return b;
17187        }
17188        return mUserNeedsBadging.valueAt(index);
17189    }
17190
17191    @Override
17192    public KeySet getKeySetByAlias(String packageName, String alias) {
17193        if (packageName == null || alias == null) {
17194            return null;
17195        }
17196        synchronized(mPackages) {
17197            final PackageParser.Package pkg = mPackages.get(packageName);
17198            if (pkg == null) {
17199                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17200                throw new IllegalArgumentException("Unknown package: " + packageName);
17201            }
17202            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17203            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17204        }
17205    }
17206
17207    @Override
17208    public KeySet getSigningKeySet(String packageName) {
17209        if (packageName == null) {
17210            return null;
17211        }
17212        synchronized(mPackages) {
17213            final PackageParser.Package pkg = mPackages.get(packageName);
17214            if (pkg == null) {
17215                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17216                throw new IllegalArgumentException("Unknown package: " + packageName);
17217            }
17218            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17219                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17220                throw new SecurityException("May not access signing KeySet of other apps.");
17221            }
17222            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17223            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17224        }
17225    }
17226
17227    @Override
17228    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17229        if (packageName == null || ks == null) {
17230            return false;
17231        }
17232        synchronized(mPackages) {
17233            final PackageParser.Package pkg = mPackages.get(packageName);
17234            if (pkg == null) {
17235                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17236                throw new IllegalArgumentException("Unknown package: " + packageName);
17237            }
17238            IBinder ksh = ks.getToken();
17239            if (ksh instanceof KeySetHandle) {
17240                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17241                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17242            }
17243            return false;
17244        }
17245    }
17246
17247    @Override
17248    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17249        if (packageName == null || ks == null) {
17250            return false;
17251        }
17252        synchronized(mPackages) {
17253            final PackageParser.Package pkg = mPackages.get(packageName);
17254            if (pkg == null) {
17255                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17256                throw new IllegalArgumentException("Unknown package: " + packageName);
17257            }
17258            IBinder ksh = ks.getToken();
17259            if (ksh instanceof KeySetHandle) {
17260                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17261                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17262            }
17263            return false;
17264        }
17265    }
17266
17267    private void deletePackageIfUnusedLPr(final String packageName) {
17268        PackageSetting ps = mSettings.mPackages.get(packageName);
17269        if (ps == null) {
17270            return;
17271        }
17272        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17273            // TODO Implement atomic delete if package is unused
17274            // It is currently possible that the package will be deleted even if it is installed
17275            // after this method returns.
17276            mHandler.post(new Runnable() {
17277                public void run() {
17278                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17279                }
17280            });
17281        }
17282    }
17283
17284    /**
17285     * Check and throw if the given before/after packages would be considered a
17286     * downgrade.
17287     */
17288    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17289            throws PackageManagerException {
17290        if (after.versionCode < before.mVersionCode) {
17291            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17292                    "Update version code " + after.versionCode + " is older than current "
17293                    + before.mVersionCode);
17294        } else if (after.versionCode == before.mVersionCode) {
17295            if (after.baseRevisionCode < before.baseRevisionCode) {
17296                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17297                        "Update base revision code " + after.baseRevisionCode
17298                        + " is older than current " + before.baseRevisionCode);
17299            }
17300
17301            if (!ArrayUtils.isEmpty(after.splitNames)) {
17302                for (int i = 0; i < after.splitNames.length; i++) {
17303                    final String splitName = after.splitNames[i];
17304                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17305                    if (j != -1) {
17306                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17307                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17308                                    "Update split " + splitName + " revision code "
17309                                    + after.splitRevisionCodes[i] + " is older than current "
17310                                    + before.splitRevisionCodes[j]);
17311                        }
17312                    }
17313                }
17314            }
17315        }
17316    }
17317
17318    private static class MoveCallbacks extends Handler {
17319        private static final int MSG_CREATED = 1;
17320        private static final int MSG_STATUS_CHANGED = 2;
17321
17322        private final RemoteCallbackList<IPackageMoveObserver>
17323                mCallbacks = new RemoteCallbackList<>();
17324
17325        private final SparseIntArray mLastStatus = new SparseIntArray();
17326
17327        public MoveCallbacks(Looper looper) {
17328            super(looper);
17329        }
17330
17331        public void register(IPackageMoveObserver callback) {
17332            mCallbacks.register(callback);
17333        }
17334
17335        public void unregister(IPackageMoveObserver callback) {
17336            mCallbacks.unregister(callback);
17337        }
17338
17339        @Override
17340        public void handleMessage(Message msg) {
17341            final SomeArgs args = (SomeArgs) msg.obj;
17342            final int n = mCallbacks.beginBroadcast();
17343            for (int i = 0; i < n; i++) {
17344                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17345                try {
17346                    invokeCallback(callback, msg.what, args);
17347                } catch (RemoteException ignored) {
17348                }
17349            }
17350            mCallbacks.finishBroadcast();
17351            args.recycle();
17352        }
17353
17354        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17355                throws RemoteException {
17356            switch (what) {
17357                case MSG_CREATED: {
17358                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17359                    break;
17360                }
17361                case MSG_STATUS_CHANGED: {
17362                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17363                    break;
17364                }
17365            }
17366        }
17367
17368        private void notifyCreated(int moveId, Bundle extras) {
17369            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17370
17371            final SomeArgs args = SomeArgs.obtain();
17372            args.argi1 = moveId;
17373            args.arg2 = extras;
17374            obtainMessage(MSG_CREATED, args).sendToTarget();
17375        }
17376
17377        private void notifyStatusChanged(int moveId, int status) {
17378            notifyStatusChanged(moveId, status, -1);
17379        }
17380
17381        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17382            Slog.v(TAG, "Move " + moveId + " status " + status);
17383
17384            final SomeArgs args = SomeArgs.obtain();
17385            args.argi1 = moveId;
17386            args.argi2 = status;
17387            args.arg3 = estMillis;
17388            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17389
17390            synchronized (mLastStatus) {
17391                mLastStatus.put(moveId, status);
17392            }
17393        }
17394    }
17395
17396    private final static class OnPermissionChangeListeners extends Handler {
17397        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17398
17399        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17400                new RemoteCallbackList<>();
17401
17402        public OnPermissionChangeListeners(Looper looper) {
17403            super(looper);
17404        }
17405
17406        @Override
17407        public void handleMessage(Message msg) {
17408            switch (msg.what) {
17409                case MSG_ON_PERMISSIONS_CHANGED: {
17410                    final int uid = msg.arg1;
17411                    handleOnPermissionsChanged(uid);
17412                } break;
17413            }
17414        }
17415
17416        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17417            mPermissionListeners.register(listener);
17418
17419        }
17420
17421        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17422            mPermissionListeners.unregister(listener);
17423        }
17424
17425        public void onPermissionsChanged(int uid) {
17426            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17427                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17428            }
17429        }
17430
17431        private void handleOnPermissionsChanged(int uid) {
17432            final int count = mPermissionListeners.beginBroadcast();
17433            try {
17434                for (int i = 0; i < count; i++) {
17435                    IOnPermissionsChangeListener callback = mPermissionListeners
17436                            .getBroadcastItem(i);
17437                    try {
17438                        callback.onPermissionsChanged(uid);
17439                    } catch (RemoteException e) {
17440                        Log.e(TAG, "Permission listener is dead", e);
17441                    }
17442                }
17443            } finally {
17444                mPermissionListeners.finishBroadcast();
17445            }
17446        }
17447    }
17448
17449    private class PackageManagerInternalImpl extends PackageManagerInternal {
17450        @Override
17451        public void setLocationPackagesProvider(PackagesProvider provider) {
17452            synchronized (mPackages) {
17453                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17454            }
17455        }
17456
17457        @Override
17458        public void setImePackagesProvider(PackagesProvider provider) {
17459            synchronized (mPackages) {
17460                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17461            }
17462        }
17463
17464        @Override
17465        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17466            synchronized (mPackages) {
17467                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17468            }
17469        }
17470
17471        @Override
17472        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17473            synchronized (mPackages) {
17474                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17475            }
17476        }
17477
17478        @Override
17479        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17480            synchronized (mPackages) {
17481                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17482            }
17483        }
17484
17485        @Override
17486        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17487            synchronized (mPackages) {
17488                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17489            }
17490        }
17491
17492        @Override
17493        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17494            synchronized (mPackages) {
17495                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17496            }
17497        }
17498
17499        @Override
17500        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17501            synchronized (mPackages) {
17502                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17503                        packageName, userId);
17504            }
17505        }
17506
17507        @Override
17508        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17509            synchronized (mPackages) {
17510                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17511                        packageName, userId);
17512            }
17513        }
17514
17515        @Override
17516        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17517            synchronized (mPackages) {
17518                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17519                        packageName, userId);
17520            }
17521        }
17522
17523        @Override
17524        public void setKeepUninstalledPackages(final List<String> packageList) {
17525            Preconditions.checkNotNull(packageList);
17526            List<String> removedFromList = null;
17527            synchronized (mPackages) {
17528                if (mKeepUninstalledPackages != null) {
17529                    final int packagesCount = mKeepUninstalledPackages.size();
17530                    for (int i = 0; i < packagesCount; i++) {
17531                        String oldPackage = mKeepUninstalledPackages.get(i);
17532                        if (packageList != null && packageList.contains(oldPackage)) {
17533                            continue;
17534                        }
17535                        if (removedFromList == null) {
17536                            removedFromList = new ArrayList<>();
17537                        }
17538                        removedFromList.add(oldPackage);
17539                    }
17540                }
17541                mKeepUninstalledPackages = new ArrayList<>(packageList);
17542                if (removedFromList != null) {
17543                    final int removedCount = removedFromList.size();
17544                    for (int i = 0; i < removedCount; i++) {
17545                        deletePackageIfUnusedLPr(removedFromList.get(i));
17546                    }
17547                }
17548            }
17549        }
17550
17551        @Override
17552        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17553            synchronized (mPackages) {
17554                // If we do not support permission review, done.
17555                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17556                    return false;
17557                }
17558
17559                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17560                if (packageSetting == null) {
17561                    return false;
17562                }
17563
17564                // Permission review applies only to apps not supporting the new permission model.
17565                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17566                    return false;
17567                }
17568
17569                // Legacy apps have the permission and get user consent on launch.
17570                PermissionsState permissionsState = packageSetting.getPermissionsState();
17571                return permissionsState.isPermissionReviewRequired(userId);
17572            }
17573        }
17574    }
17575
17576    @Override
17577    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17578        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17579        synchronized (mPackages) {
17580            final long identity = Binder.clearCallingIdentity();
17581            try {
17582                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17583                        packageNames, userId);
17584            } finally {
17585                Binder.restoreCallingIdentity(identity);
17586            }
17587        }
17588    }
17589
17590    private static void enforceSystemOrPhoneCaller(String tag) {
17591        int callingUid = Binder.getCallingUid();
17592        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17593            throw new SecurityException(
17594                    "Cannot call " + tag + " from UID " + callingUid);
17595        }
17596    }
17597}
17598