PackageManagerService.java revision 31ffb442414bd9cf6c0225799d7d0c5409f3769d
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.EphemeralApplicationInfo;
110import android.content.pm.EphemeralResolveInfo;
111import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
112import android.content.pm.FeatureInfo;
113import android.content.pm.IOnPermissionsChangeListener;
114import android.content.pm.IPackageDataObserver;
115import android.content.pm.IPackageDeleteObserver;
116import android.content.pm.IPackageDeleteObserver2;
117import android.content.pm.IPackageInstallObserver2;
118import android.content.pm.IPackageInstaller;
119import android.content.pm.IPackageManager;
120import android.content.pm.IPackageMoveObserver;
121import android.content.pm.IPackageStatsObserver;
122import android.content.pm.InstrumentationInfo;
123import android.content.pm.IntentFilterVerificationInfo;
124import android.content.pm.KeySet;
125import android.content.pm.PackageCleanItem;
126import android.content.pm.PackageInfo;
127import android.content.pm.PackageInfoLite;
128import android.content.pm.PackageInstaller;
129import android.content.pm.PackageManager;
130import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
131import android.content.pm.PackageManagerInternal;
132import android.content.pm.PackageParser;
133import android.content.pm.PackageParser.ActivityIntentInfo;
134import android.content.pm.PackageParser.PackageLite;
135import android.content.pm.PackageParser.PackageParserException;
136import android.content.pm.PackageStats;
137import android.content.pm.PackageUserState;
138import android.content.pm.ParceledListSlice;
139import android.content.pm.PermissionGroupInfo;
140import android.content.pm.PermissionInfo;
141import android.content.pm.ProviderInfo;
142import android.content.pm.ResolveInfo;
143import android.content.pm.ServiceInfo;
144import android.content.pm.Signature;
145import android.content.pm.UserInfo;
146import android.content.pm.VerificationParams;
147import android.content.pm.VerifierDeviceIdentity;
148import android.content.pm.VerifierInfo;
149import android.content.res.Resources;
150import android.graphics.Bitmap;
151import android.hardware.display.DisplayManager;
152import android.net.Uri;
153import android.os.Binder;
154import android.os.Build;
155import android.os.Bundle;
156import android.os.Debug;
157import android.os.Environment;
158import android.os.Environment.UserEnvironment;
159import android.os.FileUtils;
160import android.os.Handler;
161import android.os.IBinder;
162import android.os.Looper;
163import android.os.Message;
164import android.os.Parcel;
165import android.os.ParcelFileDescriptor;
166import android.os.Process;
167import android.os.RemoteCallbackList;
168import android.os.RemoteException;
169import android.os.ResultReceiver;
170import android.os.SELinux;
171import android.os.ServiceManager;
172import android.os.SystemClock;
173import android.os.SystemProperties;
174import android.os.Trace;
175import android.os.UserHandle;
176import android.os.UserManager;
177import android.os.storage.IMountService;
178import android.os.storage.MountServiceInternal;
179import android.os.storage.StorageEventListener;
180import android.os.storage.StorageManager;
181import android.os.storage.VolumeInfo;
182import android.os.storage.VolumeRecord;
183import android.security.KeyStore;
184import android.security.SystemKeyStore;
185import android.system.ErrnoException;
186import android.system.Os;
187import android.system.StructStat;
188import android.text.TextUtils;
189import android.text.format.DateUtils;
190import android.util.ArrayMap;
191import android.util.ArraySet;
192import android.util.AtomicFile;
193import android.util.DisplayMetrics;
194import android.util.EventLog;
195import android.util.ExceptionUtils;
196import android.util.Log;
197import android.util.LogPrinter;
198import android.util.MathUtils;
199import android.util.PrintStreamPrinter;
200import android.util.Slog;
201import android.util.SparseArray;
202import android.util.SparseBooleanArray;
203import android.util.SparseIntArray;
204import android.util.Xml;
205import android.view.Display;
206
207import com.android.internal.R;
208import com.android.internal.annotations.GuardedBy;
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_ENCRYPTION_AWARE = 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        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2851        // reader
2852        synchronized (mPackages) {
2853            PackageParser.Package p = mPackages.get(packageName);
2854            if (DEBUG_PACKAGE_INFO)
2855                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2856            if (p != null) {
2857                return generatePackageInfo(p, flags, userId);
2858            }
2859            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2860                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2861            }
2862        }
2863        return null;
2864    }
2865
2866    @Override
2867    public String[] currentToCanonicalPackageNames(String[] names) {
2868        String[] out = new String[names.length];
2869        // reader
2870        synchronized (mPackages) {
2871            for (int i=names.length-1; i>=0; i--) {
2872                PackageSetting ps = mSettings.mPackages.get(names[i]);
2873                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2874            }
2875        }
2876        return out;
2877    }
2878
2879    @Override
2880    public String[] canonicalToCurrentPackageNames(String[] names) {
2881        String[] out = new String[names.length];
2882        // reader
2883        synchronized (mPackages) {
2884            for (int i=names.length-1; i>=0; i--) {
2885                String cur = mSettings.mRenamedPackages.get(names[i]);
2886                out[i] = cur != null ? cur : names[i];
2887            }
2888        }
2889        return out;
2890    }
2891
2892    @Override
2893    public int getPackageUid(String packageName, int userId) {
2894        return getPackageUidEtc(packageName, 0, userId);
2895    }
2896
2897    @Override
2898    public int getPackageUidEtc(String packageName, int flags, int userId) {
2899        if (!sUserManager.exists(userId)) return -1;
2900        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2901
2902        // reader
2903        synchronized (mPackages) {
2904            final PackageParser.Package p = mPackages.get(packageName);
2905            if (p != null) {
2906                return UserHandle.getUid(userId, p.applicationInfo.uid);
2907            }
2908            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2909                final PackageSetting ps = mSettings.mPackages.get(packageName);
2910                if (ps != null) {
2911                    return UserHandle.getUid(userId, ps.appId);
2912                }
2913            }
2914        }
2915
2916        return -1;
2917    }
2918
2919    @Override
2920    public int[] getPackageGids(String packageName, int userId) {
2921        return getPackageGidsEtc(packageName, 0, userId);
2922    }
2923
2924    @Override
2925    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2926        if (!sUserManager.exists(userId)) {
2927            return null;
2928        }
2929
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(
2952            BasePermission bp, int flags) {
2953        if (bp.perm != null) {
2954            return PackageParser.generatePermissionInfo(bp.perm, flags);
2955        }
2956        PermissionInfo pi = new PermissionInfo();
2957        pi.name = bp.name;
2958        pi.packageName = bp.sourcePackage;
2959        pi.nonLocalizedLabel = bp.name;
2960        pi.protectionLevel = bp.protectionLevel;
2961        return pi;
2962    }
2963
2964    @Override
2965    public PermissionInfo getPermissionInfo(String name, int flags) {
2966        // reader
2967        synchronized (mPackages) {
2968            final BasePermission p = mSettings.mPermissions.get(name);
2969            if (p != null) {
2970                return generatePermissionInfo(p, flags);
2971            }
2972            return null;
2973        }
2974    }
2975
2976    @Override
2977    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2978        // reader
2979        synchronized (mPackages) {
2980            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2981            for (BasePermission p : mSettings.mPermissions.values()) {
2982                if (group == null) {
2983                    if (p.perm == null || p.perm.info.group == null) {
2984                        out.add(generatePermissionInfo(p, flags));
2985                    }
2986                } else {
2987                    if (p.perm != null && group.equals(p.perm.info.group)) {
2988                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2989                    }
2990                }
2991            }
2992
2993            if (out.size() > 0) {
2994                return out;
2995            }
2996            return mPermissionGroups.containsKey(group) ? out : null;
2997        }
2998    }
2999
3000    @Override
3001    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3002        // reader
3003        synchronized (mPackages) {
3004            return PackageParser.generatePermissionGroupInfo(
3005                    mPermissionGroups.get(name), flags);
3006        }
3007    }
3008
3009    @Override
3010    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3011        // reader
3012        synchronized (mPackages) {
3013            final int N = mPermissionGroups.size();
3014            ArrayList<PermissionGroupInfo> out
3015                    = new ArrayList<PermissionGroupInfo>(N);
3016            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3017                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3018            }
3019            return out;
3020        }
3021    }
3022
3023    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3024            int userId) {
3025        if (!sUserManager.exists(userId)) return null;
3026        PackageSetting ps = mSettings.mPackages.get(packageName);
3027        if (ps != null) {
3028            if (ps.pkg == null) {
3029                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3030                        flags, userId);
3031                if (pInfo != null) {
3032                    return pInfo.applicationInfo;
3033                }
3034                return null;
3035            }
3036            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3037                    ps.readUserState(userId), userId);
3038        }
3039        return null;
3040    }
3041
3042    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3043            int userId) {
3044        if (!sUserManager.exists(userId)) return null;
3045        PackageSetting ps = mSettings.mPackages.get(packageName);
3046        if (ps != null) {
3047            PackageParser.Package pkg = ps.pkg;
3048            if (pkg == null) {
3049                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
3050                    return null;
3051                }
3052                // Only data remains, so we aren't worried about code paths
3053                pkg = new PackageParser.Package(packageName);
3054                pkg.applicationInfo.packageName = packageName;
3055                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3056                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3057                pkg.applicationInfo.uid = ps.appId;
3058                pkg.applicationInfo.initForUser(userId);
3059                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3060                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3061            }
3062            return generatePackageInfo(pkg, flags, userId);
3063        }
3064        return null;
3065    }
3066
3067    @Override
3068    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3069        if (!sUserManager.exists(userId)) return null;
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     * Augment the given flags depending on current user running state. This is
3185     * purposefully done before acquiring {@link #mPackages} lock.
3186     */
3187    private int augmentFlagsForUser(int flags, int userId, Object cookie) {
3188        if (cookie instanceof Intent) {
3189            // If intent claims to be triaged, then we're fine with default
3190            // matching behavior below
3191            final Intent intent = (Intent) cookie;
3192            if ((intent.getFlags() & Intent.FLAG_DEBUG_ENCRYPTION_TRIAGED) != 0) {
3193                flags |= PackageManager.MATCH_ENCRYPTION_DEFAULT;
3194            }
3195        }
3196
3197        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE_ONLY
3198                | PackageManager.MATCH_ENCRYPTION_AWARE_ONLY)) != 0) {
3199            // Caller expressed an opinion about what components they want to
3200            // see, so fall through and give them what they want
3201        } else {
3202            // Caller expressed no opinion, so match based on user state
3203            if (isUserKeyUnlocked(userId)) {
3204                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3205            } else {
3206                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_ONLY;
3207
3208                // If we have a system caller that hasn't done their homework to
3209                // decide they want this default behavior, yell at them
3210                if (DEBUG_ENCRYPTION_AWARE && (Binder.getCallingUid() == Process.SYSTEM_UID)
3211                        && ((flags & PackageManager.MATCH_ENCRYPTION_DEFAULT) == 0)) {
3212                    Log.v(TAG, "Caller hasn't been triaged for FBE; they asked about " + cookie,
3213                            new Throwable());
3214                }
3215            }
3216        }
3217        return flags;
3218    }
3219
3220    @Override
3221    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3222        if (!sUserManager.exists(userId)) return null;
3223        flags = augmentFlagsForUser(flags, userId, component);
3224        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3225        synchronized (mPackages) {
3226            PackageParser.Activity a = mActivities.mActivities.get(component);
3227
3228            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3229            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3230                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3231                if (ps == null) return null;
3232                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3233                        userId);
3234            }
3235            if (mResolveComponentName.equals(component)) {
3236                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3237                        new PackageUserState(), userId);
3238            }
3239        }
3240        return null;
3241    }
3242
3243    @Override
3244    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3245            String resolvedType) {
3246        synchronized (mPackages) {
3247            if (component.equals(mResolveComponentName)) {
3248                // The resolver supports EVERYTHING!
3249                return true;
3250            }
3251            PackageParser.Activity a = mActivities.mActivities.get(component);
3252            if (a == null) {
3253                return false;
3254            }
3255            for (int i=0; i<a.intents.size(); i++) {
3256                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3257                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3258                    return true;
3259                }
3260            }
3261            return false;
3262        }
3263    }
3264
3265    @Override
3266    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3267        if (!sUserManager.exists(userId)) return null;
3268        flags = augmentFlagsForUser(flags, userId, component);
3269        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3270        synchronized (mPackages) {
3271            PackageParser.Activity a = mReceivers.mActivities.get(component);
3272            if (DEBUG_PACKAGE_INFO) Log.v(
3273                TAG, "getReceiverInfo " + component + ": " + a);
3274            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3275                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3276                if (ps == null) return null;
3277                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3278                        userId);
3279            }
3280        }
3281        return null;
3282    }
3283
3284    @Override
3285    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3286        if (!sUserManager.exists(userId)) return null;
3287        flags = augmentFlagsForUser(flags, userId, component);
3288        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3289        synchronized (mPackages) {
3290            PackageParser.Service s = mServices.mServices.get(component);
3291            if (DEBUG_PACKAGE_INFO) Log.v(
3292                TAG, "getServiceInfo " + component + ": " + s);
3293            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3294                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3295                if (ps == null) return null;
3296                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3297                        userId);
3298            }
3299        }
3300        return null;
3301    }
3302
3303    @Override
3304    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3305        if (!sUserManager.exists(userId)) return null;
3306        flags = augmentFlagsForUser(flags, userId, component);
3307        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3308        synchronized (mPackages) {
3309            PackageParser.Provider p = mProviders.mProviders.get(component);
3310            if (DEBUG_PACKAGE_INFO) Log.v(
3311                TAG, "getProviderInfo " + component + ": " + p);
3312            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3313                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3314                if (ps == null) return null;
3315                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3316                        userId);
3317            }
3318        }
3319        return null;
3320    }
3321
3322    @Override
3323    public String[] getSystemSharedLibraryNames() {
3324        Set<String> libSet;
3325        synchronized (mPackages) {
3326            libSet = mSharedLibraries.keySet();
3327            int size = libSet.size();
3328            if (size > 0) {
3329                String[] libs = new String[size];
3330                libSet.toArray(libs);
3331                return libs;
3332            }
3333        }
3334        return null;
3335    }
3336
3337    /**
3338     * @hide
3339     */
3340    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3341        synchronized (mPackages) {
3342            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3343            if (lib != null && lib.apk != null) {
3344                return mPackages.get(lib.apk);
3345            }
3346        }
3347        return null;
3348    }
3349
3350    @Override
3351    public FeatureInfo[] getSystemAvailableFeatures() {
3352        Collection<FeatureInfo> featSet;
3353        synchronized (mPackages) {
3354            featSet = mAvailableFeatures.values();
3355            int size = featSet.size();
3356            if (size > 0) {
3357                FeatureInfo[] features = new FeatureInfo[size+1];
3358                featSet.toArray(features);
3359                FeatureInfo fi = new FeatureInfo();
3360                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3361                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3362                features[size] = fi;
3363                return features;
3364            }
3365        }
3366        return null;
3367    }
3368
3369    @Override
3370    public boolean hasSystemFeature(String name) {
3371        synchronized (mPackages) {
3372            return mAvailableFeatures.containsKey(name);
3373        }
3374    }
3375
3376    @Override
3377    public int checkPermission(String permName, String pkgName, int userId) {
3378        if (!sUserManager.exists(userId)) {
3379            return PackageManager.PERMISSION_DENIED;
3380        }
3381
3382        synchronized (mPackages) {
3383            final PackageParser.Package p = mPackages.get(pkgName);
3384            if (p != null && p.mExtras != null) {
3385                final PackageSetting ps = (PackageSetting) p.mExtras;
3386                final PermissionsState permissionsState = ps.getPermissionsState();
3387                if (permissionsState.hasPermission(permName, userId)) {
3388                    return PackageManager.PERMISSION_GRANTED;
3389                }
3390                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3391                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3392                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3393                    return PackageManager.PERMISSION_GRANTED;
3394                }
3395            }
3396        }
3397
3398        return PackageManager.PERMISSION_DENIED;
3399    }
3400
3401    @Override
3402    public int checkUidPermission(String permName, int uid) {
3403        final int userId = UserHandle.getUserId(uid);
3404
3405        if (!sUserManager.exists(userId)) {
3406            return PackageManager.PERMISSION_DENIED;
3407        }
3408
3409        synchronized (mPackages) {
3410            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3411            if (obj != null) {
3412                final SettingBase ps = (SettingBase) obj;
3413                final PermissionsState permissionsState = ps.getPermissionsState();
3414                if (permissionsState.hasPermission(permName, userId)) {
3415                    return PackageManager.PERMISSION_GRANTED;
3416                }
3417                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3418                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3419                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3420                    return PackageManager.PERMISSION_GRANTED;
3421                }
3422            } else {
3423                ArraySet<String> perms = mSystemPermissions.get(uid);
3424                if (perms != null) {
3425                    if (perms.contains(permName)) {
3426                        return PackageManager.PERMISSION_GRANTED;
3427                    }
3428                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3429                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3430                        return PackageManager.PERMISSION_GRANTED;
3431                    }
3432                }
3433            }
3434        }
3435
3436        return PackageManager.PERMISSION_DENIED;
3437    }
3438
3439    @Override
3440    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3441        if (UserHandle.getCallingUserId() != userId) {
3442            mContext.enforceCallingPermission(
3443                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3444                    "isPermissionRevokedByPolicy for user " + userId);
3445        }
3446
3447        if (checkPermission(permission, packageName, userId)
3448                == PackageManager.PERMISSION_GRANTED) {
3449            return false;
3450        }
3451
3452        final long identity = Binder.clearCallingIdentity();
3453        try {
3454            final int flags = getPermissionFlags(permission, packageName, userId);
3455            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3456        } finally {
3457            Binder.restoreCallingIdentity(identity);
3458        }
3459    }
3460
3461    @Override
3462    public String getPermissionControllerPackageName() {
3463        synchronized (mPackages) {
3464            return mRequiredInstallerPackage;
3465        }
3466    }
3467
3468    /**
3469     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3470     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3471     * @param checkShell TODO(yamasani):
3472     * @param message the message to log on security exception
3473     */
3474    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3475            boolean checkShell, String message) {
3476        if (userId < 0) {
3477            throw new IllegalArgumentException("Invalid userId " + userId);
3478        }
3479        if (checkShell) {
3480            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3481        }
3482        if (userId == UserHandle.getUserId(callingUid)) return;
3483        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3484            if (requireFullPermission) {
3485                mContext.enforceCallingOrSelfPermission(
3486                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3487            } else {
3488                try {
3489                    mContext.enforceCallingOrSelfPermission(
3490                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3491                } catch (SecurityException se) {
3492                    mContext.enforceCallingOrSelfPermission(
3493                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3494                }
3495            }
3496        }
3497    }
3498
3499    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3500        if (callingUid == Process.SHELL_UID) {
3501            if (userHandle >= 0
3502                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3503                throw new SecurityException("Shell does not have permission to access user "
3504                        + userHandle);
3505            } else if (userHandle < 0) {
3506                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3507                        + Debug.getCallers(3));
3508            }
3509        }
3510    }
3511
3512    private BasePermission findPermissionTreeLP(String permName) {
3513        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3514            if (permName.startsWith(bp.name) &&
3515                    permName.length() > bp.name.length() &&
3516                    permName.charAt(bp.name.length()) == '.') {
3517                return bp;
3518            }
3519        }
3520        return null;
3521    }
3522
3523    private BasePermission checkPermissionTreeLP(String permName) {
3524        if (permName != null) {
3525            BasePermission bp = findPermissionTreeLP(permName);
3526            if (bp != null) {
3527                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3528                    return bp;
3529                }
3530                throw new SecurityException("Calling uid "
3531                        + Binder.getCallingUid()
3532                        + " is not allowed to add to permission tree "
3533                        + bp.name + " owned by uid " + bp.uid);
3534            }
3535        }
3536        throw new SecurityException("No permission tree found for " + permName);
3537    }
3538
3539    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3540        if (s1 == null) {
3541            return s2 == null;
3542        }
3543        if (s2 == null) {
3544            return false;
3545        }
3546        if (s1.getClass() != s2.getClass()) {
3547            return false;
3548        }
3549        return s1.equals(s2);
3550    }
3551
3552    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3553        if (pi1.icon != pi2.icon) return false;
3554        if (pi1.logo != pi2.logo) return false;
3555        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3556        if (!compareStrings(pi1.name, pi2.name)) return false;
3557        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3558        // We'll take care of setting this one.
3559        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3560        // These are not currently stored in settings.
3561        //if (!compareStrings(pi1.group, pi2.group)) return false;
3562        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3563        //if (pi1.labelRes != pi2.labelRes) return false;
3564        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3565        return true;
3566    }
3567
3568    int permissionInfoFootprint(PermissionInfo info) {
3569        int size = info.name.length();
3570        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3571        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3572        return size;
3573    }
3574
3575    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3576        int size = 0;
3577        for (BasePermission perm : mSettings.mPermissions.values()) {
3578            if (perm.uid == tree.uid) {
3579                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3580            }
3581        }
3582        return size;
3583    }
3584
3585    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3586        // We calculate the max size of permissions defined by this uid and throw
3587        // if that plus the size of 'info' would exceed our stated maximum.
3588        if (tree.uid != Process.SYSTEM_UID) {
3589            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3590            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3591                throw new SecurityException("Permission tree size cap exceeded");
3592            }
3593        }
3594    }
3595
3596    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3597        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3598            throw new SecurityException("Label must be specified in permission");
3599        }
3600        BasePermission tree = checkPermissionTreeLP(info.name);
3601        BasePermission bp = mSettings.mPermissions.get(info.name);
3602        boolean added = bp == null;
3603        boolean changed = true;
3604        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3605        if (added) {
3606            enforcePermissionCapLocked(info, tree);
3607            bp = new BasePermission(info.name, tree.sourcePackage,
3608                    BasePermission.TYPE_DYNAMIC);
3609        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3610            throw new SecurityException(
3611                    "Not allowed to modify non-dynamic permission "
3612                    + info.name);
3613        } else {
3614            if (bp.protectionLevel == fixedLevel
3615                    && bp.perm.owner.equals(tree.perm.owner)
3616                    && bp.uid == tree.uid
3617                    && comparePermissionInfos(bp.perm.info, info)) {
3618                changed = false;
3619            }
3620        }
3621        bp.protectionLevel = fixedLevel;
3622        info = new PermissionInfo(info);
3623        info.protectionLevel = fixedLevel;
3624        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3625        bp.perm.info.packageName = tree.perm.info.packageName;
3626        bp.uid = tree.uid;
3627        if (added) {
3628            mSettings.mPermissions.put(info.name, bp);
3629        }
3630        if (changed) {
3631            if (!async) {
3632                mSettings.writeLPr();
3633            } else {
3634                scheduleWriteSettingsLocked();
3635            }
3636        }
3637        return added;
3638    }
3639
3640    @Override
3641    public boolean addPermission(PermissionInfo info) {
3642        synchronized (mPackages) {
3643            return addPermissionLocked(info, false);
3644        }
3645    }
3646
3647    @Override
3648    public boolean addPermissionAsync(PermissionInfo info) {
3649        synchronized (mPackages) {
3650            return addPermissionLocked(info, true);
3651        }
3652    }
3653
3654    @Override
3655    public void removePermission(String name) {
3656        synchronized (mPackages) {
3657            checkPermissionTreeLP(name);
3658            BasePermission bp = mSettings.mPermissions.get(name);
3659            if (bp != null) {
3660                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3661                    throw new SecurityException(
3662                            "Not allowed to modify non-dynamic permission "
3663                            + name);
3664                }
3665                mSettings.mPermissions.remove(name);
3666                mSettings.writeLPr();
3667            }
3668        }
3669    }
3670
3671    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3672            BasePermission bp) {
3673        int index = pkg.requestedPermissions.indexOf(bp.name);
3674        if (index == -1) {
3675            throw new SecurityException("Package " + pkg.packageName
3676                    + " has not requested permission " + bp.name);
3677        }
3678        if (!bp.isRuntime() && !bp.isDevelopment()) {
3679            throw new SecurityException("Permission " + bp.name
3680                    + " is not a changeable permission type");
3681        }
3682    }
3683
3684    @Override
3685    public void grantRuntimePermission(String packageName, String name, final int userId) {
3686        if (!sUserManager.exists(userId)) {
3687            Log.e(TAG, "No such user:" + userId);
3688            return;
3689        }
3690
3691        mContext.enforceCallingOrSelfPermission(
3692                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3693                "grantRuntimePermission");
3694
3695        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3696                "grantRuntimePermission");
3697
3698        final int uid;
3699        final SettingBase sb;
3700
3701        synchronized (mPackages) {
3702            final PackageParser.Package pkg = mPackages.get(packageName);
3703            if (pkg == null) {
3704                throw new IllegalArgumentException("Unknown package: " + packageName);
3705            }
3706
3707            final BasePermission bp = mSettings.mPermissions.get(name);
3708            if (bp == null) {
3709                throw new IllegalArgumentException("Unknown permission: " + name);
3710            }
3711
3712            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3713
3714            // If a permission review is required for legacy apps we represent
3715            // their permissions as always granted runtime ones since we need
3716            // to keep the review required permission flag per user while an
3717            // install permission's state is shared across all users.
3718            if (Build.PERMISSIONS_REVIEW_REQUIRED
3719                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3720                    && bp.isRuntime()) {
3721                return;
3722            }
3723
3724            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3725            sb = (SettingBase) pkg.mExtras;
3726            if (sb == null) {
3727                throw new IllegalArgumentException("Unknown package: " + packageName);
3728            }
3729
3730            final PermissionsState permissionsState = sb.getPermissionsState();
3731
3732            final int flags = permissionsState.getPermissionFlags(name, userId);
3733            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3734                throw new SecurityException("Cannot grant system fixed permission: "
3735                        + name + " for package: " + packageName);
3736            }
3737
3738            if (bp.isDevelopment()) {
3739                // Development permissions must be handled specially, since they are not
3740                // normal runtime permissions.  For now they apply to all users.
3741                if (permissionsState.grantInstallPermission(bp) !=
3742                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3743                    scheduleWriteSettingsLocked();
3744                }
3745                return;
3746            }
3747
3748            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3749                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3750                return;
3751            }
3752
3753            final int result = permissionsState.grantRuntimePermission(bp, userId);
3754            switch (result) {
3755                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3756                    return;
3757                }
3758
3759                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3760                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3761                    mHandler.post(new Runnable() {
3762                        @Override
3763                        public void run() {
3764                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3765                        }
3766                    });
3767                }
3768                break;
3769            }
3770
3771            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3772
3773            // Not critical if that is lost - app has to request again.
3774            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3775        }
3776
3777        // Only need to do this if user is initialized. Otherwise it's a new user
3778        // and there are no processes running as the user yet and there's no need
3779        // to make an expensive call to remount processes for the changed permissions.
3780        if (READ_EXTERNAL_STORAGE.equals(name)
3781                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3782            final long token = Binder.clearCallingIdentity();
3783            try {
3784                if (sUserManager.isInitialized(userId)) {
3785                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3786                            MountServiceInternal.class);
3787                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3788                }
3789            } finally {
3790                Binder.restoreCallingIdentity(token);
3791            }
3792        }
3793    }
3794
3795    @Override
3796    public void revokeRuntimePermission(String packageName, String name, int userId) {
3797        if (!sUserManager.exists(userId)) {
3798            Log.e(TAG, "No such user:" + userId);
3799            return;
3800        }
3801
3802        mContext.enforceCallingOrSelfPermission(
3803                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3804                "revokeRuntimePermission");
3805
3806        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3807                "revokeRuntimePermission");
3808
3809        final int appId;
3810
3811        synchronized (mPackages) {
3812            final PackageParser.Package pkg = mPackages.get(packageName);
3813            if (pkg == null) {
3814                throw new IllegalArgumentException("Unknown package: " + packageName);
3815            }
3816
3817            final BasePermission bp = mSettings.mPermissions.get(name);
3818            if (bp == null) {
3819                throw new IllegalArgumentException("Unknown permission: " + name);
3820            }
3821
3822            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3823
3824            // If a permission review is required for legacy apps we represent
3825            // their permissions as always granted runtime ones since we need
3826            // to keep the review required permission flag per user while an
3827            // install permission's state is shared across all users.
3828            if (Build.PERMISSIONS_REVIEW_REQUIRED
3829                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3830                    && bp.isRuntime()) {
3831                return;
3832            }
3833
3834            SettingBase sb = (SettingBase) pkg.mExtras;
3835            if (sb == null) {
3836                throw new IllegalArgumentException("Unknown package: " + packageName);
3837            }
3838
3839            final PermissionsState permissionsState = sb.getPermissionsState();
3840
3841            final int flags = permissionsState.getPermissionFlags(name, userId);
3842            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3843                throw new SecurityException("Cannot revoke system fixed permission: "
3844                        + name + " for package: " + packageName);
3845            }
3846
3847            if (bp.isDevelopment()) {
3848                // Development permissions must be handled specially, since they are not
3849                // normal runtime permissions.  For now they apply to all users.
3850                if (permissionsState.revokeInstallPermission(bp) !=
3851                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3852                    scheduleWriteSettingsLocked();
3853                }
3854                return;
3855            }
3856
3857            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3858                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3859                return;
3860            }
3861
3862            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3863
3864            // Critical, after this call app should never have the permission.
3865            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3866
3867            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3868        }
3869
3870        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3871    }
3872
3873    @Override
3874    public void resetRuntimePermissions() {
3875        mContext.enforceCallingOrSelfPermission(
3876                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3877                "revokeRuntimePermission");
3878
3879        int callingUid = Binder.getCallingUid();
3880        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3881            mContext.enforceCallingOrSelfPermission(
3882                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3883                    "resetRuntimePermissions");
3884        }
3885
3886        synchronized (mPackages) {
3887            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3888            for (int userId : UserManagerService.getInstance().getUserIds()) {
3889                final int packageCount = mPackages.size();
3890                for (int i = 0; i < packageCount; i++) {
3891                    PackageParser.Package pkg = mPackages.valueAt(i);
3892                    if (!(pkg.mExtras instanceof PackageSetting)) {
3893                        continue;
3894                    }
3895                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3896                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3897                }
3898            }
3899        }
3900    }
3901
3902    @Override
3903    public int getPermissionFlags(String name, String packageName, int userId) {
3904        if (!sUserManager.exists(userId)) {
3905            return 0;
3906        }
3907
3908        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3909
3910        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3911                "getPermissionFlags");
3912
3913        synchronized (mPackages) {
3914            final PackageParser.Package pkg = mPackages.get(packageName);
3915            if (pkg == null) {
3916                throw new IllegalArgumentException("Unknown package: " + packageName);
3917            }
3918
3919            final BasePermission bp = mSettings.mPermissions.get(name);
3920            if (bp == null) {
3921                throw new IllegalArgumentException("Unknown permission: " + name);
3922            }
3923
3924            SettingBase sb = (SettingBase) pkg.mExtras;
3925            if (sb == null) {
3926                throw new IllegalArgumentException("Unknown package: " + packageName);
3927            }
3928
3929            PermissionsState permissionsState = sb.getPermissionsState();
3930            return permissionsState.getPermissionFlags(name, userId);
3931        }
3932    }
3933
3934    @Override
3935    public void updatePermissionFlags(String name, String packageName, int flagMask,
3936            int flagValues, int userId) {
3937        if (!sUserManager.exists(userId)) {
3938            return;
3939        }
3940
3941        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3942
3943        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3944                "updatePermissionFlags");
3945
3946        // Only the system can change these flags and nothing else.
3947        if (getCallingUid() != Process.SYSTEM_UID) {
3948            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3949            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3950            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3951            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3952            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3953        }
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
3973            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3974
3975            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3976                // Install and runtime permissions are stored in different places,
3977                // so figure out what permission changed and persist the change.
3978                if (permissionsState.getInstallPermissionState(name) != null) {
3979                    scheduleWriteSettingsLocked();
3980                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3981                        || hadState) {
3982                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3983                }
3984            }
3985        }
3986    }
3987
3988    /**
3989     * Update the permission flags for all packages and runtime permissions of a user in order
3990     * to allow device or profile owner to remove POLICY_FIXED.
3991     */
3992    @Override
3993    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3994        if (!sUserManager.exists(userId)) {
3995            return;
3996        }
3997
3998        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3999
4000        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
4001                "updatePermissionFlagsForAllApps");
4002
4003        // Only the system can change system fixed flags.
4004        if (getCallingUid() != Process.SYSTEM_UID) {
4005            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4006            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4007        }
4008
4009        synchronized (mPackages) {
4010            boolean changed = false;
4011            final int packageCount = mPackages.size();
4012            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4013                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4014                SettingBase sb = (SettingBase) pkg.mExtras;
4015                if (sb == null) {
4016                    continue;
4017                }
4018                PermissionsState permissionsState = sb.getPermissionsState();
4019                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4020                        userId, flagMask, flagValues);
4021            }
4022            if (changed) {
4023                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4024            }
4025        }
4026    }
4027
4028    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4029        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4030                != PackageManager.PERMISSION_GRANTED
4031            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4032                != PackageManager.PERMISSION_GRANTED) {
4033            throw new SecurityException(message + " requires "
4034                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4035                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4036        }
4037    }
4038
4039    @Override
4040    public boolean shouldShowRequestPermissionRationale(String permissionName,
4041            String packageName, int userId) {
4042        if (UserHandle.getCallingUserId() != userId) {
4043            mContext.enforceCallingPermission(
4044                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4045                    "canShowRequestPermissionRationale for user " + userId);
4046        }
4047
4048        final int uid = getPackageUid(packageName, userId);
4049        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4050            return false;
4051        }
4052
4053        if (checkPermission(permissionName, packageName, userId)
4054                == PackageManager.PERMISSION_GRANTED) {
4055            return false;
4056        }
4057
4058        final int flags;
4059
4060        final long identity = Binder.clearCallingIdentity();
4061        try {
4062            flags = getPermissionFlags(permissionName,
4063                    packageName, userId);
4064        } finally {
4065            Binder.restoreCallingIdentity(identity);
4066        }
4067
4068        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4069                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4070                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4071
4072        if ((flags & fixedFlags) != 0) {
4073            return false;
4074        }
4075
4076        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4077    }
4078
4079    @Override
4080    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4081        mContext.enforceCallingOrSelfPermission(
4082                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4083                "addOnPermissionsChangeListener");
4084
4085        synchronized (mPackages) {
4086            mOnPermissionChangeListeners.addListenerLocked(listener);
4087        }
4088    }
4089
4090    @Override
4091    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4092        synchronized (mPackages) {
4093            mOnPermissionChangeListeners.removeListenerLocked(listener);
4094        }
4095    }
4096
4097    @Override
4098    public boolean isProtectedBroadcast(String actionName) {
4099        synchronized (mPackages) {
4100            if (mProtectedBroadcasts.contains(actionName)) {
4101                return true;
4102            } else if (actionName != null) {
4103                // TODO: remove these terrible hacks
4104                if (actionName.startsWith("android.net.netmon.lingerExpired")
4105                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4106                    return true;
4107                }
4108            }
4109        }
4110        return false;
4111    }
4112
4113    @Override
4114    public int checkSignatures(String pkg1, String pkg2) {
4115        synchronized (mPackages) {
4116            final PackageParser.Package p1 = mPackages.get(pkg1);
4117            final PackageParser.Package p2 = mPackages.get(pkg2);
4118            if (p1 == null || p1.mExtras == null
4119                    || p2 == null || p2.mExtras == null) {
4120                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4121            }
4122            return compareSignatures(p1.mSignatures, p2.mSignatures);
4123        }
4124    }
4125
4126    @Override
4127    public int checkUidSignatures(int uid1, int uid2) {
4128        // Map to base uids.
4129        uid1 = UserHandle.getAppId(uid1);
4130        uid2 = UserHandle.getAppId(uid2);
4131        // reader
4132        synchronized (mPackages) {
4133            Signature[] s1;
4134            Signature[] s2;
4135            Object obj = mSettings.getUserIdLPr(uid1);
4136            if (obj != null) {
4137                if (obj instanceof SharedUserSetting) {
4138                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4139                } else if (obj instanceof PackageSetting) {
4140                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4141                } else {
4142                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4143                }
4144            } else {
4145                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4146            }
4147            obj = mSettings.getUserIdLPr(uid2);
4148            if (obj != null) {
4149                if (obj instanceof SharedUserSetting) {
4150                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4151                } else if (obj instanceof PackageSetting) {
4152                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4153                } else {
4154                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4155                }
4156            } else {
4157                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4158            }
4159            return compareSignatures(s1, s2);
4160        }
4161    }
4162
4163    private void killUid(int appId, int userId, String reason) {
4164        final long identity = Binder.clearCallingIdentity();
4165        try {
4166            IActivityManager am = ActivityManagerNative.getDefault();
4167            if (am != null) {
4168                try {
4169                    am.killUid(appId, userId, reason);
4170                } catch (RemoteException e) {
4171                    /* ignore - same process */
4172                }
4173            }
4174        } finally {
4175            Binder.restoreCallingIdentity(identity);
4176        }
4177    }
4178
4179    /**
4180     * Compares two sets of signatures. Returns:
4181     * <br />
4182     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4183     * <br />
4184     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4185     * <br />
4186     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4187     * <br />
4188     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4189     * <br />
4190     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4191     */
4192    static int compareSignatures(Signature[] s1, Signature[] s2) {
4193        if (s1 == null) {
4194            return s2 == null
4195                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4196                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4197        }
4198
4199        if (s2 == null) {
4200            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4201        }
4202
4203        if (s1.length != s2.length) {
4204            return PackageManager.SIGNATURE_NO_MATCH;
4205        }
4206
4207        // Since both signature sets are of size 1, we can compare without HashSets.
4208        if (s1.length == 1) {
4209            return s1[0].equals(s2[0]) ?
4210                    PackageManager.SIGNATURE_MATCH :
4211                    PackageManager.SIGNATURE_NO_MATCH;
4212        }
4213
4214        ArraySet<Signature> set1 = new ArraySet<Signature>();
4215        for (Signature sig : s1) {
4216            set1.add(sig);
4217        }
4218        ArraySet<Signature> set2 = new ArraySet<Signature>();
4219        for (Signature sig : s2) {
4220            set2.add(sig);
4221        }
4222        // Make sure s2 contains all signatures in s1.
4223        if (set1.equals(set2)) {
4224            return PackageManager.SIGNATURE_MATCH;
4225        }
4226        return PackageManager.SIGNATURE_NO_MATCH;
4227    }
4228
4229    /**
4230     * If the database version for this type of package (internal storage or
4231     * external storage) is less than the version where package signatures
4232     * were updated, return true.
4233     */
4234    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4235        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4236        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4237    }
4238
4239    /**
4240     * Used for backward compatibility to make sure any packages with
4241     * certificate chains get upgraded to the new style. {@code existingSigs}
4242     * will be in the old format (since they were stored on disk from before the
4243     * system upgrade) and {@code scannedSigs} will be in the newer format.
4244     */
4245    private int compareSignaturesCompat(PackageSignatures existingSigs,
4246            PackageParser.Package scannedPkg) {
4247        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4248            return PackageManager.SIGNATURE_NO_MATCH;
4249        }
4250
4251        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4252        for (Signature sig : existingSigs.mSignatures) {
4253            existingSet.add(sig);
4254        }
4255        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4256        for (Signature sig : scannedPkg.mSignatures) {
4257            try {
4258                Signature[] chainSignatures = sig.getChainSignatures();
4259                for (Signature chainSig : chainSignatures) {
4260                    scannedCompatSet.add(chainSig);
4261                }
4262            } catch (CertificateEncodingException e) {
4263                scannedCompatSet.add(sig);
4264            }
4265        }
4266        /*
4267         * Make sure the expanded scanned set contains all signatures in the
4268         * existing one.
4269         */
4270        if (scannedCompatSet.equals(existingSet)) {
4271            // Migrate the old signatures to the new scheme.
4272            existingSigs.assignSignatures(scannedPkg.mSignatures);
4273            // The new KeySets will be re-added later in the scanning process.
4274            synchronized (mPackages) {
4275                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4276            }
4277            return PackageManager.SIGNATURE_MATCH;
4278        }
4279        return PackageManager.SIGNATURE_NO_MATCH;
4280    }
4281
4282    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4283        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4284        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4285    }
4286
4287    private int compareSignaturesRecover(PackageSignatures existingSigs,
4288            PackageParser.Package scannedPkg) {
4289        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4290            return PackageManager.SIGNATURE_NO_MATCH;
4291        }
4292
4293        String msg = null;
4294        try {
4295            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4296                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4297                        + scannedPkg.packageName);
4298                return PackageManager.SIGNATURE_MATCH;
4299            }
4300        } catch (CertificateException e) {
4301            msg = e.getMessage();
4302        }
4303
4304        logCriticalInfo(Log.INFO,
4305                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4306        return PackageManager.SIGNATURE_NO_MATCH;
4307    }
4308
4309    @Override
4310    public String[] getPackagesForUid(int uid) {
4311        uid = UserHandle.getAppId(uid);
4312        // reader
4313        synchronized (mPackages) {
4314            Object obj = mSettings.getUserIdLPr(uid);
4315            if (obj instanceof SharedUserSetting) {
4316                final SharedUserSetting sus = (SharedUserSetting) obj;
4317                final int N = sus.packages.size();
4318                final String[] res = new String[N];
4319                final Iterator<PackageSetting> it = sus.packages.iterator();
4320                int i = 0;
4321                while (it.hasNext()) {
4322                    res[i++] = it.next().name;
4323                }
4324                return res;
4325            } else if (obj instanceof PackageSetting) {
4326                final PackageSetting ps = (PackageSetting) obj;
4327                return new String[] { ps.name };
4328            }
4329        }
4330        return null;
4331    }
4332
4333    @Override
4334    public String getNameForUid(int uid) {
4335        // reader
4336        synchronized (mPackages) {
4337            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4338            if (obj instanceof SharedUserSetting) {
4339                final SharedUserSetting sus = (SharedUserSetting) obj;
4340                return sus.name + ":" + sus.userId;
4341            } else if (obj instanceof PackageSetting) {
4342                final PackageSetting ps = (PackageSetting) obj;
4343                return ps.name;
4344            }
4345        }
4346        return null;
4347    }
4348
4349    @Override
4350    public int getUidForSharedUser(String sharedUserName) {
4351        if(sharedUserName == null) {
4352            return -1;
4353        }
4354        // reader
4355        synchronized (mPackages) {
4356            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4357            if (suid == null) {
4358                return -1;
4359            }
4360            return suid.userId;
4361        }
4362    }
4363
4364    @Override
4365    public int getFlagsForUid(int uid) {
4366        synchronized (mPackages) {
4367            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4368            if (obj instanceof SharedUserSetting) {
4369                final SharedUserSetting sus = (SharedUserSetting) obj;
4370                return sus.pkgFlags;
4371            } else if (obj instanceof PackageSetting) {
4372                final PackageSetting ps = (PackageSetting) obj;
4373                return ps.pkgFlags;
4374            }
4375        }
4376        return 0;
4377    }
4378
4379    @Override
4380    public int getPrivateFlagsForUid(int uid) {
4381        synchronized (mPackages) {
4382            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4383            if (obj instanceof SharedUserSetting) {
4384                final SharedUserSetting sus = (SharedUserSetting) obj;
4385                return sus.pkgPrivateFlags;
4386            } else if (obj instanceof PackageSetting) {
4387                final PackageSetting ps = (PackageSetting) obj;
4388                return ps.pkgPrivateFlags;
4389            }
4390        }
4391        return 0;
4392    }
4393
4394    @Override
4395    public boolean isUidPrivileged(int uid) {
4396        uid = UserHandle.getAppId(uid);
4397        // reader
4398        synchronized (mPackages) {
4399            Object obj = mSettings.getUserIdLPr(uid);
4400            if (obj instanceof SharedUserSetting) {
4401                final SharedUserSetting sus = (SharedUserSetting) obj;
4402                final Iterator<PackageSetting> it = sus.packages.iterator();
4403                while (it.hasNext()) {
4404                    if (it.next().isPrivileged()) {
4405                        return true;
4406                    }
4407                }
4408            } else if (obj instanceof PackageSetting) {
4409                final PackageSetting ps = (PackageSetting) obj;
4410                return ps.isPrivileged();
4411            }
4412        }
4413        return false;
4414    }
4415
4416    @Override
4417    public String[] getAppOpPermissionPackages(String permissionName) {
4418        synchronized (mPackages) {
4419            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4420            if (pkgs == null) {
4421                return null;
4422            }
4423            return pkgs.toArray(new String[pkgs.size()]);
4424        }
4425    }
4426
4427    @Override
4428    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4429            int flags, int userId) {
4430        if (!sUserManager.exists(userId)) return null;
4431        flags = augmentFlagsForUser(flags, userId, intent);
4432        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4433        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4434        final ResolveInfo bestChoice =
4435                chooseBestActivity(intent, resolvedType, flags, query, userId);
4436
4437        if (isEphemeralAllowed(intent, query, userId)) {
4438            final EphemeralResolveInfo ai =
4439                    getEphemeralResolveInfo(intent, resolvedType, userId);
4440            if (ai != null) {
4441                if (DEBUG_EPHEMERAL) {
4442                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4443                }
4444                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4445                bestChoice.ephemeralResolveInfo = ai;
4446            }
4447        }
4448        return bestChoice;
4449    }
4450
4451    @Override
4452    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4453            IntentFilter filter, int match, ComponentName activity) {
4454        final int userId = UserHandle.getCallingUserId();
4455        if (DEBUG_PREFERRED) {
4456            Log.v(TAG, "setLastChosenActivity intent=" + intent
4457                + " resolvedType=" + resolvedType
4458                + " flags=" + flags
4459                + " filter=" + filter
4460                + " match=" + match
4461                + " activity=" + activity);
4462            filter.dump(new PrintStreamPrinter(System.out), "    ");
4463        }
4464        intent.setComponent(null);
4465        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4466        // Find any earlier preferred or last chosen entries and nuke them
4467        findPreferredActivity(intent, resolvedType,
4468                flags, query, 0, false, true, false, userId);
4469        // Add the new activity as the last chosen for this filter
4470        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4471                "Setting last chosen");
4472    }
4473
4474    @Override
4475    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4476        final int userId = UserHandle.getCallingUserId();
4477        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4478        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4479        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4480                false, false, false, userId);
4481    }
4482
4483
4484    private boolean isEphemeralAllowed(
4485            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4486        // Short circuit and return early if possible.
4487        final int callingUser = UserHandle.getCallingUserId();
4488        if (callingUser != UserHandle.USER_SYSTEM) {
4489            return false;
4490        }
4491        if (mEphemeralResolverConnection == null) {
4492            return false;
4493        }
4494        if (intent.getComponent() != null) {
4495            return false;
4496        }
4497        if (intent.getPackage() != null) {
4498            return false;
4499        }
4500        final boolean isWebUri = hasWebURI(intent);
4501        if (!isWebUri) {
4502            return false;
4503        }
4504        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4505        synchronized (mPackages) {
4506            final int count = resolvedActivites.size();
4507            for (int n = 0; n < count; n++) {
4508                ResolveInfo info = resolvedActivites.get(n);
4509                String packageName = info.activityInfo.packageName;
4510                PackageSetting ps = mSettings.mPackages.get(packageName);
4511                if (ps != null) {
4512                    // Try to get the status from User settings first
4513                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4514                    int status = (int) (packedStatus >> 32);
4515                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4516                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4517                        if (DEBUG_EPHEMERAL) {
4518                            Slog.v(TAG, "DENY ephemeral apps;"
4519                                + " pkg: " + packageName + ", status: " + status);
4520                        }
4521                        return false;
4522                    }
4523                }
4524            }
4525        }
4526        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4527        return true;
4528    }
4529
4530    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4531            int userId) {
4532        MessageDigest digest = null;
4533        try {
4534            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4535        } catch (NoSuchAlgorithmException e) {
4536            // If we can't create a digest, ignore ephemeral apps.
4537            return null;
4538        }
4539
4540        final byte[] hostBytes = intent.getData().getHost().getBytes();
4541        final byte[] digestBytes = digest.digest(hostBytes);
4542        int shaPrefix =
4543                digestBytes[0] << 24
4544                | digestBytes[1] << 16
4545                | digestBytes[2] << 8
4546                | digestBytes[3] << 0;
4547        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4548                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4549        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4550            // No hash prefix match; there are no ephemeral apps for this domain.
4551            return null;
4552        }
4553        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4554            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4555            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4556                continue;
4557            }
4558            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4559            // No filters; this should never happen.
4560            if (filters.isEmpty()) {
4561                continue;
4562            }
4563            // We have a domain match; resolve the filters to see if anything matches.
4564            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4565            for (int j = filters.size() - 1; j >= 0; --j) {
4566                final EphemeralResolveIntentInfo intentInfo =
4567                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4568                ephemeralResolver.addFilter(intentInfo);
4569            }
4570            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4571                    intent, resolvedType, false /*defaultOnly*/, userId);
4572            if (!matchedResolveInfoList.isEmpty()) {
4573                return matchedResolveInfoList.get(0);
4574            }
4575        }
4576        // Hash or filter mis-match; no ephemeral apps for this domain.
4577        return null;
4578    }
4579
4580    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4581            int flags, List<ResolveInfo> query, int userId) {
4582        if (query != null) {
4583            final int N = query.size();
4584            if (N == 1) {
4585                return query.get(0);
4586            } else if (N > 1) {
4587                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4588                // If there is more than one activity with the same priority,
4589                // then let the user decide between them.
4590                ResolveInfo r0 = query.get(0);
4591                ResolveInfo r1 = query.get(1);
4592                if (DEBUG_INTENT_MATCHING || debug) {
4593                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4594                            + r1.activityInfo.name + "=" + r1.priority);
4595                }
4596                // If the first activity has a higher priority, or a different
4597                // default, then it is always desirable to pick it.
4598                if (r0.priority != r1.priority
4599                        || r0.preferredOrder != r1.preferredOrder
4600                        || r0.isDefault != r1.isDefault) {
4601                    return query.get(0);
4602                }
4603                // If we have saved a preference for a preferred activity for
4604                // this Intent, use that.
4605                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4606                        flags, query, r0.priority, true, false, debug, userId);
4607                if (ri != null) {
4608                    return ri;
4609                }
4610                ri = new ResolveInfo(mResolveInfo);
4611                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4612                ri.activityInfo.applicationInfo = new ApplicationInfo(
4613                        ri.activityInfo.applicationInfo);
4614                if (userId != 0) {
4615                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4616                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4617                }
4618                // Make sure that the resolver is displayable in car mode
4619                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4620                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4621                return ri;
4622            }
4623        }
4624        return null;
4625    }
4626
4627    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4628            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4629        final int N = query.size();
4630        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4631                .get(userId);
4632        // Get the list of persistent preferred activities that handle the intent
4633        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4634        List<PersistentPreferredActivity> pprefs = ppir != null
4635                ? ppir.queryIntent(intent, resolvedType,
4636                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4637                : null;
4638        if (pprefs != null && pprefs.size() > 0) {
4639            final int M = pprefs.size();
4640            for (int i=0; i<M; i++) {
4641                final PersistentPreferredActivity ppa = pprefs.get(i);
4642                if (DEBUG_PREFERRED || debug) {
4643                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4644                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4645                            + "\n  component=" + ppa.mComponent);
4646                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4647                }
4648                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4649                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4650                if (DEBUG_PREFERRED || debug) {
4651                    Slog.v(TAG, "Found persistent preferred activity:");
4652                    if (ai != null) {
4653                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4654                    } else {
4655                        Slog.v(TAG, "  null");
4656                    }
4657                }
4658                if (ai == null) {
4659                    // This previously registered persistent preferred activity
4660                    // component is no longer known. Ignore it and do NOT remove it.
4661                    continue;
4662                }
4663                for (int j=0; j<N; j++) {
4664                    final ResolveInfo ri = query.get(j);
4665                    if (!ri.activityInfo.applicationInfo.packageName
4666                            .equals(ai.applicationInfo.packageName)) {
4667                        continue;
4668                    }
4669                    if (!ri.activityInfo.name.equals(ai.name)) {
4670                        continue;
4671                    }
4672                    //  Found a persistent preference that can handle the intent.
4673                    if (DEBUG_PREFERRED || debug) {
4674                        Slog.v(TAG, "Returning persistent preferred activity: " +
4675                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4676                    }
4677                    return ri;
4678                }
4679            }
4680        }
4681        return null;
4682    }
4683
4684    // TODO: handle preferred activities missing while user has amnesia
4685    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4686            List<ResolveInfo> query, int priority, boolean always,
4687            boolean removeMatches, boolean debug, int userId) {
4688        if (!sUserManager.exists(userId)) return null;
4689        flags = augmentFlagsForUser(flags, userId, intent);
4690        // writer
4691        synchronized (mPackages) {
4692            if (intent.getSelector() != null) {
4693                intent = intent.getSelector();
4694            }
4695            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4696
4697            // Try to find a matching persistent preferred activity.
4698            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4699                    debug, userId);
4700
4701            // If a persistent preferred activity matched, use it.
4702            if (pri != null) {
4703                return pri;
4704            }
4705
4706            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4707            // Get the list of preferred activities that handle the intent
4708            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4709            List<PreferredActivity> prefs = pir != null
4710                    ? pir.queryIntent(intent, resolvedType,
4711                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4712                    : null;
4713            if (prefs != null && prefs.size() > 0) {
4714                boolean changed = false;
4715                try {
4716                    // First figure out how good the original match set is.
4717                    // We will only allow preferred activities that came
4718                    // from the same match quality.
4719                    int match = 0;
4720
4721                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4722
4723                    final int N = query.size();
4724                    for (int j=0; j<N; j++) {
4725                        final ResolveInfo ri = query.get(j);
4726                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4727                                + ": 0x" + Integer.toHexString(match));
4728                        if (ri.match > match) {
4729                            match = ri.match;
4730                        }
4731                    }
4732
4733                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4734                            + Integer.toHexString(match));
4735
4736                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4737                    final int M = prefs.size();
4738                    for (int i=0; i<M; i++) {
4739                        final PreferredActivity pa = prefs.get(i);
4740                        if (DEBUG_PREFERRED || debug) {
4741                            Slog.v(TAG, "Checking PreferredActivity ds="
4742                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4743                                    + "\n  component=" + pa.mPref.mComponent);
4744                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4745                        }
4746                        if (pa.mPref.mMatch != match) {
4747                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4748                                    + Integer.toHexString(pa.mPref.mMatch));
4749                            continue;
4750                        }
4751                        // If it's not an "always" type preferred activity and that's what we're
4752                        // looking for, skip it.
4753                        if (always && !pa.mPref.mAlways) {
4754                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4755                            continue;
4756                        }
4757                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4758                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4759                        if (DEBUG_PREFERRED || debug) {
4760                            Slog.v(TAG, "Found preferred activity:");
4761                            if (ai != null) {
4762                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4763                            } else {
4764                                Slog.v(TAG, "  null");
4765                            }
4766                        }
4767                        if (ai == null) {
4768                            // This previously registered preferred activity
4769                            // component is no longer known.  Most likely an update
4770                            // to the app was installed and in the new version this
4771                            // component no longer exists.  Clean it up by removing
4772                            // it from the preferred activities list, and skip it.
4773                            Slog.w(TAG, "Removing dangling preferred activity: "
4774                                    + pa.mPref.mComponent);
4775                            pir.removeFilter(pa);
4776                            changed = true;
4777                            continue;
4778                        }
4779                        for (int j=0; j<N; j++) {
4780                            final ResolveInfo ri = query.get(j);
4781                            if (!ri.activityInfo.applicationInfo.packageName
4782                                    .equals(ai.applicationInfo.packageName)) {
4783                                continue;
4784                            }
4785                            if (!ri.activityInfo.name.equals(ai.name)) {
4786                                continue;
4787                            }
4788
4789                            if (removeMatches) {
4790                                pir.removeFilter(pa);
4791                                changed = true;
4792                                if (DEBUG_PREFERRED) {
4793                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4794                                }
4795                                break;
4796                            }
4797
4798                            // Okay we found a previously set preferred or last chosen app.
4799                            // If the result set is different from when this
4800                            // was created, we need to clear it and re-ask the
4801                            // user their preference, if we're looking for an "always" type entry.
4802                            if (always && !pa.mPref.sameSet(query)) {
4803                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4804                                        + intent + " type " + resolvedType);
4805                                if (DEBUG_PREFERRED) {
4806                                    Slog.v(TAG, "Removing preferred activity since set changed "
4807                                            + pa.mPref.mComponent);
4808                                }
4809                                pir.removeFilter(pa);
4810                                // Re-add the filter as a "last chosen" entry (!always)
4811                                PreferredActivity lastChosen = new PreferredActivity(
4812                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4813                                pir.addFilter(lastChosen);
4814                                changed = true;
4815                                return null;
4816                            }
4817
4818                            // Yay! Either the set matched or we're looking for the last chosen
4819                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4820                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4821                            return ri;
4822                        }
4823                    }
4824                } finally {
4825                    if (changed) {
4826                        if (DEBUG_PREFERRED) {
4827                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4828                        }
4829                        scheduleWritePackageRestrictionsLocked(userId);
4830                    }
4831                }
4832            }
4833        }
4834        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4835        return null;
4836    }
4837
4838    /*
4839     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4840     */
4841    @Override
4842    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4843            int targetUserId) {
4844        mContext.enforceCallingOrSelfPermission(
4845                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4846        List<CrossProfileIntentFilter> matches =
4847                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4848        if (matches != null) {
4849            int size = matches.size();
4850            for (int i = 0; i < size; i++) {
4851                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4852            }
4853        }
4854        if (hasWebURI(intent)) {
4855            // cross-profile app linking works only towards the parent.
4856            final UserInfo parent = getProfileParent(sourceUserId);
4857            synchronized(mPackages) {
4858                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4859                        intent, resolvedType, 0, sourceUserId, parent.id);
4860                return xpDomainInfo != null;
4861            }
4862        }
4863        return false;
4864    }
4865
4866    private UserInfo getProfileParent(int userId) {
4867        final long identity = Binder.clearCallingIdentity();
4868        try {
4869            return sUserManager.getProfileParent(userId);
4870        } finally {
4871            Binder.restoreCallingIdentity(identity);
4872        }
4873    }
4874
4875    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4876            String resolvedType, int userId) {
4877        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4878        if (resolver != null) {
4879            return resolver.queryIntent(intent, resolvedType, false, userId);
4880        }
4881        return null;
4882    }
4883
4884    @Override
4885    public List<ResolveInfo> queryIntentActivities(Intent intent,
4886            String resolvedType, int flags, int userId) {
4887        if (!sUserManager.exists(userId)) return Collections.emptyList();
4888        flags = augmentFlagsForUser(flags, userId, intent);
4889        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4890        ComponentName comp = intent.getComponent();
4891        if (comp == null) {
4892            if (intent.getSelector() != null) {
4893                intent = intent.getSelector();
4894                comp = intent.getComponent();
4895            }
4896        }
4897
4898        if (comp != null) {
4899            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4900            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4901            if (ai != null) {
4902                final ResolveInfo ri = new ResolveInfo();
4903                ri.activityInfo = ai;
4904                list.add(ri);
4905            }
4906            return list;
4907        }
4908
4909        // reader
4910        synchronized (mPackages) {
4911            final String pkgName = intent.getPackage();
4912            if (pkgName == null) {
4913                List<CrossProfileIntentFilter> matchingFilters =
4914                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4915                // Check for results that need to skip the current profile.
4916                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4917                        resolvedType, flags, userId);
4918                if (xpResolveInfo != null) {
4919                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4920                    result.add(xpResolveInfo);
4921                    return filterIfNotSystemUser(result, userId);
4922                }
4923
4924                // Check for results in the current profile.
4925                List<ResolveInfo> result = mActivities.queryIntent(
4926                        intent, resolvedType, flags, userId);
4927                result = filterIfNotSystemUser(result, userId);
4928
4929                // Check for cross profile results.
4930                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4931                xpResolveInfo = queryCrossProfileIntents(
4932                        matchingFilters, intent, resolvedType, flags, userId,
4933                        hasNonNegativePriorityResult);
4934                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4935                    boolean isVisibleToUser = filterIfNotSystemUser(
4936                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4937                    if (isVisibleToUser) {
4938                        result.add(xpResolveInfo);
4939                        Collections.sort(result, mResolvePrioritySorter);
4940                    }
4941                }
4942                if (hasWebURI(intent)) {
4943                    CrossProfileDomainInfo xpDomainInfo = null;
4944                    final UserInfo parent = getProfileParent(userId);
4945                    if (parent != null) {
4946                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4947                                flags, userId, parent.id);
4948                    }
4949                    if (xpDomainInfo != null) {
4950                        if (xpResolveInfo != null) {
4951                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4952                            // in the result.
4953                            result.remove(xpResolveInfo);
4954                        }
4955                        if (result.size() == 0) {
4956                            result.add(xpDomainInfo.resolveInfo);
4957                            return result;
4958                        }
4959                    } else if (result.size() <= 1) {
4960                        return result;
4961                    }
4962                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4963                            xpDomainInfo, userId);
4964                    Collections.sort(result, mResolvePrioritySorter);
4965                }
4966                return result;
4967            }
4968            final PackageParser.Package pkg = mPackages.get(pkgName);
4969            if (pkg != null) {
4970                return filterIfNotSystemUser(
4971                        mActivities.queryIntentForPackage(
4972                                intent, resolvedType, flags, pkg.activities, userId),
4973                        userId);
4974            }
4975            return new ArrayList<ResolveInfo>();
4976        }
4977    }
4978
4979    private static class CrossProfileDomainInfo {
4980        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4981        ResolveInfo resolveInfo;
4982        /* Best domain verification status of the activities found in the other profile */
4983        int bestDomainVerificationStatus;
4984    }
4985
4986    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4987            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4988        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4989                sourceUserId)) {
4990            return null;
4991        }
4992        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4993                resolvedType, flags, parentUserId);
4994
4995        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4996            return null;
4997        }
4998        CrossProfileDomainInfo result = null;
4999        int size = resultTargetUser.size();
5000        for (int i = 0; i < size; i++) {
5001            ResolveInfo riTargetUser = resultTargetUser.get(i);
5002            // Intent filter verification is only for filters that specify a host. So don't return
5003            // those that handle all web uris.
5004            if (riTargetUser.handleAllWebDataURI) {
5005                continue;
5006            }
5007            String packageName = riTargetUser.activityInfo.packageName;
5008            PackageSetting ps = mSettings.mPackages.get(packageName);
5009            if (ps == null) {
5010                continue;
5011            }
5012            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5013            int status = (int)(verificationState >> 32);
5014            if (result == null) {
5015                result = new CrossProfileDomainInfo();
5016                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5017                        sourceUserId, parentUserId);
5018                result.bestDomainVerificationStatus = status;
5019            } else {
5020                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5021                        result.bestDomainVerificationStatus);
5022            }
5023        }
5024        // Don't consider matches with status NEVER across profiles.
5025        if (result != null && result.bestDomainVerificationStatus
5026                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5027            return null;
5028        }
5029        return result;
5030    }
5031
5032    /**
5033     * Verification statuses are ordered from the worse to the best, except for
5034     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5035     */
5036    private int bestDomainVerificationStatus(int status1, int status2) {
5037        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5038            return status2;
5039        }
5040        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5041            return status1;
5042        }
5043        return (int) MathUtils.max(status1, status2);
5044    }
5045
5046    private boolean isUserEnabled(int userId) {
5047        long callingId = Binder.clearCallingIdentity();
5048        try {
5049            UserInfo userInfo = sUserManager.getUserInfo(userId);
5050            return userInfo != null && userInfo.isEnabled();
5051        } finally {
5052            Binder.restoreCallingIdentity(callingId);
5053        }
5054    }
5055
5056    /**
5057     * Filter out activities with systemUserOnly flag set, when current user is not System.
5058     *
5059     * @return filtered list
5060     */
5061    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5062        if (userId == UserHandle.USER_SYSTEM) {
5063            return resolveInfos;
5064        }
5065        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5066            ResolveInfo info = resolveInfos.get(i);
5067            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5068                resolveInfos.remove(i);
5069            }
5070        }
5071        return resolveInfos;
5072    }
5073
5074    /**
5075     * @param resolveInfos list of resolve infos in descending priority order
5076     * @return if the list contains a resolve info with non-negative priority
5077     */
5078    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5079        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5080    }
5081
5082    private static boolean hasWebURI(Intent intent) {
5083        if (intent.getData() == null) {
5084            return false;
5085        }
5086        final String scheme = intent.getScheme();
5087        if (TextUtils.isEmpty(scheme)) {
5088            return false;
5089        }
5090        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5091    }
5092
5093    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5094            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5095            int userId) {
5096        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5097
5098        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5099            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5100                    candidates.size());
5101        }
5102
5103        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5104        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5105        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5106        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5107        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5108        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5109
5110        synchronized (mPackages) {
5111            final int count = candidates.size();
5112            // First, try to use linked apps. Partition the candidates into four lists:
5113            // one for the final results, one for the "do not use ever", one for "undefined status"
5114            // and finally one for "browser app type".
5115            for (int n=0; n<count; n++) {
5116                ResolveInfo info = candidates.get(n);
5117                String packageName = info.activityInfo.packageName;
5118                PackageSetting ps = mSettings.mPackages.get(packageName);
5119                if (ps != null) {
5120                    // Add to the special match all list (Browser use case)
5121                    if (info.handleAllWebDataURI) {
5122                        matchAllList.add(info);
5123                        continue;
5124                    }
5125                    // Try to get the status from User settings first
5126                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5127                    int status = (int)(packedStatus >> 32);
5128                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5129                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5130                        if (DEBUG_DOMAIN_VERIFICATION) {
5131                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5132                                    + " : linkgen=" + linkGeneration);
5133                        }
5134                        // Use link-enabled generation as preferredOrder, i.e.
5135                        // prefer newly-enabled over earlier-enabled.
5136                        info.preferredOrder = linkGeneration;
5137                        alwaysList.add(info);
5138                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5139                        if (DEBUG_DOMAIN_VERIFICATION) {
5140                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5141                        }
5142                        neverList.add(info);
5143                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5144                        if (DEBUG_DOMAIN_VERIFICATION) {
5145                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5146                        }
5147                        alwaysAskList.add(info);
5148                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5149                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5150                        if (DEBUG_DOMAIN_VERIFICATION) {
5151                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5152                        }
5153                        undefinedList.add(info);
5154                    }
5155                }
5156            }
5157
5158            // We'll want to include browser possibilities in a few cases
5159            boolean includeBrowser = false;
5160
5161            // First try to add the "always" resolution(s) for the current user, if any
5162            if (alwaysList.size() > 0) {
5163                result.addAll(alwaysList);
5164            } else {
5165                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5166                result.addAll(undefinedList);
5167                // Maybe add one for the other profile.
5168                if (xpDomainInfo != null && (
5169                        xpDomainInfo.bestDomainVerificationStatus
5170                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5171                    result.add(xpDomainInfo.resolveInfo);
5172                }
5173                includeBrowser = true;
5174            }
5175
5176            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5177            // If there were 'always' entries their preferred order has been set, so we also
5178            // back that off to make the alternatives equivalent
5179            if (alwaysAskList.size() > 0) {
5180                for (ResolveInfo i : result) {
5181                    i.preferredOrder = 0;
5182                }
5183                result.addAll(alwaysAskList);
5184                includeBrowser = true;
5185            }
5186
5187            if (includeBrowser) {
5188                // Also add browsers (all of them or only the default one)
5189                if (DEBUG_DOMAIN_VERIFICATION) {
5190                    Slog.v(TAG, "   ...including browsers in candidate set");
5191                }
5192                if ((matchFlags & MATCH_ALL) != 0) {
5193                    result.addAll(matchAllList);
5194                } else {
5195                    // Browser/generic handling case.  If there's a default browser, go straight
5196                    // to that (but only if there is no other higher-priority match).
5197                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5198                    int maxMatchPrio = 0;
5199                    ResolveInfo defaultBrowserMatch = null;
5200                    final int numCandidates = matchAllList.size();
5201                    for (int n = 0; n < numCandidates; n++) {
5202                        ResolveInfo info = matchAllList.get(n);
5203                        // track the highest overall match priority...
5204                        if (info.priority > maxMatchPrio) {
5205                            maxMatchPrio = info.priority;
5206                        }
5207                        // ...and the highest-priority default browser match
5208                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5209                            if (defaultBrowserMatch == null
5210                                    || (defaultBrowserMatch.priority < info.priority)) {
5211                                if (debug) {
5212                                    Slog.v(TAG, "Considering default browser match " + info);
5213                                }
5214                                defaultBrowserMatch = info;
5215                            }
5216                        }
5217                    }
5218                    if (defaultBrowserMatch != null
5219                            && defaultBrowserMatch.priority >= maxMatchPrio
5220                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5221                    {
5222                        if (debug) {
5223                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5224                        }
5225                        result.add(defaultBrowserMatch);
5226                    } else {
5227                        result.addAll(matchAllList);
5228                    }
5229                }
5230
5231                // If there is nothing selected, add all candidates and remove the ones that the user
5232                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5233                if (result.size() == 0) {
5234                    result.addAll(candidates);
5235                    result.removeAll(neverList);
5236                }
5237            }
5238        }
5239        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5240            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5241                    result.size());
5242            for (ResolveInfo info : result) {
5243                Slog.v(TAG, "  + " + info.activityInfo);
5244            }
5245        }
5246        return result;
5247    }
5248
5249    // Returns a packed value as a long:
5250    //
5251    // high 'int'-sized word: link status: undefined/ask/never/always.
5252    // low 'int'-sized word: relative priority among 'always' results.
5253    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5254        long result = ps.getDomainVerificationStatusForUser(userId);
5255        // if none available, get the master status
5256        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5257            if (ps.getIntentFilterVerificationInfo() != null) {
5258                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5259            }
5260        }
5261        return result;
5262    }
5263
5264    private ResolveInfo querySkipCurrentProfileIntents(
5265            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5266            int flags, int sourceUserId) {
5267        if (matchingFilters != null) {
5268            int size = matchingFilters.size();
5269            for (int i = 0; i < size; i ++) {
5270                CrossProfileIntentFilter filter = matchingFilters.get(i);
5271                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5272                    // Checking if there are activities in the target user that can handle the
5273                    // intent.
5274                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5275                            resolvedType, flags, sourceUserId);
5276                    if (resolveInfo != null) {
5277                        return resolveInfo;
5278                    }
5279                }
5280            }
5281        }
5282        return null;
5283    }
5284
5285    // Return matching ResolveInfo in target user if any.
5286    private ResolveInfo queryCrossProfileIntents(
5287            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5288            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5289        if (matchingFilters != null) {
5290            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5291            // match the same intent. For performance reasons, it is better not to
5292            // run queryIntent twice for the same userId
5293            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5294            int size = matchingFilters.size();
5295            for (int i = 0; i < size; i++) {
5296                CrossProfileIntentFilter filter = matchingFilters.get(i);
5297                int targetUserId = filter.getTargetUserId();
5298                boolean skipCurrentProfile =
5299                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5300                boolean skipCurrentProfileIfNoMatchFound =
5301                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5302                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5303                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5304                    // Checking if there are activities in the target user that can handle the
5305                    // intent.
5306                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5307                            resolvedType, flags, sourceUserId);
5308                    if (resolveInfo != null) return resolveInfo;
5309                    alreadyTriedUserIds.put(targetUserId, true);
5310                }
5311            }
5312        }
5313        return null;
5314    }
5315
5316    /**
5317     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5318     * will forward the intent to the filter's target user.
5319     * Otherwise, returns null.
5320     */
5321    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5322            String resolvedType, int flags, int sourceUserId) {
5323        int targetUserId = filter.getTargetUserId();
5324        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5325                resolvedType, flags, targetUserId);
5326        if (resultTargetUser != null && !resultTargetUser.isEmpty()
5327                && isUserEnabled(targetUserId)) {
5328            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
5329        }
5330        return null;
5331    }
5332
5333    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5334            int sourceUserId, int targetUserId) {
5335        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5336        long ident = Binder.clearCallingIdentity();
5337        boolean targetIsProfile;
5338        try {
5339            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5340        } finally {
5341            Binder.restoreCallingIdentity(ident);
5342        }
5343        String className;
5344        if (targetIsProfile) {
5345            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5346        } else {
5347            className = FORWARD_INTENT_TO_PARENT;
5348        }
5349        ComponentName forwardingActivityComponentName = new ComponentName(
5350                mAndroidApplication.packageName, className);
5351        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5352                sourceUserId);
5353        if (!targetIsProfile) {
5354            forwardingActivityInfo.showUserIcon = targetUserId;
5355            forwardingResolveInfo.noResourceId = true;
5356        }
5357        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5358        forwardingResolveInfo.priority = 0;
5359        forwardingResolveInfo.preferredOrder = 0;
5360        forwardingResolveInfo.match = 0;
5361        forwardingResolveInfo.isDefault = true;
5362        forwardingResolveInfo.filter = filter;
5363        forwardingResolveInfo.targetUserId = targetUserId;
5364        return forwardingResolveInfo;
5365    }
5366
5367    @Override
5368    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5369            Intent[] specifics, String[] specificTypes, Intent intent,
5370            String resolvedType, int flags, int userId) {
5371        if (!sUserManager.exists(userId)) return Collections.emptyList();
5372        flags = augmentFlagsForUser(flags, userId, intent);
5373        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5374                false, "query intent activity options");
5375        final String resultsAction = intent.getAction();
5376
5377        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5378                | PackageManager.GET_RESOLVED_FILTER, userId);
5379
5380        if (DEBUG_INTENT_MATCHING) {
5381            Log.v(TAG, "Query " + intent + ": " + results);
5382        }
5383
5384        int specificsPos = 0;
5385        int N;
5386
5387        // todo: note that the algorithm used here is O(N^2).  This
5388        // isn't a problem in our current environment, but if we start running
5389        // into situations where we have more than 5 or 10 matches then this
5390        // should probably be changed to something smarter...
5391
5392        // First we go through and resolve each of the specific items
5393        // that were supplied, taking care of removing any corresponding
5394        // duplicate items in the generic resolve list.
5395        if (specifics != null) {
5396            for (int i=0; i<specifics.length; i++) {
5397                final Intent sintent = specifics[i];
5398                if (sintent == null) {
5399                    continue;
5400                }
5401
5402                if (DEBUG_INTENT_MATCHING) {
5403                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5404                }
5405
5406                String action = sintent.getAction();
5407                if (resultsAction != null && resultsAction.equals(action)) {
5408                    // If this action was explicitly requested, then don't
5409                    // remove things that have it.
5410                    action = null;
5411                }
5412
5413                ResolveInfo ri = null;
5414                ActivityInfo ai = null;
5415
5416                ComponentName comp = sintent.getComponent();
5417                if (comp == null) {
5418                    ri = resolveIntent(
5419                        sintent,
5420                        specificTypes != null ? specificTypes[i] : null,
5421                            flags, userId);
5422                    if (ri == null) {
5423                        continue;
5424                    }
5425                    if (ri == mResolveInfo) {
5426                        // ACK!  Must do something better with this.
5427                    }
5428                    ai = ri.activityInfo;
5429                    comp = new ComponentName(ai.applicationInfo.packageName,
5430                            ai.name);
5431                } else {
5432                    ai = getActivityInfo(comp, flags, userId);
5433                    if (ai == null) {
5434                        continue;
5435                    }
5436                }
5437
5438                // Look for any generic query activities that are duplicates
5439                // of this specific one, and remove them from the results.
5440                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5441                N = results.size();
5442                int j;
5443                for (j=specificsPos; j<N; j++) {
5444                    ResolveInfo sri = results.get(j);
5445                    if ((sri.activityInfo.name.equals(comp.getClassName())
5446                            && sri.activityInfo.applicationInfo.packageName.equals(
5447                                    comp.getPackageName()))
5448                        || (action != null && sri.filter.matchAction(action))) {
5449                        results.remove(j);
5450                        if (DEBUG_INTENT_MATCHING) Log.v(
5451                            TAG, "Removing duplicate item from " + j
5452                            + " due to specific " + specificsPos);
5453                        if (ri == null) {
5454                            ri = sri;
5455                        }
5456                        j--;
5457                        N--;
5458                    }
5459                }
5460
5461                // Add this specific item to its proper place.
5462                if (ri == null) {
5463                    ri = new ResolveInfo();
5464                    ri.activityInfo = ai;
5465                }
5466                results.add(specificsPos, ri);
5467                ri.specificIndex = i;
5468                specificsPos++;
5469            }
5470        }
5471
5472        // Now we go through the remaining generic results and remove any
5473        // duplicate actions that are found here.
5474        N = results.size();
5475        for (int i=specificsPos; i<N-1; i++) {
5476            final ResolveInfo rii = results.get(i);
5477            if (rii.filter == null) {
5478                continue;
5479            }
5480
5481            // Iterate over all of the actions of this result's intent
5482            // filter...  typically this should be just one.
5483            final Iterator<String> it = rii.filter.actionsIterator();
5484            if (it == null) {
5485                continue;
5486            }
5487            while (it.hasNext()) {
5488                final String action = it.next();
5489                if (resultsAction != null && resultsAction.equals(action)) {
5490                    // If this action was explicitly requested, then don't
5491                    // remove things that have it.
5492                    continue;
5493                }
5494                for (int j=i+1; j<N; j++) {
5495                    final ResolveInfo rij = results.get(j);
5496                    if (rij.filter != null && rij.filter.hasAction(action)) {
5497                        results.remove(j);
5498                        if (DEBUG_INTENT_MATCHING) Log.v(
5499                            TAG, "Removing duplicate item from " + j
5500                            + " due to action " + action + " at " + i);
5501                        j--;
5502                        N--;
5503                    }
5504                }
5505            }
5506
5507            // If the caller didn't request filter information, drop it now
5508            // so we don't have to marshall/unmarshall it.
5509            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5510                rii.filter = null;
5511            }
5512        }
5513
5514        // Filter out the caller activity if so requested.
5515        if (caller != null) {
5516            N = results.size();
5517            for (int i=0; i<N; i++) {
5518                ActivityInfo ainfo = results.get(i).activityInfo;
5519                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5520                        && caller.getClassName().equals(ainfo.name)) {
5521                    results.remove(i);
5522                    break;
5523                }
5524            }
5525        }
5526
5527        // If the caller didn't request filter information,
5528        // drop them now so we don't have to
5529        // marshall/unmarshall it.
5530        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5531            N = results.size();
5532            for (int i=0; i<N; i++) {
5533                results.get(i).filter = null;
5534            }
5535        }
5536
5537        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5538        return results;
5539    }
5540
5541    @Override
5542    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5543            int userId) {
5544        if (!sUserManager.exists(userId)) return Collections.emptyList();
5545        flags = augmentFlagsForUser(flags, userId, intent);
5546        ComponentName comp = intent.getComponent();
5547        if (comp == null) {
5548            if (intent.getSelector() != null) {
5549                intent = intent.getSelector();
5550                comp = intent.getComponent();
5551            }
5552        }
5553        if (comp != null) {
5554            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5555            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5556            if (ai != null) {
5557                ResolveInfo ri = new ResolveInfo();
5558                ri.activityInfo = ai;
5559                list.add(ri);
5560            }
5561            return list;
5562        }
5563
5564        // reader
5565        synchronized (mPackages) {
5566            String pkgName = intent.getPackage();
5567            if (pkgName == null) {
5568                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5569            }
5570            final PackageParser.Package pkg = mPackages.get(pkgName);
5571            if (pkg != null) {
5572                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5573                        userId);
5574            }
5575            return null;
5576        }
5577    }
5578
5579    @Override
5580    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5581        if (!sUserManager.exists(userId)) return null;
5582        flags = augmentFlagsForUser(flags, userId, intent);
5583        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5584        if (query != null) {
5585            if (query.size() >= 1) {
5586                // If there is more than one service with the same priority,
5587                // just arbitrarily pick the first one.
5588                return query.get(0);
5589            }
5590        }
5591        return null;
5592    }
5593
5594    @Override
5595    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5596            int userId) {
5597        if (!sUserManager.exists(userId)) return Collections.emptyList();
5598        flags = augmentFlagsForUser(flags, userId, intent);
5599        ComponentName comp = intent.getComponent();
5600        if (comp == null) {
5601            if (intent.getSelector() != null) {
5602                intent = intent.getSelector();
5603                comp = intent.getComponent();
5604            }
5605        }
5606        if (comp != null) {
5607            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5608            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5609            if (si != null) {
5610                final ResolveInfo ri = new ResolveInfo();
5611                ri.serviceInfo = si;
5612                list.add(ri);
5613            }
5614            return list;
5615        }
5616
5617        // reader
5618        synchronized (mPackages) {
5619            String pkgName = intent.getPackage();
5620            if (pkgName == null) {
5621                return mServices.queryIntent(intent, resolvedType, flags, userId);
5622            }
5623            final PackageParser.Package pkg = mPackages.get(pkgName);
5624            if (pkg != null) {
5625                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5626                        userId);
5627            }
5628            return null;
5629        }
5630    }
5631
5632    @Override
5633    public List<ResolveInfo> queryIntentContentProviders(
5634            Intent intent, String resolvedType, int flags, int userId) {
5635        if (!sUserManager.exists(userId)) return Collections.emptyList();
5636        flags = augmentFlagsForUser(flags, userId, intent);
5637        ComponentName comp = intent.getComponent();
5638        if (comp == null) {
5639            if (intent.getSelector() != null) {
5640                intent = intent.getSelector();
5641                comp = intent.getComponent();
5642            }
5643        }
5644        if (comp != null) {
5645            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5646            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5647            if (pi != null) {
5648                final ResolveInfo ri = new ResolveInfo();
5649                ri.providerInfo = pi;
5650                list.add(ri);
5651            }
5652            return list;
5653        }
5654
5655        // reader
5656        synchronized (mPackages) {
5657            String pkgName = intent.getPackage();
5658            if (pkgName == null) {
5659                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5660            }
5661            final PackageParser.Package pkg = mPackages.get(pkgName);
5662            if (pkg != null) {
5663                return mProviders.queryIntentForPackage(
5664                        intent, resolvedType, flags, pkg.providers, userId);
5665            }
5666            return null;
5667        }
5668    }
5669
5670    @Override
5671    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5672        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5673
5674        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5675
5676        // writer
5677        synchronized (mPackages) {
5678            ArrayList<PackageInfo> list;
5679            if (listUninstalled) {
5680                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5681                for (PackageSetting ps : mSettings.mPackages.values()) {
5682                    PackageInfo pi;
5683                    if (ps.pkg != null) {
5684                        pi = generatePackageInfo(ps.pkg, flags, userId);
5685                    } else {
5686                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5687                    }
5688                    if (pi != null) {
5689                        list.add(pi);
5690                    }
5691                }
5692            } else {
5693                list = new ArrayList<PackageInfo>(mPackages.size());
5694                for (PackageParser.Package p : mPackages.values()) {
5695                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5696                    if (pi != null) {
5697                        list.add(pi);
5698                    }
5699                }
5700            }
5701
5702            return new ParceledListSlice<PackageInfo>(list);
5703        }
5704    }
5705
5706    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5707            String[] permissions, boolean[] tmp, int flags, int userId) {
5708        int numMatch = 0;
5709        final PermissionsState permissionsState = ps.getPermissionsState();
5710        for (int i=0; i<permissions.length; i++) {
5711            final String permission = permissions[i];
5712            if (permissionsState.hasPermission(permission, userId)) {
5713                tmp[i] = true;
5714                numMatch++;
5715            } else {
5716                tmp[i] = false;
5717            }
5718        }
5719        if (numMatch == 0) {
5720            return;
5721        }
5722        PackageInfo pi;
5723        if (ps.pkg != null) {
5724            pi = generatePackageInfo(ps.pkg, flags, userId);
5725        } else {
5726            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5727        }
5728        // The above might return null in cases of uninstalled apps or install-state
5729        // skew across users/profiles.
5730        if (pi != null) {
5731            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5732                if (numMatch == permissions.length) {
5733                    pi.requestedPermissions = permissions;
5734                } else {
5735                    pi.requestedPermissions = new String[numMatch];
5736                    numMatch = 0;
5737                    for (int i=0; i<permissions.length; i++) {
5738                        if (tmp[i]) {
5739                            pi.requestedPermissions[numMatch] = permissions[i];
5740                            numMatch++;
5741                        }
5742                    }
5743                }
5744            }
5745            list.add(pi);
5746        }
5747    }
5748
5749    @Override
5750    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5751            String[] permissions, int flags, int userId) {
5752        if (!sUserManager.exists(userId)) return null;
5753        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5754
5755        // writer
5756        synchronized (mPackages) {
5757            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5758            boolean[] tmpBools = new boolean[permissions.length];
5759            if (listUninstalled) {
5760                for (PackageSetting ps : mSettings.mPackages.values()) {
5761                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5762                }
5763            } else {
5764                for (PackageParser.Package pkg : mPackages.values()) {
5765                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5766                    if (ps != null) {
5767                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5768                                userId);
5769                    }
5770                }
5771            }
5772
5773            return new ParceledListSlice<PackageInfo>(list);
5774        }
5775    }
5776
5777    @Override
5778    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5779        if (!sUserManager.exists(userId)) return null;
5780        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5781
5782        // writer
5783        synchronized (mPackages) {
5784            ArrayList<ApplicationInfo> list;
5785            if (listUninstalled) {
5786                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5787                for (PackageSetting ps : mSettings.mPackages.values()) {
5788                    ApplicationInfo ai;
5789                    if (ps.pkg != null) {
5790                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5791                                ps.readUserState(userId), userId);
5792                    } else {
5793                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5794                    }
5795                    if (ai != null) {
5796                        list.add(ai);
5797                    }
5798                }
5799            } else {
5800                list = new ArrayList<ApplicationInfo>(mPackages.size());
5801                for (PackageParser.Package p : mPackages.values()) {
5802                    if (p.mExtras != null) {
5803                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5804                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5805                        if (ai != null) {
5806                            list.add(ai);
5807                        }
5808                    }
5809                }
5810            }
5811
5812            return new ParceledListSlice<ApplicationInfo>(list);
5813        }
5814    }
5815
5816    @Override
5817    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5818        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5819                "getEphemeralApplications");
5820        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5821                "getEphemeralApplications");
5822        synchronized (mPackages) {
5823            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5824                    .getEphemeralApplicationsLPw(userId);
5825            if (ephemeralApps != null) {
5826                return new ParceledListSlice<>(ephemeralApps);
5827            }
5828        }
5829        return null;
5830    }
5831
5832    @Override
5833    public boolean isEphemeralApplication(String packageName, int userId) {
5834        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5835                "isEphemeral");
5836        if (!isCallerSameApp(packageName)) {
5837            return false;
5838        }
5839        synchronized (mPackages) {
5840            PackageParser.Package pkg = mPackages.get(packageName);
5841            if (pkg != null) {
5842                return pkg.applicationInfo.isEphemeralApp();
5843            }
5844        }
5845        return false;
5846    }
5847
5848    @Override
5849    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5850        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5851                "getCookie");
5852        if (!isCallerSameApp(packageName)) {
5853            return null;
5854        }
5855        synchronized (mPackages) {
5856            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5857                    packageName, userId);
5858        }
5859    }
5860
5861    @Override
5862    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5863        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5864                "setCookie");
5865        if (!isCallerSameApp(packageName)) {
5866            return false;
5867        }
5868        synchronized (mPackages) {
5869            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5870                    packageName, cookie, userId);
5871        }
5872    }
5873
5874    @Override
5875    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5876        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5877                "getEphemeralApplicationIcon");
5878        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5879                "getEphemeralApplicationIcon");
5880        synchronized (mPackages) {
5881            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5882                    packageName, userId);
5883        }
5884    }
5885
5886    private boolean isCallerSameApp(String packageName) {
5887        PackageParser.Package pkg = mPackages.get(packageName);
5888        return pkg != null
5889                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5890    }
5891
5892    public List<ApplicationInfo> getPersistentApplications(int flags) {
5893        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5894
5895        // reader
5896        synchronized (mPackages) {
5897            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5898            final int userId = UserHandle.getCallingUserId();
5899            while (i.hasNext()) {
5900                final PackageParser.Package p = i.next();
5901                if (p.applicationInfo != null
5902                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5903                        && (!mSafeMode || isSystemApp(p))) {
5904                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5905                    if (ps != null) {
5906                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5907                                ps.readUserState(userId), userId);
5908                        if (ai != null) {
5909                            finalList.add(ai);
5910                        }
5911                    }
5912                }
5913            }
5914        }
5915
5916        return finalList;
5917    }
5918
5919    @Override
5920    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5921        if (!sUserManager.exists(userId)) return null;
5922        flags = augmentFlagsForUser(flags, userId, name);
5923        // reader
5924        synchronized (mPackages) {
5925            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5926            PackageSetting ps = provider != null
5927                    ? mSettings.mPackages.get(provider.owner.packageName)
5928                    : null;
5929            return ps != null
5930                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5931                    && (!mSafeMode || (provider.info.applicationInfo.flags
5932                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5933                    ? PackageParser.generateProviderInfo(provider, flags,
5934                            ps.readUserState(userId), userId)
5935                    : null;
5936        }
5937    }
5938
5939    /**
5940     * @deprecated
5941     */
5942    @Deprecated
5943    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5944        // reader
5945        synchronized (mPackages) {
5946            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5947                    .entrySet().iterator();
5948            final int userId = UserHandle.getCallingUserId();
5949            while (i.hasNext()) {
5950                Map.Entry<String, PackageParser.Provider> entry = i.next();
5951                PackageParser.Provider p = entry.getValue();
5952                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5953
5954                if (ps != null && p.syncable
5955                        && (!mSafeMode || (p.info.applicationInfo.flags
5956                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5957                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5958                            ps.readUserState(userId), userId);
5959                    if (info != null) {
5960                        outNames.add(entry.getKey());
5961                        outInfo.add(info);
5962                    }
5963                }
5964            }
5965        }
5966    }
5967
5968    @Override
5969    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5970            int uid, int flags) {
5971        final int userId = processName != null ? UserHandle.getUserId(uid)
5972                : UserHandle.getCallingUserId();
5973        if (!sUserManager.exists(userId)) return null;
5974        flags = augmentFlagsForUser(flags, userId, processName);
5975
5976        ArrayList<ProviderInfo> finalList = null;
5977        // reader
5978        synchronized (mPackages) {
5979            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5980            while (i.hasNext()) {
5981                final PackageParser.Provider p = i.next();
5982                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5983                if (ps != null && p.info.authority != null
5984                        && (processName == null
5985                                || (p.info.processName.equals(processName)
5986                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5987                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)
5988                        && (!mSafeMode
5989                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5990                    if (finalList == null) {
5991                        finalList = new ArrayList<ProviderInfo>(3);
5992                    }
5993                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5994                            ps.readUserState(userId), userId);
5995                    if (info != null) {
5996                        finalList.add(info);
5997                    }
5998                }
5999            }
6000        }
6001
6002        if (finalList != null) {
6003            Collections.sort(finalList, mProviderInitOrderSorter);
6004            return new ParceledListSlice<ProviderInfo>(finalList);
6005        }
6006
6007        return null;
6008    }
6009
6010    @Override
6011    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
6012            int flags) {
6013        // reader
6014        synchronized (mPackages) {
6015            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6016            return PackageParser.generateInstrumentationInfo(i, flags);
6017        }
6018    }
6019
6020    @Override
6021    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6022            int flags) {
6023        ArrayList<InstrumentationInfo> finalList =
6024            new ArrayList<InstrumentationInfo>();
6025
6026        // reader
6027        synchronized (mPackages) {
6028            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6029            while (i.hasNext()) {
6030                final PackageParser.Instrumentation p = i.next();
6031                if (targetPackage == null
6032                        || targetPackage.equals(p.info.targetPackage)) {
6033                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6034                            flags);
6035                    if (ii != null) {
6036                        finalList.add(ii);
6037                    }
6038                }
6039            }
6040        }
6041
6042        return finalList;
6043    }
6044
6045    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6046        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6047        if (overlays == null) {
6048            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6049            return;
6050        }
6051        for (PackageParser.Package opkg : overlays.values()) {
6052            // Not much to do if idmap fails: we already logged the error
6053            // and we certainly don't want to abort installation of pkg simply
6054            // because an overlay didn't fit properly. For these reasons,
6055            // ignore the return value of createIdmapForPackagePairLI.
6056            createIdmapForPackagePairLI(pkg, opkg);
6057        }
6058    }
6059
6060    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6061            PackageParser.Package opkg) {
6062        if (!opkg.mTrustedOverlay) {
6063            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6064                    opkg.baseCodePath + ": overlay not trusted");
6065            return false;
6066        }
6067        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6068        if (overlaySet == null) {
6069            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6070                    opkg.baseCodePath + " but target package has no known overlays");
6071            return false;
6072        }
6073        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6074        // TODO: generate idmap for split APKs
6075        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6076            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6077                    + opkg.baseCodePath);
6078            return false;
6079        }
6080        PackageParser.Package[] overlayArray =
6081            overlaySet.values().toArray(new PackageParser.Package[0]);
6082        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6083            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6084                return p1.mOverlayPriority - p2.mOverlayPriority;
6085            }
6086        };
6087        Arrays.sort(overlayArray, cmp);
6088
6089        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6090        int i = 0;
6091        for (PackageParser.Package p : overlayArray) {
6092            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6093        }
6094        return true;
6095    }
6096
6097    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6098        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6099        try {
6100            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6101        } finally {
6102            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6103        }
6104    }
6105
6106    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6107        final File[] files = dir.listFiles();
6108        if (ArrayUtils.isEmpty(files)) {
6109            Log.d(TAG, "No files in app dir " + dir);
6110            return;
6111        }
6112
6113        if (DEBUG_PACKAGE_SCANNING) {
6114            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6115                    + " flags=0x" + Integer.toHexString(parseFlags));
6116        }
6117
6118        for (File file : files) {
6119            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6120                    && !PackageInstallerService.isStageName(file.getName());
6121            if (!isPackage) {
6122                // Ignore entries which are not packages
6123                continue;
6124            }
6125            try {
6126                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6127                        scanFlags, currentTime, null);
6128            } catch (PackageManagerException e) {
6129                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6130
6131                // Delete invalid userdata apps
6132                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6133                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6134                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6135                    if (file.isDirectory()) {
6136                        mInstaller.rmPackageDir(file.getAbsolutePath());
6137                    } else {
6138                        file.delete();
6139                    }
6140                }
6141            }
6142        }
6143    }
6144
6145    private static File getSettingsProblemFile() {
6146        File dataDir = Environment.getDataDirectory();
6147        File systemDir = new File(dataDir, "system");
6148        File fname = new File(systemDir, "uiderrors.txt");
6149        return fname;
6150    }
6151
6152    static void reportSettingsProblem(int priority, String msg) {
6153        logCriticalInfo(priority, msg);
6154    }
6155
6156    static void logCriticalInfo(int priority, String msg) {
6157        Slog.println(priority, TAG, msg);
6158        EventLogTags.writePmCriticalInfo(msg);
6159        try {
6160            File fname = getSettingsProblemFile();
6161            FileOutputStream out = new FileOutputStream(fname, true);
6162            PrintWriter pw = new FastPrintWriter(out);
6163            SimpleDateFormat formatter = new SimpleDateFormat();
6164            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6165            pw.println(dateString + ": " + msg);
6166            pw.close();
6167            FileUtils.setPermissions(
6168                    fname.toString(),
6169                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6170                    -1, -1);
6171        } catch (java.io.IOException e) {
6172        }
6173    }
6174
6175    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6176            PackageParser.Package pkg, File srcFile, int parseFlags)
6177            throws PackageManagerException {
6178        if (ps != null
6179                && ps.codePath.equals(srcFile)
6180                && ps.timeStamp == srcFile.lastModified()
6181                && !isCompatSignatureUpdateNeeded(pkg)
6182                && !isRecoverSignatureUpdateNeeded(pkg)) {
6183            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6184            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6185            ArraySet<PublicKey> signingKs;
6186            synchronized (mPackages) {
6187                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6188            }
6189            if (ps.signatures.mSignatures != null
6190                    && ps.signatures.mSignatures.length != 0
6191                    && signingKs != null) {
6192                // Optimization: reuse the existing cached certificates
6193                // if the package appears to be unchanged.
6194                pkg.mSignatures = ps.signatures.mSignatures;
6195                pkg.mSigningKeys = signingKs;
6196                return;
6197            }
6198
6199            Slog.w(TAG, "PackageSetting for " + ps.name
6200                    + " is missing signatures.  Collecting certs again to recover them.");
6201        } else {
6202            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6203        }
6204
6205        try {
6206            pp.collectCertificates(pkg, parseFlags);
6207        } catch (PackageParserException e) {
6208            throw PackageManagerException.from(e);
6209        }
6210    }
6211
6212    /**
6213     *  Traces a package scan.
6214     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6215     */
6216    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6217            long currentTime, UserHandle user) throws PackageManagerException {
6218        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6219        try {
6220            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6221        } finally {
6222            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6223        }
6224    }
6225
6226    /**
6227     *  Scans a package and returns the newly parsed package.
6228     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6229     */
6230    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6231            long currentTime, UserHandle user) throws PackageManagerException {
6232        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6233        parseFlags |= mDefParseFlags;
6234        PackageParser pp = new PackageParser();
6235        pp.setSeparateProcesses(mSeparateProcesses);
6236        pp.setOnlyCoreApps(mOnlyCore);
6237        pp.setDisplayMetrics(mMetrics);
6238
6239        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6240            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6241        }
6242
6243        final PackageParser.Package pkg;
6244        try {
6245            pkg = pp.parsePackage(scanFile, parseFlags);
6246        } catch (PackageParserException e) {
6247            throw PackageManagerException.from(e);
6248        }
6249
6250        PackageSetting ps = null;
6251        PackageSetting updatedPkg;
6252        // reader
6253        synchronized (mPackages) {
6254            // Look to see if we already know about this package.
6255            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6256            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6257                // This package has been renamed to its original name.  Let's
6258                // use that.
6259                ps = mSettings.peekPackageLPr(oldName);
6260            }
6261            // If there was no original package, see one for the real package name.
6262            if (ps == null) {
6263                ps = mSettings.peekPackageLPr(pkg.packageName);
6264            }
6265            // Check to see if this package could be hiding/updating a system
6266            // package.  Must look for it either under the original or real
6267            // package name depending on our state.
6268            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6269            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6270        }
6271        boolean updatedPkgBetter = false;
6272        // First check if this is a system package that may involve an update
6273        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6274            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6275            // it needs to drop FLAG_PRIVILEGED.
6276            if (locationIsPrivileged(scanFile)) {
6277                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6278            } else {
6279                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6280            }
6281
6282            if (ps != null && !ps.codePath.equals(scanFile)) {
6283                // The path has changed from what was last scanned...  check the
6284                // version of the new path against what we have stored to determine
6285                // what to do.
6286                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6287                if (pkg.mVersionCode <= ps.versionCode) {
6288                    // The system package has been updated and the code path does not match
6289                    // Ignore entry. Skip it.
6290                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6291                            + " ignored: updated version " + ps.versionCode
6292                            + " better than this " + pkg.mVersionCode);
6293                    if (!updatedPkg.codePath.equals(scanFile)) {
6294                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
6295                                + ps.name + " changing from " + updatedPkg.codePathString
6296                                + " to " + scanFile);
6297                        updatedPkg.codePath = scanFile;
6298                        updatedPkg.codePathString = scanFile.toString();
6299                        updatedPkg.resourcePath = scanFile;
6300                        updatedPkg.resourcePathString = scanFile.toString();
6301                    }
6302                    updatedPkg.pkg = pkg;
6303                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6304                            "Package " + ps.name + " at " + scanFile
6305                                    + " ignored: updated version " + ps.versionCode
6306                                    + " better than this " + pkg.mVersionCode);
6307                } else {
6308                    // The current app on the system partition is better than
6309                    // what we have updated to on the data partition; switch
6310                    // back to the system partition version.
6311                    // At this point, its safely assumed that package installation for
6312                    // apps in system partition will go through. If not there won't be a working
6313                    // version of the app
6314                    // writer
6315                    synchronized (mPackages) {
6316                        // Just remove the loaded entries from package lists.
6317                        mPackages.remove(ps.name);
6318                    }
6319
6320                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6321                            + " reverting from " + ps.codePathString
6322                            + ": new version " + pkg.mVersionCode
6323                            + " better than installed " + ps.versionCode);
6324
6325                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6326                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6327                    synchronized (mInstallLock) {
6328                        args.cleanUpResourcesLI();
6329                    }
6330                    synchronized (mPackages) {
6331                        mSettings.enableSystemPackageLPw(ps.name);
6332                    }
6333                    updatedPkgBetter = true;
6334                }
6335            }
6336        }
6337
6338        if (updatedPkg != null) {
6339            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6340            // initially
6341            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6342
6343            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6344            // flag set initially
6345            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6346                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6347            }
6348        }
6349
6350        // Verify certificates against what was last scanned
6351        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6352
6353        /*
6354         * A new system app appeared, but we already had a non-system one of the
6355         * same name installed earlier.
6356         */
6357        boolean shouldHideSystemApp = false;
6358        if (updatedPkg == null && ps != null
6359                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6360            /*
6361             * Check to make sure the signatures match first. If they don't,
6362             * wipe the installed application and its data.
6363             */
6364            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6365                    != PackageManager.SIGNATURE_MATCH) {
6366                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6367                        + " signatures don't match existing userdata copy; removing");
6368                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6369                ps = null;
6370            } else {
6371                /*
6372                 * If the newly-added system app is an older version than the
6373                 * already installed version, hide it. It will be scanned later
6374                 * and re-added like an update.
6375                 */
6376                if (pkg.mVersionCode <= ps.versionCode) {
6377                    shouldHideSystemApp = true;
6378                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6379                            + " but new version " + pkg.mVersionCode + " better than installed "
6380                            + ps.versionCode + "; hiding system");
6381                } else {
6382                    /*
6383                     * The newly found system app is a newer version that the
6384                     * one previously installed. Simply remove the
6385                     * already-installed application and replace it with our own
6386                     * while keeping the application data.
6387                     */
6388                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6389                            + " reverting from " + ps.codePathString + ": new version "
6390                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6391                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6392                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6393                    synchronized (mInstallLock) {
6394                        args.cleanUpResourcesLI();
6395                    }
6396                }
6397            }
6398        }
6399
6400        // The apk is forward locked (not public) if its code and resources
6401        // are kept in different files. (except for app in either system or
6402        // vendor path).
6403        // TODO grab this value from PackageSettings
6404        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6405            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6406                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6407            }
6408        }
6409
6410        // TODO: extend to support forward-locked splits
6411        String resourcePath = null;
6412        String baseResourcePath = null;
6413        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6414            if (ps != null && ps.resourcePathString != null) {
6415                resourcePath = ps.resourcePathString;
6416                baseResourcePath = ps.resourcePathString;
6417            } else {
6418                // Should not happen at all. Just log an error.
6419                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
6420            }
6421        } else {
6422            resourcePath = pkg.codePath;
6423            baseResourcePath = pkg.baseCodePath;
6424        }
6425
6426        // Set application objects path explicitly.
6427        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6428        pkg.applicationInfo.setCodePath(pkg.codePath);
6429        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6430        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6431        pkg.applicationInfo.setResourcePath(resourcePath);
6432        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6433        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6434
6435        // Note that we invoke the following method only if we are about to unpack an application
6436        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6437                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6438
6439        /*
6440         * If the system app should be overridden by a previously installed
6441         * data, hide the system app now and let the /data/app scan pick it up
6442         * again.
6443         */
6444        if (shouldHideSystemApp) {
6445            synchronized (mPackages) {
6446                mSettings.disableSystemPackageLPw(pkg.packageName);
6447            }
6448        }
6449
6450        return scannedPkg;
6451    }
6452
6453    private static String fixProcessName(String defProcessName,
6454            String processName, int uid) {
6455        if (processName == null) {
6456            return defProcessName;
6457        }
6458        return processName;
6459    }
6460
6461    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6462            throws PackageManagerException {
6463        if (pkgSetting.signatures.mSignatures != null) {
6464            // Already existing package. Make sure signatures match
6465            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6466                    == PackageManager.SIGNATURE_MATCH;
6467            if (!match) {
6468                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6469                        == PackageManager.SIGNATURE_MATCH;
6470            }
6471            if (!match) {
6472                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6473                        == PackageManager.SIGNATURE_MATCH;
6474            }
6475            if (!match) {
6476                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6477                        + pkg.packageName + " signatures do not match the "
6478                        + "previously installed version; ignoring!");
6479            }
6480        }
6481
6482        // Check for shared user signatures
6483        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6484            // Already existing package. Make sure signatures match
6485            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6486                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6487            if (!match) {
6488                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6489                        == PackageManager.SIGNATURE_MATCH;
6490            }
6491            if (!match) {
6492                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6493                        == PackageManager.SIGNATURE_MATCH;
6494            }
6495            if (!match) {
6496                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6497                        "Package " + pkg.packageName
6498                        + " has no signatures that match those in shared user "
6499                        + pkgSetting.sharedUser.name + "; ignoring!");
6500            }
6501        }
6502    }
6503
6504    /**
6505     * Enforces that only the system UID or root's UID can call a method exposed
6506     * via Binder.
6507     *
6508     * @param message used as message if SecurityException is thrown
6509     * @throws SecurityException if the caller is not system or root
6510     */
6511    private static final void enforceSystemOrRoot(String message) {
6512        final int uid = Binder.getCallingUid();
6513        if (uid != Process.SYSTEM_UID && uid != 0) {
6514            throw new SecurityException(message);
6515        }
6516    }
6517
6518    @Override
6519    public void performFstrimIfNeeded() {
6520        enforceSystemOrRoot("Only the system can request fstrim");
6521
6522        // Before everything else, see whether we need to fstrim.
6523        try {
6524            IMountService ms = PackageHelper.getMountService();
6525            if (ms != null) {
6526                final boolean isUpgrade = isUpgrade();
6527                boolean doTrim = isUpgrade;
6528                if (doTrim) {
6529                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6530                } else {
6531                    final long interval = android.provider.Settings.Global.getLong(
6532                            mContext.getContentResolver(),
6533                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6534                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6535                    if (interval > 0) {
6536                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6537                        if (timeSinceLast > interval) {
6538                            doTrim = true;
6539                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6540                                    + "; running immediately");
6541                        }
6542                    }
6543                }
6544                if (doTrim) {
6545                    if (!isFirstBoot()) {
6546                        try {
6547                            ActivityManagerNative.getDefault().showBootMessage(
6548                                    mContext.getResources().getString(
6549                                            R.string.android_upgrading_fstrim), true);
6550                        } catch (RemoteException e) {
6551                        }
6552                    }
6553                    ms.runMaintenance();
6554                }
6555            } else {
6556                Slog.e(TAG, "Mount service unavailable!");
6557            }
6558        } catch (RemoteException e) {
6559            // Can't happen; MountService is local
6560        }
6561    }
6562
6563    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6564        List<ResolveInfo> ris = null;
6565        try {
6566            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6567                    intent, null, 0, userId);
6568        } catch (RemoteException e) {
6569        }
6570        ArraySet<String> pkgNames = new ArraySet<String>();
6571        if (ris != null) {
6572            for (ResolveInfo ri : ris) {
6573                pkgNames.add(ri.activityInfo.packageName);
6574            }
6575        }
6576        return pkgNames;
6577    }
6578
6579    @Override
6580    public void notifyPackageUse(String packageName) {
6581        synchronized (mPackages) {
6582            PackageParser.Package p = mPackages.get(packageName);
6583            if (p == null) {
6584                return;
6585            }
6586            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6587        }
6588    }
6589
6590    @Override
6591    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6592        return performDexOptTraced(packageName, instructionSet);
6593    }
6594
6595    public boolean performDexOpt(String packageName, String instructionSet) {
6596        return performDexOptTraced(packageName, instructionSet);
6597    }
6598
6599    private boolean performDexOptTraced(String packageName, String instructionSet) {
6600        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6601        try {
6602            return performDexOptInternal(packageName, instructionSet);
6603        } finally {
6604            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6605        }
6606    }
6607
6608    private boolean performDexOptInternal(String packageName, String instructionSet) {
6609        PackageParser.Package p;
6610        final String targetInstructionSet;
6611        synchronized (mPackages) {
6612            p = mPackages.get(packageName);
6613            if (p == null) {
6614                return false;
6615            }
6616            mPackageUsage.write(false);
6617
6618            targetInstructionSet = instructionSet != null ? instructionSet :
6619                    getPrimaryInstructionSet(p.applicationInfo);
6620            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6621                return false;
6622            }
6623        }
6624        long callingId = Binder.clearCallingIdentity();
6625        try {
6626            synchronized (mInstallLock) {
6627                final String[] instructionSets = new String[] { targetInstructionSet };
6628                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6629                        true /* inclDependencies */);
6630                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6631            }
6632        } finally {
6633            Binder.restoreCallingIdentity(callingId);
6634        }
6635    }
6636
6637    public ArraySet<String> getPackagesThatNeedDexOpt() {
6638        ArraySet<String> pkgs = null;
6639        synchronized (mPackages) {
6640            for (PackageParser.Package p : mPackages.values()) {
6641                if (DEBUG_DEXOPT) {
6642                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6643                }
6644                if (!p.mDexOptPerformed.isEmpty()) {
6645                    continue;
6646                }
6647                if (pkgs == null) {
6648                    pkgs = new ArraySet<String>();
6649                }
6650                pkgs.add(p.packageName);
6651            }
6652        }
6653        return pkgs;
6654    }
6655
6656    public void shutdown() {
6657        mPackageUsage.write(true);
6658    }
6659
6660    @Override
6661    public void forceDexOpt(String packageName) {
6662        enforceSystemOrRoot("forceDexOpt");
6663
6664        PackageParser.Package pkg;
6665        synchronized (mPackages) {
6666            pkg = mPackages.get(packageName);
6667            if (pkg == null) {
6668                throw new IllegalArgumentException("Missing package: " + packageName);
6669            }
6670        }
6671
6672        synchronized (mInstallLock) {
6673            final String[] instructionSets = new String[] {
6674                    getPrimaryInstructionSet(pkg.applicationInfo) };
6675
6676            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6677
6678            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6679                    true /* inclDependencies */);
6680
6681            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6682            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6683                throw new IllegalStateException("Failed to dexopt: " + res);
6684            }
6685        }
6686    }
6687
6688    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6689        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6690            Slog.w(TAG, "Unable to update from " + oldPkg.name
6691                    + " to " + newPkg.packageName
6692                    + ": old package not in system partition");
6693            return false;
6694        } else if (mPackages.get(oldPkg.name) != null) {
6695            Slog.w(TAG, "Unable to update from " + oldPkg.name
6696                    + " to " + newPkg.packageName
6697                    + ": old package still exists");
6698            return false;
6699        }
6700        return true;
6701    }
6702
6703    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6704            throws PackageManagerException {
6705        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6706        if (res != 0) {
6707            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6708                    "Failed to install " + packageName + ": " + res);
6709        }
6710
6711        final int[] users = sUserManager.getUserIds();
6712        for (int user : users) {
6713            if (user != 0) {
6714                res = mInstaller.createUserData(volumeUuid, packageName,
6715                        UserHandle.getUid(user, uid), user, seinfo);
6716                if (res != 0) {
6717                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6718                            "Failed to createUserData " + packageName + ": " + res);
6719                }
6720            }
6721        }
6722    }
6723
6724    private int removeDataDirsLI(String volumeUuid, String packageName) {
6725        int[] users = sUserManager.getUserIds();
6726        int res = 0;
6727        for (int user : users) {
6728            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6729            if (resInner < 0) {
6730                res = resInner;
6731            }
6732        }
6733
6734        return res;
6735    }
6736
6737    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6738        int[] users = sUserManager.getUserIds();
6739        int res = 0;
6740        for (int user : users) {
6741            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6742            if (resInner < 0) {
6743                res = resInner;
6744            }
6745        }
6746        return res;
6747    }
6748
6749    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6750            PackageParser.Package changingLib) {
6751        if (file.path != null) {
6752            usesLibraryFiles.add(file.path);
6753            return;
6754        }
6755        PackageParser.Package p = mPackages.get(file.apk);
6756        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6757            // If we are doing this while in the middle of updating a library apk,
6758            // then we need to make sure to use that new apk for determining the
6759            // dependencies here.  (We haven't yet finished committing the new apk
6760            // to the package manager state.)
6761            if (p == null || p.packageName.equals(changingLib.packageName)) {
6762                p = changingLib;
6763            }
6764        }
6765        if (p != null) {
6766            usesLibraryFiles.addAll(p.getAllCodePaths());
6767        }
6768    }
6769
6770    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6771            PackageParser.Package changingLib) throws PackageManagerException {
6772        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6773            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6774            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6775            for (int i=0; i<N; i++) {
6776                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6777                if (file == null) {
6778                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6779                            "Package " + pkg.packageName + " requires unavailable shared library "
6780                            + pkg.usesLibraries.get(i) + "; failing!");
6781                }
6782                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6783            }
6784            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6785            for (int i=0; i<N; i++) {
6786                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6787                if (file == null) {
6788                    Slog.w(TAG, "Package " + pkg.packageName
6789                            + " desires unavailable shared library "
6790                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6791                } else {
6792                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6793                }
6794            }
6795            N = usesLibraryFiles.size();
6796            if (N > 0) {
6797                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6798            } else {
6799                pkg.usesLibraryFiles = null;
6800            }
6801        }
6802    }
6803
6804    private static boolean hasString(List<String> list, List<String> which) {
6805        if (list == null) {
6806            return false;
6807        }
6808        for (int i=list.size()-1; i>=0; i--) {
6809            for (int j=which.size()-1; j>=0; j--) {
6810                if (which.get(j).equals(list.get(i))) {
6811                    return true;
6812                }
6813            }
6814        }
6815        return false;
6816    }
6817
6818    private void updateAllSharedLibrariesLPw() {
6819        for (PackageParser.Package pkg : mPackages.values()) {
6820            try {
6821                updateSharedLibrariesLPw(pkg, null);
6822            } catch (PackageManagerException e) {
6823                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6824            }
6825        }
6826    }
6827
6828    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6829            PackageParser.Package changingPkg) {
6830        ArrayList<PackageParser.Package> res = null;
6831        for (PackageParser.Package pkg : mPackages.values()) {
6832            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6833                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6834                if (res == null) {
6835                    res = new ArrayList<PackageParser.Package>();
6836                }
6837                res.add(pkg);
6838                try {
6839                    updateSharedLibrariesLPw(pkg, changingPkg);
6840                } catch (PackageManagerException e) {
6841                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6842                }
6843            }
6844        }
6845        return res;
6846    }
6847
6848    /**
6849     * Derive the value of the {@code cpuAbiOverride} based on the provided
6850     * value and an optional stored value from the package settings.
6851     */
6852    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6853        String cpuAbiOverride = null;
6854
6855        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6856            cpuAbiOverride = null;
6857        } else if (abiOverride != null) {
6858            cpuAbiOverride = abiOverride;
6859        } else if (settings != null) {
6860            cpuAbiOverride = settings.cpuAbiOverrideString;
6861        }
6862
6863        return cpuAbiOverride;
6864    }
6865
6866    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6867            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6868        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6869        try {
6870            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6871        } finally {
6872            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6873        }
6874    }
6875
6876    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6877            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6878        boolean success = false;
6879        try {
6880            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6881                    currentTime, user);
6882            success = true;
6883            return res;
6884        } finally {
6885            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6886                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6887            }
6888        }
6889    }
6890
6891    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6892            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6893        final File scanFile = new File(pkg.codePath);
6894        if (pkg.applicationInfo.getCodePath() == null ||
6895                pkg.applicationInfo.getResourcePath() == null) {
6896            // Bail out. The resource and code paths haven't been set.
6897            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6898                    "Code and resource paths haven't been set correctly");
6899        }
6900
6901        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6902            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6903        } else {
6904            // Only allow system apps to be flagged as core apps.
6905            pkg.coreApp = false;
6906        }
6907
6908        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6909            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6910        }
6911
6912        if (mCustomResolverComponentName != null &&
6913                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6914            setUpCustomResolverActivity(pkg);
6915        }
6916
6917        if (pkg.packageName.equals("android")) {
6918            synchronized (mPackages) {
6919                if (mAndroidApplication != null) {
6920                    Slog.w(TAG, "*************************************************");
6921                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6922                    Slog.w(TAG, " file=" + scanFile);
6923                    Slog.w(TAG, "*************************************************");
6924                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6925                            "Core android package being redefined.  Skipping.");
6926                }
6927
6928                // Set up information for our fall-back user intent resolution activity.
6929                mPlatformPackage = pkg;
6930                pkg.mVersionCode = mSdkVersion;
6931                mAndroidApplication = pkg.applicationInfo;
6932
6933                if (!mResolverReplaced) {
6934                    mResolveActivity.applicationInfo = mAndroidApplication;
6935                    mResolveActivity.name = ResolverActivity.class.getName();
6936                    mResolveActivity.packageName = mAndroidApplication.packageName;
6937                    mResolveActivity.processName = "system:ui";
6938                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6939                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6940                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6941                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6942                    mResolveActivity.exported = true;
6943                    mResolveActivity.enabled = true;
6944                    mResolveInfo.activityInfo = mResolveActivity;
6945                    mResolveInfo.priority = 0;
6946                    mResolveInfo.preferredOrder = 0;
6947                    mResolveInfo.match = 0;
6948                    mResolveComponentName = new ComponentName(
6949                            mAndroidApplication.packageName, mResolveActivity.name);
6950                }
6951            }
6952        }
6953
6954        if (DEBUG_PACKAGE_SCANNING) {
6955            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6956                Log.d(TAG, "Scanning package " + pkg.packageName);
6957        }
6958
6959        if (mPackages.containsKey(pkg.packageName)
6960                || mSharedLibraries.containsKey(pkg.packageName)) {
6961            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6962                    "Application package " + pkg.packageName
6963                    + " already installed.  Skipping duplicate.");
6964        }
6965
6966        // If we're only installing presumed-existing packages, require that the
6967        // scanned APK is both already known and at the path previously established
6968        // for it.  Previously unknown packages we pick up normally, but if we have an
6969        // a priori expectation about this package's install presence, enforce it.
6970        // With a singular exception for new system packages. When an OTA contains
6971        // a new system package, we allow the codepath to change from a system location
6972        // to the user-installed location. If we don't allow this change, any newer,
6973        // user-installed version of the application will be ignored.
6974        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6975            if (mExpectingBetter.containsKey(pkg.packageName)) {
6976                logCriticalInfo(Log.WARN,
6977                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6978            } else {
6979                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6980                if (known != null) {
6981                    if (DEBUG_PACKAGE_SCANNING) {
6982                        Log.d(TAG, "Examining " + pkg.codePath
6983                                + " and requiring known paths " + known.codePathString
6984                                + " & " + known.resourcePathString);
6985                    }
6986                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6987                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6988                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6989                                "Application package " + pkg.packageName
6990                                + " found at " + pkg.applicationInfo.getCodePath()
6991                                + " but expected at " + known.codePathString + "; ignoring.");
6992                    }
6993                }
6994            }
6995        }
6996
6997        // Initialize package source and resource directories
6998        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6999        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7000
7001        SharedUserSetting suid = null;
7002        PackageSetting pkgSetting = null;
7003
7004        if (!isSystemApp(pkg)) {
7005            // Only system apps can use these features.
7006            pkg.mOriginalPackages = null;
7007            pkg.mRealPackage = null;
7008            pkg.mAdoptPermissions = null;
7009        }
7010
7011        // writer
7012        synchronized (mPackages) {
7013            if (pkg.mSharedUserId != null) {
7014                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7015                if (suid == null) {
7016                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7017                            "Creating application package " + pkg.packageName
7018                            + " for shared user failed");
7019                }
7020                if (DEBUG_PACKAGE_SCANNING) {
7021                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7022                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7023                                + "): packages=" + suid.packages);
7024                }
7025            }
7026
7027            // Check if we are renaming from an original package name.
7028            PackageSetting origPackage = null;
7029            String realName = null;
7030            if (pkg.mOriginalPackages != null) {
7031                // This package may need to be renamed to a previously
7032                // installed name.  Let's check on that...
7033                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7034                if (pkg.mOriginalPackages.contains(renamed)) {
7035                    // This package had originally been installed as the
7036                    // original name, and we have already taken care of
7037                    // transitioning to the new one.  Just update the new
7038                    // one to continue using the old name.
7039                    realName = pkg.mRealPackage;
7040                    if (!pkg.packageName.equals(renamed)) {
7041                        // Callers into this function may have already taken
7042                        // care of renaming the package; only do it here if
7043                        // it is not already done.
7044                        pkg.setPackageName(renamed);
7045                    }
7046
7047                } else {
7048                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7049                        if ((origPackage = mSettings.peekPackageLPr(
7050                                pkg.mOriginalPackages.get(i))) != null) {
7051                            // We do have the package already installed under its
7052                            // original name...  should we use it?
7053                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7054                                // New package is not compatible with original.
7055                                origPackage = null;
7056                                continue;
7057                            } else if (origPackage.sharedUser != null) {
7058                                // Make sure uid is compatible between packages.
7059                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7060                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7061                                            + " to " + pkg.packageName + ": old uid "
7062                                            + origPackage.sharedUser.name
7063                                            + " differs from " + pkg.mSharedUserId);
7064                                    origPackage = null;
7065                                    continue;
7066                                }
7067                            } else {
7068                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7069                                        + pkg.packageName + " to old name " + origPackage.name);
7070                            }
7071                            break;
7072                        }
7073                    }
7074                }
7075            }
7076
7077            if (mTransferedPackages.contains(pkg.packageName)) {
7078                Slog.w(TAG, "Package " + pkg.packageName
7079                        + " was transferred to another, but its .apk remains");
7080            }
7081
7082            // Just create the setting, don't add it yet. For already existing packages
7083            // the PkgSetting exists already and doesn't have to be created.
7084            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7085                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7086                    pkg.applicationInfo.primaryCpuAbi,
7087                    pkg.applicationInfo.secondaryCpuAbi,
7088                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7089                    user, false);
7090            if (pkgSetting == null) {
7091                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7092                        "Creating application package " + pkg.packageName + " failed");
7093            }
7094
7095            if (pkgSetting.origPackage != null) {
7096                // If we are first transitioning from an original package,
7097                // fix up the new package's name now.  We need to do this after
7098                // looking up the package under its new name, so getPackageLP
7099                // can take care of fiddling things correctly.
7100                pkg.setPackageName(origPackage.name);
7101
7102                // File a report about this.
7103                String msg = "New package " + pkgSetting.realName
7104                        + " renamed to replace old package " + pkgSetting.name;
7105                reportSettingsProblem(Log.WARN, msg);
7106
7107                // Make a note of it.
7108                mTransferedPackages.add(origPackage.name);
7109
7110                // No longer need to retain this.
7111                pkgSetting.origPackage = null;
7112            }
7113
7114            if (realName != null) {
7115                // Make a note of it.
7116                mTransferedPackages.add(pkg.packageName);
7117            }
7118
7119            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7120                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7121            }
7122
7123            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7124                // Check all shared libraries and map to their actual file path.
7125                // We only do this here for apps not on a system dir, because those
7126                // are the only ones that can fail an install due to this.  We
7127                // will take care of the system apps by updating all of their
7128                // library paths after the scan is done.
7129                updateSharedLibrariesLPw(pkg, null);
7130            }
7131
7132            if (mFoundPolicyFile) {
7133                SELinuxMMAC.assignSeinfoValue(pkg);
7134            }
7135
7136            pkg.applicationInfo.uid = pkgSetting.appId;
7137            pkg.mExtras = pkgSetting;
7138            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7139                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7140                    // We just determined the app is signed correctly, so bring
7141                    // over the latest parsed certs.
7142                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7143                } else {
7144                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7145                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7146                                "Package " + pkg.packageName + " upgrade keys do not match the "
7147                                + "previously installed version");
7148                    } else {
7149                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7150                        String msg = "System package " + pkg.packageName
7151                            + " signature changed; retaining data.";
7152                        reportSettingsProblem(Log.WARN, msg);
7153                    }
7154                }
7155            } else {
7156                try {
7157                    verifySignaturesLP(pkgSetting, pkg);
7158                    // We just determined the app is signed correctly, so bring
7159                    // over the latest parsed certs.
7160                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7161                } catch (PackageManagerException e) {
7162                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7163                        throw e;
7164                    }
7165                    // The signature has changed, but this package is in the system
7166                    // image...  let's recover!
7167                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7168                    // However...  if this package is part of a shared user, but it
7169                    // doesn't match the signature of the shared user, let's fail.
7170                    // What this means is that you can't change the signatures
7171                    // associated with an overall shared user, which doesn't seem all
7172                    // that unreasonable.
7173                    if (pkgSetting.sharedUser != null) {
7174                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7175                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7176                            throw new PackageManagerException(
7177                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7178                                            "Signature mismatch for shared user : "
7179                                            + pkgSetting.sharedUser);
7180                        }
7181                    }
7182                    // File a report about this.
7183                    String msg = "System package " + pkg.packageName
7184                        + " signature changed; retaining data.";
7185                    reportSettingsProblem(Log.WARN, msg);
7186                }
7187            }
7188            // Verify that this new package doesn't have any content providers
7189            // that conflict with existing packages.  Only do this if the
7190            // package isn't already installed, since we don't want to break
7191            // things that are installed.
7192            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7193                final int N = pkg.providers.size();
7194                int i;
7195                for (i=0; i<N; i++) {
7196                    PackageParser.Provider p = pkg.providers.get(i);
7197                    if (p.info.authority != null) {
7198                        String names[] = p.info.authority.split(";");
7199                        for (int j = 0; j < names.length; j++) {
7200                            if (mProvidersByAuthority.containsKey(names[j])) {
7201                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7202                                final String otherPackageName =
7203                                        ((other != null && other.getComponentName() != null) ?
7204                                                other.getComponentName().getPackageName() : "?");
7205                                throw new PackageManagerException(
7206                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7207                                                "Can't install because provider name " + names[j]
7208                                                + " (in package " + pkg.applicationInfo.packageName
7209                                                + ") is already used by " + otherPackageName);
7210                            }
7211                        }
7212                    }
7213                }
7214            }
7215
7216            if (pkg.mAdoptPermissions != null) {
7217                // This package wants to adopt ownership of permissions from
7218                // another package.
7219                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7220                    final String origName = pkg.mAdoptPermissions.get(i);
7221                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7222                    if (orig != null) {
7223                        if (verifyPackageUpdateLPr(orig, pkg)) {
7224                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7225                                    + pkg.packageName);
7226                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7227                        }
7228                    }
7229                }
7230            }
7231        }
7232
7233        final String pkgName = pkg.packageName;
7234
7235        final long scanFileTime = scanFile.lastModified();
7236        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7237        pkg.applicationInfo.processName = fixProcessName(
7238                pkg.applicationInfo.packageName,
7239                pkg.applicationInfo.processName,
7240                pkg.applicationInfo.uid);
7241
7242        if (pkg != mPlatformPackage) {
7243            // This is a normal package, need to make its data directory.
7244            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7245                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7246
7247            boolean uidError = false;
7248            if (dataPath.exists()) {
7249                int currentUid = 0;
7250                try {
7251                    StructStat stat = Os.stat(dataPath.getPath());
7252                    currentUid = stat.st_uid;
7253                } catch (ErrnoException e) {
7254                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7255                }
7256
7257                // If we have mismatched owners for the data path, we have a problem.
7258                if (currentUid != pkg.applicationInfo.uid) {
7259                    boolean recovered = false;
7260                    if (currentUid == 0) {
7261                        // The directory somehow became owned by root.  Wow.
7262                        // This is probably because the system was stopped while
7263                        // installd was in the middle of messing with its libs
7264                        // directory.  Ask installd to fix that.
7265                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7266                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7267                        if (ret >= 0) {
7268                            recovered = true;
7269                            String msg = "Package " + pkg.packageName
7270                                    + " unexpectedly changed to uid 0; recovered to " +
7271                                    + pkg.applicationInfo.uid;
7272                            reportSettingsProblem(Log.WARN, msg);
7273                        }
7274                    }
7275                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7276                            || (scanFlags&SCAN_BOOTING) != 0)) {
7277                        // If this is a system app, we can at least delete its
7278                        // current data so the application will still work.
7279                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7280                        if (ret >= 0) {
7281                            // TODO: Kill the processes first
7282                            // Old data gone!
7283                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7284                                    ? "System package " : "Third party package ";
7285                            String msg = prefix + pkg.packageName
7286                                    + " has changed from uid: "
7287                                    + currentUid + " to "
7288                                    + pkg.applicationInfo.uid + "; old data erased";
7289                            reportSettingsProblem(Log.WARN, msg);
7290                            recovered = true;
7291                        }
7292                        if (!recovered) {
7293                            mHasSystemUidErrors = true;
7294                        }
7295                    } else if (!recovered) {
7296                        // If we allow this install to proceed, we will be broken.
7297                        // Abort, abort!
7298                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7299                                "scanPackageLI");
7300                    }
7301                    if (!recovered) {
7302                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7303                            + pkg.applicationInfo.uid + "/fs_"
7304                            + currentUid;
7305                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7306                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7307                        String msg = "Package " + pkg.packageName
7308                                + " has mismatched uid: "
7309                                + currentUid + " on disk, "
7310                                + pkg.applicationInfo.uid + " in settings";
7311                        // writer
7312                        synchronized (mPackages) {
7313                            mSettings.mReadMessages.append(msg);
7314                            mSettings.mReadMessages.append('\n');
7315                            uidError = true;
7316                            if (!pkgSetting.uidError) {
7317                                reportSettingsProblem(Log.ERROR, msg);
7318                            }
7319                        }
7320                    }
7321                }
7322
7323                // Ensure that directories are prepared
7324                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7325                        pkg.applicationInfo.seinfo);
7326
7327                if (mShouldRestoreconData) {
7328                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7329                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7330                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7331                }
7332            } else {
7333                if (DEBUG_PACKAGE_SCANNING) {
7334                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7335                        Log.v(TAG, "Want this data dir: " + dataPath);
7336                }
7337                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7338                        pkg.applicationInfo.seinfo);
7339            }
7340
7341            // Get all of our default paths setup
7342            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7343
7344            pkgSetting.uidError = uidError;
7345        }
7346
7347        final String path = scanFile.getPath();
7348        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7349
7350        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7351            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7352
7353            // Some system apps still use directory structure for native libraries
7354            // in which case we might end up not detecting abi solely based on apk
7355            // structure. Try to detect abi based on directory structure.
7356            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7357                    pkg.applicationInfo.primaryCpuAbi == null) {
7358                setBundledAppAbisAndRoots(pkg, pkgSetting);
7359                setNativeLibraryPaths(pkg);
7360            }
7361
7362        } else {
7363            if ((scanFlags & SCAN_MOVE) != 0) {
7364                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7365                // but we already have this packages package info in the PackageSetting. We just
7366                // use that and derive the native library path based on the new codepath.
7367                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7368                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7369            }
7370
7371            // Set native library paths again. For moves, the path will be updated based on the
7372            // ABIs we've determined above. For non-moves, the path will be updated based on the
7373            // ABIs we determined during compilation, but the path will depend on the final
7374            // package path (after the rename away from the stage path).
7375            setNativeLibraryPaths(pkg);
7376        }
7377
7378        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7379        final int[] userIds = sUserManager.getUserIds();
7380        synchronized (mInstallLock) {
7381            // Make sure all user data directories are ready to roll; we're okay
7382            // if they already exist
7383            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7384                for (int userId : userIds) {
7385                    if (userId != UserHandle.USER_SYSTEM) {
7386                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7387                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7388                                pkg.applicationInfo.seinfo);
7389                    }
7390                }
7391            }
7392
7393            // Create a native library symlink only if we have native libraries
7394            // and if the native libraries are 32 bit libraries. We do not provide
7395            // this symlink for 64 bit libraries.
7396            if (pkg.applicationInfo.primaryCpuAbi != null &&
7397                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7398                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7399                try {
7400                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7401                    for (int userId : userIds) {
7402                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7403                                nativeLibPath, userId) < 0) {
7404                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7405                                    "Failed linking native library dir (user=" + userId + ")");
7406                        }
7407                    }
7408                } finally {
7409                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7410                }
7411            }
7412        }
7413
7414        // This is a special case for the "system" package, where the ABI is
7415        // dictated by the zygote configuration (and init.rc). We should keep track
7416        // of this ABI so that we can deal with "normal" applications that run under
7417        // the same UID correctly.
7418        if (mPlatformPackage == pkg) {
7419            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7420                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7421        }
7422
7423        // If there's a mismatch between the abi-override in the package setting
7424        // and the abiOverride specified for the install. Warn about this because we
7425        // would've already compiled the app without taking the package setting into
7426        // account.
7427        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7428            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7429                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7430                        " for package: " + pkg.packageName);
7431            }
7432        }
7433
7434        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7435        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7436        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7437
7438        // Copy the derived override back to the parsed package, so that we can
7439        // update the package settings accordingly.
7440        pkg.cpuAbiOverride = cpuAbiOverride;
7441
7442        if (DEBUG_ABI_SELECTION) {
7443            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7444                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7445                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7446        }
7447
7448        // Push the derived path down into PackageSettings so we know what to
7449        // clean up at uninstall time.
7450        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7451
7452        if (DEBUG_ABI_SELECTION) {
7453            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7454                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7455                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7456        }
7457
7458        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7459            // We don't do this here during boot because we can do it all
7460            // at once after scanning all existing packages.
7461            //
7462            // We also do this *before* we perform dexopt on this package, so that
7463            // we can avoid redundant dexopts, and also to make sure we've got the
7464            // code and package path correct.
7465            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7466                    pkg, true /* boot complete */);
7467        }
7468
7469        if (mFactoryTest && pkg.requestedPermissions.contains(
7470                android.Manifest.permission.FACTORY_TEST)) {
7471            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7472        }
7473
7474        ArrayList<PackageParser.Package> clientLibPkgs = null;
7475
7476        // writer
7477        synchronized (mPackages) {
7478            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7479                // Only system apps can add new shared libraries.
7480                if (pkg.libraryNames != null) {
7481                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7482                        String name = pkg.libraryNames.get(i);
7483                        boolean allowed = false;
7484                        if (pkg.isUpdatedSystemApp()) {
7485                            // New library entries can only be added through the
7486                            // system image.  This is important to get rid of a lot
7487                            // of nasty edge cases: for example if we allowed a non-
7488                            // system update of the app to add a library, then uninstalling
7489                            // the update would make the library go away, and assumptions
7490                            // we made such as through app install filtering would now
7491                            // have allowed apps on the device which aren't compatible
7492                            // with it.  Better to just have the restriction here, be
7493                            // conservative, and create many fewer cases that can negatively
7494                            // impact the user experience.
7495                            final PackageSetting sysPs = mSettings
7496                                    .getDisabledSystemPkgLPr(pkg.packageName);
7497                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7498                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7499                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7500                                        allowed = true;
7501                                        break;
7502                                    }
7503                                }
7504                            }
7505                        } else {
7506                            allowed = true;
7507                        }
7508                        if (allowed) {
7509                            if (!mSharedLibraries.containsKey(name)) {
7510                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7511                            } else if (!name.equals(pkg.packageName)) {
7512                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7513                                        + name + " already exists; skipping");
7514                            }
7515                        } else {
7516                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7517                                    + name + " that is not declared on system image; skipping");
7518                        }
7519                    }
7520                    if ((scanFlags & SCAN_BOOTING) == 0) {
7521                        // If we are not booting, we need to update any applications
7522                        // that are clients of our shared library.  If we are booting,
7523                        // this will all be done once the scan is complete.
7524                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7525                    }
7526                }
7527            }
7528        }
7529
7530        // Request the ActivityManager to kill the process(only for existing packages)
7531        // so that we do not end up in a confused state while the user is still using the older
7532        // version of the application while the new one gets installed.
7533        if ((scanFlags & SCAN_REPLACING) != 0) {
7534            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7535
7536            killApplication(pkg.applicationInfo.packageName,
7537                        pkg.applicationInfo.uid, "replace pkg");
7538
7539            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7540        }
7541
7542        // Also need to kill any apps that are dependent on the library.
7543        if (clientLibPkgs != null) {
7544            for (int i=0; i<clientLibPkgs.size(); i++) {
7545                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7546                killApplication(clientPkg.applicationInfo.packageName,
7547                        clientPkg.applicationInfo.uid, "update lib");
7548            }
7549        }
7550
7551        // Make sure we're not adding any bogus keyset info
7552        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7553        ksms.assertScannedPackageValid(pkg);
7554
7555        // writer
7556        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7557
7558        boolean createIdmapFailed = false;
7559        synchronized (mPackages) {
7560            // We don't expect installation to fail beyond this point
7561
7562            // Add the new setting to mSettings
7563            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7564            // Add the new setting to mPackages
7565            mPackages.put(pkg.applicationInfo.packageName, pkg);
7566            // Make sure we don't accidentally delete its data.
7567            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7568            while (iter.hasNext()) {
7569                PackageCleanItem item = iter.next();
7570                if (pkgName.equals(item.packageName)) {
7571                    iter.remove();
7572                }
7573            }
7574
7575            // Take care of first install / last update times.
7576            if (currentTime != 0) {
7577                if (pkgSetting.firstInstallTime == 0) {
7578                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7579                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7580                    pkgSetting.lastUpdateTime = currentTime;
7581                }
7582            } else if (pkgSetting.firstInstallTime == 0) {
7583                // We need *something*.  Take time time stamp of the file.
7584                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7585            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7586                if (scanFileTime != pkgSetting.timeStamp) {
7587                    // A package on the system image has changed; consider this
7588                    // to be an update.
7589                    pkgSetting.lastUpdateTime = scanFileTime;
7590                }
7591            }
7592
7593            // Add the package's KeySets to the global KeySetManagerService
7594            ksms.addScannedPackageLPw(pkg);
7595
7596            int N = pkg.providers.size();
7597            StringBuilder r = null;
7598            int i;
7599            for (i=0; i<N; i++) {
7600                PackageParser.Provider p = pkg.providers.get(i);
7601                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7602                        p.info.processName, pkg.applicationInfo.uid);
7603                mProviders.addProvider(p);
7604                p.syncable = p.info.isSyncable;
7605                if (p.info.authority != null) {
7606                    String names[] = p.info.authority.split(";");
7607                    p.info.authority = null;
7608                    for (int j = 0; j < names.length; j++) {
7609                        if (j == 1 && p.syncable) {
7610                            // We only want the first authority for a provider to possibly be
7611                            // syncable, so if we already added this provider using a different
7612                            // authority clear the syncable flag. We copy the provider before
7613                            // changing it because the mProviders object contains a reference
7614                            // to a provider that we don't want to change.
7615                            // Only do this for the second authority since the resulting provider
7616                            // object can be the same for all future authorities for this provider.
7617                            p = new PackageParser.Provider(p);
7618                            p.syncable = false;
7619                        }
7620                        if (!mProvidersByAuthority.containsKey(names[j])) {
7621                            mProvidersByAuthority.put(names[j], p);
7622                            if (p.info.authority == null) {
7623                                p.info.authority = names[j];
7624                            } else {
7625                                p.info.authority = p.info.authority + ";" + names[j];
7626                            }
7627                            if (DEBUG_PACKAGE_SCANNING) {
7628                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7629                                    Log.d(TAG, "Registered content provider: " + names[j]
7630                                            + ", className = " + p.info.name + ", isSyncable = "
7631                                            + p.info.isSyncable);
7632                            }
7633                        } else {
7634                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7635                            Slog.w(TAG, "Skipping provider name " + names[j] +
7636                                    " (in package " + pkg.applicationInfo.packageName +
7637                                    "): name already used by "
7638                                    + ((other != null && other.getComponentName() != null)
7639                                            ? other.getComponentName().getPackageName() : "?"));
7640                        }
7641                    }
7642                }
7643                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7644                    if (r == null) {
7645                        r = new StringBuilder(256);
7646                    } else {
7647                        r.append(' ');
7648                    }
7649                    r.append(p.info.name);
7650                }
7651            }
7652            if (r != null) {
7653                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7654            }
7655
7656            N = pkg.services.size();
7657            r = null;
7658            for (i=0; i<N; i++) {
7659                PackageParser.Service s = pkg.services.get(i);
7660                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7661                        s.info.processName, pkg.applicationInfo.uid);
7662                mServices.addService(s);
7663                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7664                    if (r == null) {
7665                        r = new StringBuilder(256);
7666                    } else {
7667                        r.append(' ');
7668                    }
7669                    r.append(s.info.name);
7670                }
7671            }
7672            if (r != null) {
7673                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7674            }
7675
7676            N = pkg.receivers.size();
7677            r = null;
7678            for (i=0; i<N; i++) {
7679                PackageParser.Activity a = pkg.receivers.get(i);
7680                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7681                        a.info.processName, pkg.applicationInfo.uid);
7682                mReceivers.addActivity(a, "receiver");
7683                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7684                    if (r == null) {
7685                        r = new StringBuilder(256);
7686                    } else {
7687                        r.append(' ');
7688                    }
7689                    r.append(a.info.name);
7690                }
7691            }
7692            if (r != null) {
7693                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7694            }
7695
7696            N = pkg.activities.size();
7697            r = null;
7698            for (i=0; i<N; i++) {
7699                PackageParser.Activity a = pkg.activities.get(i);
7700                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7701                        a.info.processName, pkg.applicationInfo.uid);
7702                mActivities.addActivity(a, "activity");
7703                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7704                    if (r == null) {
7705                        r = new StringBuilder(256);
7706                    } else {
7707                        r.append(' ');
7708                    }
7709                    r.append(a.info.name);
7710                }
7711            }
7712            if (r != null) {
7713                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7714            }
7715
7716            N = pkg.permissionGroups.size();
7717            r = null;
7718            for (i=0; i<N; i++) {
7719                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7720                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7721                if (cur == null) {
7722                    mPermissionGroups.put(pg.info.name, pg);
7723                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7724                        if (r == null) {
7725                            r = new StringBuilder(256);
7726                        } else {
7727                            r.append(' ');
7728                        }
7729                        r.append(pg.info.name);
7730                    }
7731                } else {
7732                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7733                            + pg.info.packageName + " ignored: original from "
7734                            + cur.info.packageName);
7735                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7736                        if (r == null) {
7737                            r = new StringBuilder(256);
7738                        } else {
7739                            r.append(' ');
7740                        }
7741                        r.append("DUP:");
7742                        r.append(pg.info.name);
7743                    }
7744                }
7745            }
7746            if (r != null) {
7747                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7748            }
7749
7750            N = pkg.permissions.size();
7751            r = null;
7752            for (i=0; i<N; i++) {
7753                PackageParser.Permission p = pkg.permissions.get(i);
7754
7755                // Assume by default that we did not install this permission into the system.
7756                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7757
7758                // Now that permission groups have a special meaning, we ignore permission
7759                // groups for legacy apps to prevent unexpected behavior. In particular,
7760                // permissions for one app being granted to someone just becuase they happen
7761                // to be in a group defined by another app (before this had no implications).
7762                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7763                    p.group = mPermissionGroups.get(p.info.group);
7764                    // Warn for a permission in an unknown group.
7765                    if (p.info.group != null && p.group == null) {
7766                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7767                                + p.info.packageName + " in an unknown group " + p.info.group);
7768                    }
7769                }
7770
7771                ArrayMap<String, BasePermission> permissionMap =
7772                        p.tree ? mSettings.mPermissionTrees
7773                                : mSettings.mPermissions;
7774                BasePermission bp = permissionMap.get(p.info.name);
7775
7776                // Allow system apps to redefine non-system permissions
7777                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7778                    final boolean currentOwnerIsSystem = (bp.perm != null
7779                            && isSystemApp(bp.perm.owner));
7780                    if (isSystemApp(p.owner)) {
7781                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7782                            // It's a built-in permission and no owner, take ownership now
7783                            bp.packageSetting = pkgSetting;
7784                            bp.perm = p;
7785                            bp.uid = pkg.applicationInfo.uid;
7786                            bp.sourcePackage = p.info.packageName;
7787                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7788                        } else if (!currentOwnerIsSystem) {
7789                            String msg = "New decl " + p.owner + " of permission  "
7790                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7791                            reportSettingsProblem(Log.WARN, msg);
7792                            bp = null;
7793                        }
7794                    }
7795                }
7796
7797                if (bp == null) {
7798                    bp = new BasePermission(p.info.name, p.info.packageName,
7799                            BasePermission.TYPE_NORMAL);
7800                    permissionMap.put(p.info.name, bp);
7801                }
7802
7803                if (bp.perm == null) {
7804                    if (bp.sourcePackage == null
7805                            || bp.sourcePackage.equals(p.info.packageName)) {
7806                        BasePermission tree = findPermissionTreeLP(p.info.name);
7807                        if (tree == null
7808                                || tree.sourcePackage.equals(p.info.packageName)) {
7809                            bp.packageSetting = pkgSetting;
7810                            bp.perm = p;
7811                            bp.uid = pkg.applicationInfo.uid;
7812                            bp.sourcePackage = p.info.packageName;
7813                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7814                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7815                                if (r == null) {
7816                                    r = new StringBuilder(256);
7817                                } else {
7818                                    r.append(' ');
7819                                }
7820                                r.append(p.info.name);
7821                            }
7822                        } else {
7823                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7824                                    + p.info.packageName + " ignored: base tree "
7825                                    + tree.name + " is from package "
7826                                    + tree.sourcePackage);
7827                        }
7828                    } else {
7829                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7830                                + p.info.packageName + " ignored: original from "
7831                                + bp.sourcePackage);
7832                    }
7833                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7834                    if (r == null) {
7835                        r = new StringBuilder(256);
7836                    } else {
7837                        r.append(' ');
7838                    }
7839                    r.append("DUP:");
7840                    r.append(p.info.name);
7841                }
7842                if (bp.perm == p) {
7843                    bp.protectionLevel = p.info.protectionLevel;
7844                }
7845            }
7846
7847            if (r != null) {
7848                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7849            }
7850
7851            N = pkg.instrumentation.size();
7852            r = null;
7853            for (i=0; i<N; i++) {
7854                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7855                a.info.packageName = pkg.applicationInfo.packageName;
7856                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7857                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7858                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7859                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7860                a.info.dataDir = pkg.applicationInfo.dataDir;
7861                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7862                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7863
7864                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7865                // need other information about the application, like the ABI and what not ?
7866                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7867                mInstrumentation.put(a.getComponentName(), a);
7868                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7869                    if (r == null) {
7870                        r = new StringBuilder(256);
7871                    } else {
7872                        r.append(' ');
7873                    }
7874                    r.append(a.info.name);
7875                }
7876            }
7877            if (r != null) {
7878                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7879            }
7880
7881            if (pkg.protectedBroadcasts != null) {
7882                N = pkg.protectedBroadcasts.size();
7883                for (i=0; i<N; i++) {
7884                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7885                }
7886            }
7887
7888            pkgSetting.setTimeStamp(scanFileTime);
7889
7890            // Create idmap files for pairs of (packages, overlay packages).
7891            // Note: "android", ie framework-res.apk, is handled by native layers.
7892            if (pkg.mOverlayTarget != null) {
7893                // This is an overlay package.
7894                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7895                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7896                        mOverlays.put(pkg.mOverlayTarget,
7897                                new ArrayMap<String, PackageParser.Package>());
7898                    }
7899                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7900                    map.put(pkg.packageName, pkg);
7901                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7902                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7903                        createIdmapFailed = true;
7904                    }
7905                }
7906            } else if (mOverlays.containsKey(pkg.packageName) &&
7907                    !pkg.packageName.equals("android")) {
7908                // This is a regular package, with one or more known overlay packages.
7909                createIdmapsForPackageLI(pkg);
7910            }
7911        }
7912
7913        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7914
7915        if (createIdmapFailed) {
7916            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7917                    "scanPackageLI failed to createIdmap");
7918        }
7919        return pkg;
7920    }
7921
7922    /**
7923     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7924     * is derived purely on the basis of the contents of {@code scanFile} and
7925     * {@code cpuAbiOverride}.
7926     *
7927     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7928     */
7929    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7930                                 String cpuAbiOverride, boolean extractLibs)
7931            throws PackageManagerException {
7932        // TODO: We can probably be smarter about this stuff. For installed apps,
7933        // we can calculate this information at install time once and for all. For
7934        // system apps, we can probably assume that this information doesn't change
7935        // after the first boot scan. As things stand, we do lots of unnecessary work.
7936
7937        // Give ourselves some initial paths; we'll come back for another
7938        // pass once we've determined ABI below.
7939        setNativeLibraryPaths(pkg);
7940
7941        // We would never need to extract libs for forward-locked and external packages,
7942        // since the container service will do it for us. We shouldn't attempt to
7943        // extract libs from system app when it was not updated.
7944        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7945                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7946            extractLibs = false;
7947        }
7948
7949        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7950        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7951
7952        NativeLibraryHelper.Handle handle = null;
7953        try {
7954            handle = NativeLibraryHelper.Handle.create(pkg);
7955            // TODO(multiArch): This can be null for apps that didn't go through the
7956            // usual installation process. We can calculate it again, like we
7957            // do during install time.
7958            //
7959            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7960            // unnecessary.
7961            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7962
7963            // Null out the abis so that they can be recalculated.
7964            pkg.applicationInfo.primaryCpuAbi = null;
7965            pkg.applicationInfo.secondaryCpuAbi = null;
7966            if (isMultiArch(pkg.applicationInfo)) {
7967                // Warn if we've set an abiOverride for multi-lib packages..
7968                // By definition, we need to copy both 32 and 64 bit libraries for
7969                // such packages.
7970                if (pkg.cpuAbiOverride != null
7971                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7972                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7973                }
7974
7975                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7976                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7977                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7978                    if (extractLibs) {
7979                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7980                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7981                                useIsaSpecificSubdirs);
7982                    } else {
7983                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7984                    }
7985                }
7986
7987                maybeThrowExceptionForMultiArchCopy(
7988                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7989
7990                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7991                    if (extractLibs) {
7992                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7993                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7994                                useIsaSpecificSubdirs);
7995                    } else {
7996                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7997                    }
7998                }
7999
8000                maybeThrowExceptionForMultiArchCopy(
8001                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8002
8003                if (abi64 >= 0) {
8004                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8005                }
8006
8007                if (abi32 >= 0) {
8008                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8009                    if (abi64 >= 0) {
8010                        pkg.applicationInfo.secondaryCpuAbi = abi;
8011                    } else {
8012                        pkg.applicationInfo.primaryCpuAbi = abi;
8013                    }
8014                }
8015            } else {
8016                String[] abiList = (cpuAbiOverride != null) ?
8017                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8018
8019                // Enable gross and lame hacks for apps that are built with old
8020                // SDK tools. We must scan their APKs for renderscript bitcode and
8021                // not launch them if it's present. Don't bother checking on devices
8022                // that don't have 64 bit support.
8023                boolean needsRenderScriptOverride = false;
8024                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8025                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8026                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8027                    needsRenderScriptOverride = true;
8028                }
8029
8030                final int copyRet;
8031                if (extractLibs) {
8032                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8033                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8034                } else {
8035                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8036                }
8037
8038                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8039                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8040                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8041                }
8042
8043                if (copyRet >= 0) {
8044                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8045                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8046                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8047                } else if (needsRenderScriptOverride) {
8048                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8049                }
8050            }
8051        } catch (IOException ioe) {
8052            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8053        } finally {
8054            IoUtils.closeQuietly(handle);
8055        }
8056
8057        // Now that we've calculated the ABIs and determined if it's an internal app,
8058        // we will go ahead and populate the nativeLibraryPath.
8059        setNativeLibraryPaths(pkg);
8060    }
8061
8062    /**
8063     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8064     * i.e, so that all packages can be run inside a single process if required.
8065     *
8066     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8067     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8068     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8069     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8070     * updating a package that belongs to a shared user.
8071     *
8072     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8073     * adds unnecessary complexity.
8074     */
8075    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8076            PackageParser.Package scannedPackage, boolean bootComplete) {
8077        String requiredInstructionSet = null;
8078        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8079            requiredInstructionSet = VMRuntime.getInstructionSet(
8080                     scannedPackage.applicationInfo.primaryCpuAbi);
8081        }
8082
8083        PackageSetting requirer = null;
8084        for (PackageSetting ps : packagesForUser) {
8085            // If packagesForUser contains scannedPackage, we skip it. This will happen
8086            // when scannedPackage is an update of an existing package. Without this check,
8087            // we will never be able to change the ABI of any package belonging to a shared
8088            // user, even if it's compatible with other packages.
8089            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8090                if (ps.primaryCpuAbiString == null) {
8091                    continue;
8092                }
8093
8094                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8095                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8096                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8097                    // this but there's not much we can do.
8098                    String errorMessage = "Instruction set mismatch, "
8099                            + ((requirer == null) ? "[caller]" : requirer)
8100                            + " requires " + requiredInstructionSet + " whereas " + ps
8101                            + " requires " + instructionSet;
8102                    Slog.w(TAG, errorMessage);
8103                }
8104
8105                if (requiredInstructionSet == null) {
8106                    requiredInstructionSet = instructionSet;
8107                    requirer = ps;
8108                }
8109            }
8110        }
8111
8112        if (requiredInstructionSet != null) {
8113            String adjustedAbi;
8114            if (requirer != null) {
8115                // requirer != null implies that either scannedPackage was null or that scannedPackage
8116                // did not require an ABI, in which case we have to adjust scannedPackage to match
8117                // the ABI of the set (which is the same as requirer's ABI)
8118                adjustedAbi = requirer.primaryCpuAbiString;
8119                if (scannedPackage != null) {
8120                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8121                }
8122            } else {
8123                // requirer == null implies that we're updating all ABIs in the set to
8124                // match scannedPackage.
8125                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8126            }
8127
8128            for (PackageSetting ps : packagesForUser) {
8129                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8130                    if (ps.primaryCpuAbiString != null) {
8131                        continue;
8132                    }
8133
8134                    ps.primaryCpuAbiString = adjustedAbi;
8135                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8136                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8137                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
8138                        mInstaller.rmdex(ps.codePathString,
8139                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8140                    }
8141                }
8142            }
8143        }
8144    }
8145
8146    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8147        synchronized (mPackages) {
8148            mResolverReplaced = true;
8149            // Set up information for custom user intent resolution activity.
8150            mResolveActivity.applicationInfo = pkg.applicationInfo;
8151            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8152            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8153            mResolveActivity.processName = pkg.applicationInfo.packageName;
8154            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8155            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8156                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8157            mResolveActivity.theme = 0;
8158            mResolveActivity.exported = true;
8159            mResolveActivity.enabled = true;
8160            mResolveInfo.activityInfo = mResolveActivity;
8161            mResolveInfo.priority = 0;
8162            mResolveInfo.preferredOrder = 0;
8163            mResolveInfo.match = 0;
8164            mResolveComponentName = mCustomResolverComponentName;
8165            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8166                    mResolveComponentName);
8167        }
8168    }
8169
8170    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8171        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8172
8173        // Set up information for ephemeral installer activity
8174        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8175        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8176        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8177        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8178        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8179        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8180                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8181        mEphemeralInstallerActivity.theme = 0;
8182        mEphemeralInstallerActivity.exported = true;
8183        mEphemeralInstallerActivity.enabled = true;
8184        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8185        mEphemeralInstallerInfo.priority = 0;
8186        mEphemeralInstallerInfo.preferredOrder = 0;
8187        mEphemeralInstallerInfo.match = 0;
8188
8189        if (DEBUG_EPHEMERAL) {
8190            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8191        }
8192    }
8193
8194    private static String calculateBundledApkRoot(final String codePathString) {
8195        final File codePath = new File(codePathString);
8196        final File codeRoot;
8197        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8198            codeRoot = Environment.getRootDirectory();
8199        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8200            codeRoot = Environment.getOemDirectory();
8201        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8202            codeRoot = Environment.getVendorDirectory();
8203        } else {
8204            // Unrecognized code path; take its top real segment as the apk root:
8205            // e.g. /something/app/blah.apk => /something
8206            try {
8207                File f = codePath.getCanonicalFile();
8208                File parent = f.getParentFile();    // non-null because codePath is a file
8209                File tmp;
8210                while ((tmp = parent.getParentFile()) != null) {
8211                    f = parent;
8212                    parent = tmp;
8213                }
8214                codeRoot = f;
8215                Slog.w(TAG, "Unrecognized code path "
8216                        + codePath + " - using " + codeRoot);
8217            } catch (IOException e) {
8218                // Can't canonicalize the code path -- shenanigans?
8219                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8220                return Environment.getRootDirectory().getPath();
8221            }
8222        }
8223        return codeRoot.getPath();
8224    }
8225
8226    /**
8227     * Derive and set the location of native libraries for the given package,
8228     * which varies depending on where and how the package was installed.
8229     */
8230    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8231        final ApplicationInfo info = pkg.applicationInfo;
8232        final String codePath = pkg.codePath;
8233        final File codeFile = new File(codePath);
8234        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8235        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8236
8237        info.nativeLibraryRootDir = null;
8238        info.nativeLibraryRootRequiresIsa = false;
8239        info.nativeLibraryDir = null;
8240        info.secondaryNativeLibraryDir = null;
8241
8242        if (isApkFile(codeFile)) {
8243            // Monolithic install
8244            if (bundledApp) {
8245                // If "/system/lib64/apkname" exists, assume that is the per-package
8246                // native library directory to use; otherwise use "/system/lib/apkname".
8247                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8248                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8249                        getPrimaryInstructionSet(info));
8250
8251                // This is a bundled system app so choose the path based on the ABI.
8252                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8253                // is just the default path.
8254                final String apkName = deriveCodePathName(codePath);
8255                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8256                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8257                        apkName).getAbsolutePath();
8258
8259                if (info.secondaryCpuAbi != null) {
8260                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8261                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8262                            secondaryLibDir, apkName).getAbsolutePath();
8263                }
8264            } else if (asecApp) {
8265                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8266                        .getAbsolutePath();
8267            } else {
8268                final String apkName = deriveCodePathName(codePath);
8269                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8270                        .getAbsolutePath();
8271            }
8272
8273            info.nativeLibraryRootRequiresIsa = false;
8274            info.nativeLibraryDir = info.nativeLibraryRootDir;
8275        } else {
8276            // Cluster install
8277            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8278            info.nativeLibraryRootRequiresIsa = true;
8279
8280            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8281                    getPrimaryInstructionSet(info)).getAbsolutePath();
8282
8283            if (info.secondaryCpuAbi != null) {
8284                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8285                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8286            }
8287        }
8288    }
8289
8290    /**
8291     * Calculate the abis and roots for a bundled app. These can uniquely
8292     * be determined from the contents of the system partition, i.e whether
8293     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8294     * of this information, and instead assume that the system was built
8295     * sensibly.
8296     */
8297    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8298                                           PackageSetting pkgSetting) {
8299        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8300
8301        // If "/system/lib64/apkname" exists, assume that is the per-package
8302        // native library directory to use; otherwise use "/system/lib/apkname".
8303        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8304        setBundledAppAbi(pkg, apkRoot, apkName);
8305        // pkgSetting might be null during rescan following uninstall of updates
8306        // to a bundled app, so accommodate that possibility.  The settings in
8307        // that case will be established later from the parsed package.
8308        //
8309        // If the settings aren't null, sync them up with what we've just derived.
8310        // note that apkRoot isn't stored in the package settings.
8311        if (pkgSetting != null) {
8312            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8313            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8314        }
8315    }
8316
8317    /**
8318     * Deduces the ABI of a bundled app and sets the relevant fields on the
8319     * parsed pkg object.
8320     *
8321     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8322     *        under which system libraries are installed.
8323     * @param apkName the name of the installed package.
8324     */
8325    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8326        final File codeFile = new File(pkg.codePath);
8327
8328        final boolean has64BitLibs;
8329        final boolean has32BitLibs;
8330        if (isApkFile(codeFile)) {
8331            // Monolithic install
8332            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8333            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8334        } else {
8335            // Cluster install
8336            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8337            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8338                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8339                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8340                has64BitLibs = (new File(rootDir, isa)).exists();
8341            } else {
8342                has64BitLibs = false;
8343            }
8344            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8345                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8346                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8347                has32BitLibs = (new File(rootDir, isa)).exists();
8348            } else {
8349                has32BitLibs = false;
8350            }
8351        }
8352
8353        if (has64BitLibs && !has32BitLibs) {
8354            // The package has 64 bit libs, but not 32 bit libs. Its primary
8355            // ABI should be 64 bit. We can safely assume here that the bundled
8356            // native libraries correspond to the most preferred ABI in the list.
8357
8358            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8359            pkg.applicationInfo.secondaryCpuAbi = null;
8360        } else if (has32BitLibs && !has64BitLibs) {
8361            // The package has 32 bit libs but not 64 bit libs. Its primary
8362            // ABI should be 32 bit.
8363
8364            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8365            pkg.applicationInfo.secondaryCpuAbi = null;
8366        } else if (has32BitLibs && has64BitLibs) {
8367            // The application has both 64 and 32 bit bundled libraries. We check
8368            // here that the app declares multiArch support, and warn if it doesn't.
8369            //
8370            // We will be lenient here and record both ABIs. The primary will be the
8371            // ABI that's higher on the list, i.e, a device that's configured to prefer
8372            // 64 bit apps will see a 64 bit primary ABI,
8373
8374            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8375                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8376            }
8377
8378            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8379                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8380                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8381            } else {
8382                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8383                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8384            }
8385        } else {
8386            pkg.applicationInfo.primaryCpuAbi = null;
8387            pkg.applicationInfo.secondaryCpuAbi = null;
8388        }
8389    }
8390
8391    private void killApplication(String pkgName, int appId, String reason) {
8392        // Request the ActivityManager to kill the process(only for existing packages)
8393        // so that we do not end up in a confused state while the user is still using the older
8394        // version of the application while the new one gets installed.
8395        IActivityManager am = ActivityManagerNative.getDefault();
8396        if (am != null) {
8397            try {
8398                am.killApplicationWithAppId(pkgName, appId, reason);
8399            } catch (RemoteException e) {
8400            }
8401        }
8402    }
8403
8404    void removePackageLI(PackageSetting ps, boolean chatty) {
8405        if (DEBUG_INSTALL) {
8406            if (chatty)
8407                Log.d(TAG, "Removing package " + ps.name);
8408        }
8409
8410        // writer
8411        synchronized (mPackages) {
8412            mPackages.remove(ps.name);
8413            final PackageParser.Package pkg = ps.pkg;
8414            if (pkg != null) {
8415                cleanPackageDataStructuresLILPw(pkg, chatty);
8416            }
8417        }
8418    }
8419
8420    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8421        if (DEBUG_INSTALL) {
8422            if (chatty)
8423                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8424        }
8425
8426        // writer
8427        synchronized (mPackages) {
8428            mPackages.remove(pkg.applicationInfo.packageName);
8429            cleanPackageDataStructuresLILPw(pkg, chatty);
8430        }
8431    }
8432
8433    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8434        int N = pkg.providers.size();
8435        StringBuilder r = null;
8436        int i;
8437        for (i=0; i<N; i++) {
8438            PackageParser.Provider p = pkg.providers.get(i);
8439            mProviders.removeProvider(p);
8440            if (p.info.authority == null) {
8441
8442                /* There was another ContentProvider with this authority when
8443                 * this app was installed so this authority is null,
8444                 * Ignore it as we don't have to unregister the provider.
8445                 */
8446                continue;
8447            }
8448            String names[] = p.info.authority.split(";");
8449            for (int j = 0; j < names.length; j++) {
8450                if (mProvidersByAuthority.get(names[j]) == p) {
8451                    mProvidersByAuthority.remove(names[j]);
8452                    if (DEBUG_REMOVE) {
8453                        if (chatty)
8454                            Log.d(TAG, "Unregistered content provider: " + names[j]
8455                                    + ", className = " + p.info.name + ", isSyncable = "
8456                                    + p.info.isSyncable);
8457                    }
8458                }
8459            }
8460            if (DEBUG_REMOVE && chatty) {
8461                if (r == null) {
8462                    r = new StringBuilder(256);
8463                } else {
8464                    r.append(' ');
8465                }
8466                r.append(p.info.name);
8467            }
8468        }
8469        if (r != null) {
8470            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8471        }
8472
8473        N = pkg.services.size();
8474        r = null;
8475        for (i=0; i<N; i++) {
8476            PackageParser.Service s = pkg.services.get(i);
8477            mServices.removeService(s);
8478            if (chatty) {
8479                if (r == null) {
8480                    r = new StringBuilder(256);
8481                } else {
8482                    r.append(' ');
8483                }
8484                r.append(s.info.name);
8485            }
8486        }
8487        if (r != null) {
8488            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8489        }
8490
8491        N = pkg.receivers.size();
8492        r = null;
8493        for (i=0; i<N; i++) {
8494            PackageParser.Activity a = pkg.receivers.get(i);
8495            mReceivers.removeActivity(a, "receiver");
8496            if (DEBUG_REMOVE && chatty) {
8497                if (r == null) {
8498                    r = new StringBuilder(256);
8499                } else {
8500                    r.append(' ');
8501                }
8502                r.append(a.info.name);
8503            }
8504        }
8505        if (r != null) {
8506            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8507        }
8508
8509        N = pkg.activities.size();
8510        r = null;
8511        for (i=0; i<N; i++) {
8512            PackageParser.Activity a = pkg.activities.get(i);
8513            mActivities.removeActivity(a, "activity");
8514            if (DEBUG_REMOVE && chatty) {
8515                if (r == null) {
8516                    r = new StringBuilder(256);
8517                } else {
8518                    r.append(' ');
8519                }
8520                r.append(a.info.name);
8521            }
8522        }
8523        if (r != null) {
8524            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8525        }
8526
8527        N = pkg.permissions.size();
8528        r = null;
8529        for (i=0; i<N; i++) {
8530            PackageParser.Permission p = pkg.permissions.get(i);
8531            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8532            if (bp == null) {
8533                bp = mSettings.mPermissionTrees.get(p.info.name);
8534            }
8535            if (bp != null && bp.perm == p) {
8536                bp.perm = null;
8537                if (DEBUG_REMOVE && chatty) {
8538                    if (r == null) {
8539                        r = new StringBuilder(256);
8540                    } else {
8541                        r.append(' ');
8542                    }
8543                    r.append(p.info.name);
8544                }
8545            }
8546            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8547                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8548                if (appOpPkgs != null) {
8549                    appOpPkgs.remove(pkg.packageName);
8550                }
8551            }
8552        }
8553        if (r != null) {
8554            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8555        }
8556
8557        N = pkg.requestedPermissions.size();
8558        r = null;
8559        for (i=0; i<N; i++) {
8560            String perm = pkg.requestedPermissions.get(i);
8561            BasePermission bp = mSettings.mPermissions.get(perm);
8562            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8563                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8564                if (appOpPkgs != null) {
8565                    appOpPkgs.remove(pkg.packageName);
8566                    if (appOpPkgs.isEmpty()) {
8567                        mAppOpPermissionPackages.remove(perm);
8568                    }
8569                }
8570            }
8571        }
8572        if (r != null) {
8573            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8574        }
8575
8576        N = pkg.instrumentation.size();
8577        r = null;
8578        for (i=0; i<N; i++) {
8579            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8580            mInstrumentation.remove(a.getComponentName());
8581            if (DEBUG_REMOVE && chatty) {
8582                if (r == null) {
8583                    r = new StringBuilder(256);
8584                } else {
8585                    r.append(' ');
8586                }
8587                r.append(a.info.name);
8588            }
8589        }
8590        if (r != null) {
8591            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8592        }
8593
8594        r = null;
8595        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8596            // Only system apps can hold shared libraries.
8597            if (pkg.libraryNames != null) {
8598                for (i=0; i<pkg.libraryNames.size(); i++) {
8599                    String name = pkg.libraryNames.get(i);
8600                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8601                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8602                        mSharedLibraries.remove(name);
8603                        if (DEBUG_REMOVE && chatty) {
8604                            if (r == null) {
8605                                r = new StringBuilder(256);
8606                            } else {
8607                                r.append(' ');
8608                            }
8609                            r.append(name);
8610                        }
8611                    }
8612                }
8613            }
8614        }
8615        if (r != null) {
8616            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8617        }
8618    }
8619
8620    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8621        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8622            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8623                return true;
8624            }
8625        }
8626        return false;
8627    }
8628
8629    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8630    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8631    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8632
8633    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8634            int flags) {
8635        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8636        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8637    }
8638
8639    private void updatePermissionsLPw(String changingPkg,
8640            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8641        // Make sure there are no dangling permission trees.
8642        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8643        while (it.hasNext()) {
8644            final BasePermission bp = it.next();
8645            if (bp.packageSetting == null) {
8646                // We may not yet have parsed the package, so just see if
8647                // we still know about its settings.
8648                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8649            }
8650            if (bp.packageSetting == null) {
8651                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8652                        + " from package " + bp.sourcePackage);
8653                it.remove();
8654            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8655                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8656                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8657                            + " from package " + bp.sourcePackage);
8658                    flags |= UPDATE_PERMISSIONS_ALL;
8659                    it.remove();
8660                }
8661            }
8662        }
8663
8664        // Make sure all dynamic permissions have been assigned to a package,
8665        // and make sure there are no dangling permissions.
8666        it = mSettings.mPermissions.values().iterator();
8667        while (it.hasNext()) {
8668            final BasePermission bp = it.next();
8669            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8670                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8671                        + bp.name + " pkg=" + bp.sourcePackage
8672                        + " info=" + bp.pendingInfo);
8673                if (bp.packageSetting == null && bp.pendingInfo != null) {
8674                    final BasePermission tree = findPermissionTreeLP(bp.name);
8675                    if (tree != null && tree.perm != null) {
8676                        bp.packageSetting = tree.packageSetting;
8677                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8678                                new PermissionInfo(bp.pendingInfo));
8679                        bp.perm.info.packageName = tree.perm.info.packageName;
8680                        bp.perm.info.name = bp.name;
8681                        bp.uid = tree.uid;
8682                    }
8683                }
8684            }
8685            if (bp.packageSetting == null) {
8686                // We may not yet have parsed the package, so just see if
8687                // we still know about its settings.
8688                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8689            }
8690            if (bp.packageSetting == null) {
8691                Slog.w(TAG, "Removing dangling permission: " + bp.name
8692                        + " from package " + bp.sourcePackage);
8693                it.remove();
8694            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8695                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8696                    Slog.i(TAG, "Removing old permission: " + bp.name
8697                            + " from package " + bp.sourcePackage);
8698                    flags |= UPDATE_PERMISSIONS_ALL;
8699                    it.remove();
8700                }
8701            }
8702        }
8703
8704        // Now update the permissions for all packages, in particular
8705        // replace the granted permissions of the system packages.
8706        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8707            for (PackageParser.Package pkg : mPackages.values()) {
8708                if (pkg != pkgInfo) {
8709                    // Only replace for packages on requested volume
8710                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8711                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8712                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8713                    grantPermissionsLPw(pkg, replace, changingPkg);
8714                }
8715            }
8716        }
8717
8718        if (pkgInfo != null) {
8719            // Only replace for packages on requested volume
8720            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8721            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8722                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8723            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8724        }
8725    }
8726
8727    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8728            String packageOfInterest) {
8729        // IMPORTANT: There are two types of permissions: install and runtime.
8730        // Install time permissions are granted when the app is installed to
8731        // all device users and users added in the future. Runtime permissions
8732        // are granted at runtime explicitly to specific users. Normal and signature
8733        // protected permissions are install time permissions. Dangerous permissions
8734        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8735        // otherwise they are runtime permissions. This function does not manage
8736        // runtime permissions except for the case an app targeting Lollipop MR1
8737        // being upgraded to target a newer SDK, in which case dangerous permissions
8738        // are transformed from install time to runtime ones.
8739
8740        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8741        if (ps == null) {
8742            return;
8743        }
8744
8745        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8746
8747        PermissionsState permissionsState = ps.getPermissionsState();
8748        PermissionsState origPermissions = permissionsState;
8749
8750        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8751
8752        boolean runtimePermissionsRevoked = false;
8753        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8754
8755        boolean changedInstallPermission = false;
8756
8757        if (replace) {
8758            ps.installPermissionsFixed = false;
8759            if (!ps.isSharedUser()) {
8760                origPermissions = new PermissionsState(permissionsState);
8761                permissionsState.reset();
8762            } else {
8763                // We need to know only about runtime permission changes since the
8764                // calling code always writes the install permissions state but
8765                // the runtime ones are written only if changed. The only cases of
8766                // changed runtime permissions here are promotion of an install to
8767                // runtime and revocation of a runtime from a shared user.
8768                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8769                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8770                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8771                    runtimePermissionsRevoked = true;
8772                }
8773            }
8774        }
8775
8776        permissionsState.setGlobalGids(mGlobalGids);
8777
8778        final int N = pkg.requestedPermissions.size();
8779        for (int i=0; i<N; i++) {
8780            final String name = pkg.requestedPermissions.get(i);
8781            final BasePermission bp = mSettings.mPermissions.get(name);
8782
8783            if (DEBUG_INSTALL) {
8784                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8785            }
8786
8787            if (bp == null || bp.packageSetting == null) {
8788                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8789                    Slog.w(TAG, "Unknown permission " + name
8790                            + " in package " + pkg.packageName);
8791                }
8792                continue;
8793            }
8794
8795            final String perm = bp.name;
8796            boolean allowedSig = false;
8797            int grant = GRANT_DENIED;
8798
8799            // Keep track of app op permissions.
8800            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8801                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8802                if (pkgs == null) {
8803                    pkgs = new ArraySet<>();
8804                    mAppOpPermissionPackages.put(bp.name, pkgs);
8805                }
8806                pkgs.add(pkg.packageName);
8807            }
8808
8809            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8810            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8811                    >= Build.VERSION_CODES.M;
8812            switch (level) {
8813                case PermissionInfo.PROTECTION_NORMAL: {
8814                    // For all apps normal permissions are install time ones.
8815                    grant = GRANT_INSTALL;
8816                } break;
8817
8818                case PermissionInfo.PROTECTION_DANGEROUS: {
8819                    // If a permission review is required for legacy apps we represent
8820                    // their permissions as always granted runtime ones since we need
8821                    // to keep the review required permission flag per user while an
8822                    // install permission's state is shared across all users.
8823                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8824                        // For legacy apps dangerous permissions are install time ones.
8825                        grant = GRANT_INSTALL;
8826                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8827                        // For legacy apps that became modern, install becomes runtime.
8828                        grant = GRANT_UPGRADE;
8829                    } else if (mPromoteSystemApps
8830                            && isSystemApp(ps)
8831                            && mExistingSystemPackages.contains(ps.name)) {
8832                        // For legacy system apps, install becomes runtime.
8833                        // We cannot check hasInstallPermission() for system apps since those
8834                        // permissions were granted implicitly and not persisted pre-M.
8835                        grant = GRANT_UPGRADE;
8836                    } else {
8837                        // For modern apps keep runtime permissions unchanged.
8838                        grant = GRANT_RUNTIME;
8839                    }
8840                } break;
8841
8842                case PermissionInfo.PROTECTION_SIGNATURE: {
8843                    // For all apps signature permissions are install time ones.
8844                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8845                    if (allowedSig) {
8846                        grant = GRANT_INSTALL;
8847                    }
8848                } break;
8849            }
8850
8851            if (DEBUG_INSTALL) {
8852                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8853            }
8854
8855            if (grant != GRANT_DENIED) {
8856                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8857                    // If this is an existing, non-system package, then
8858                    // we can't add any new permissions to it.
8859                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8860                        // Except...  if this is a permission that was added
8861                        // to the platform (note: need to only do this when
8862                        // updating the platform).
8863                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8864                            grant = GRANT_DENIED;
8865                        }
8866                    }
8867                }
8868
8869                switch (grant) {
8870                    case GRANT_INSTALL: {
8871                        // Revoke this as runtime permission to handle the case of
8872                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8873                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8874                            if (origPermissions.getRuntimePermissionState(
8875                                    bp.name, userId) != null) {
8876                                // Revoke the runtime permission and clear the flags.
8877                                origPermissions.revokeRuntimePermission(bp, userId);
8878                                origPermissions.updatePermissionFlags(bp, userId,
8879                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8880                                // If we revoked a permission permission, we have to write.
8881                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8882                                        changedRuntimePermissionUserIds, userId);
8883                            }
8884                        }
8885                        // Grant an install permission.
8886                        if (permissionsState.grantInstallPermission(bp) !=
8887                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8888                            changedInstallPermission = true;
8889                        }
8890                    } break;
8891
8892                    case GRANT_RUNTIME: {
8893                        // Grant previously granted runtime permissions.
8894                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8895                            PermissionState permissionState = origPermissions
8896                                    .getRuntimePermissionState(bp.name, userId);
8897                            int flags = permissionState != null
8898                                    ? permissionState.getFlags() : 0;
8899                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8900                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8901                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8902                                    // If we cannot put the permission as it was, we have to write.
8903                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8904                                            changedRuntimePermissionUserIds, userId);
8905                                }
8906                                // If the app supports runtime permissions no need for a review.
8907                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8908                                        && appSupportsRuntimePermissions
8909                                        && (flags & PackageManager
8910                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8911                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8912                                    // Since we changed the flags, we have to write.
8913                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8914                                            changedRuntimePermissionUserIds, userId);
8915                                }
8916                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8917                                    && !appSupportsRuntimePermissions) {
8918                                // For legacy apps that need a permission review, every new
8919                                // runtime permission is granted but it is pending a review.
8920                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8921                                    permissionsState.grantRuntimePermission(bp, userId);
8922                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8923                                    // We changed the permission and flags, hence have to write.
8924                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8925                                            changedRuntimePermissionUserIds, userId);
8926                                }
8927                            }
8928                            // Propagate the permission flags.
8929                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8930                        }
8931                    } break;
8932
8933                    case GRANT_UPGRADE: {
8934                        // Grant runtime permissions for a previously held install permission.
8935                        PermissionState permissionState = origPermissions
8936                                .getInstallPermissionState(bp.name);
8937                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8938
8939                        if (origPermissions.revokeInstallPermission(bp)
8940                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8941                            // We will be transferring the permission flags, so clear them.
8942                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8943                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8944                            changedInstallPermission = true;
8945                        }
8946
8947                        // If the permission is not to be promoted to runtime we ignore it and
8948                        // also its other flags as they are not applicable to install permissions.
8949                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8950                            for (int userId : currentUserIds) {
8951                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8952                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8953                                    // Transfer the permission flags.
8954                                    permissionsState.updatePermissionFlags(bp, userId,
8955                                            flags, flags);
8956                                    // If we granted the permission, we have to write.
8957                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8958                                            changedRuntimePermissionUserIds, userId);
8959                                }
8960                            }
8961                        }
8962                    } break;
8963
8964                    default: {
8965                        if (packageOfInterest == null
8966                                || packageOfInterest.equals(pkg.packageName)) {
8967                            Slog.w(TAG, "Not granting permission " + perm
8968                                    + " to package " + pkg.packageName
8969                                    + " because it was previously installed without");
8970                        }
8971                    } break;
8972                }
8973            } else {
8974                if (permissionsState.revokeInstallPermission(bp) !=
8975                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8976                    // Also drop the permission flags.
8977                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8978                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8979                    changedInstallPermission = true;
8980                    Slog.i(TAG, "Un-granting permission " + perm
8981                            + " from package " + pkg.packageName
8982                            + " (protectionLevel=" + bp.protectionLevel
8983                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8984                            + ")");
8985                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8986                    // Don't print warning for app op permissions, since it is fine for them
8987                    // not to be granted, there is a UI for the user to decide.
8988                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8989                        Slog.w(TAG, "Not granting permission " + perm
8990                                + " to package " + pkg.packageName
8991                                + " (protectionLevel=" + bp.protectionLevel
8992                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8993                                + ")");
8994                    }
8995                }
8996            }
8997        }
8998
8999        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9000                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9001            // This is the first that we have heard about this package, so the
9002            // permissions we have now selected are fixed until explicitly
9003            // changed.
9004            ps.installPermissionsFixed = true;
9005        }
9006
9007        // Persist the runtime permissions state for users with changes. If permissions
9008        // were revoked because no app in the shared user declares them we have to
9009        // write synchronously to avoid losing runtime permissions state.
9010        for (int userId : changedRuntimePermissionUserIds) {
9011            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9012        }
9013
9014        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9015    }
9016
9017    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9018        boolean allowed = false;
9019        final int NP = PackageParser.NEW_PERMISSIONS.length;
9020        for (int ip=0; ip<NP; ip++) {
9021            final PackageParser.NewPermissionInfo npi
9022                    = PackageParser.NEW_PERMISSIONS[ip];
9023            if (npi.name.equals(perm)
9024                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9025                allowed = true;
9026                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9027                        + pkg.packageName);
9028                break;
9029            }
9030        }
9031        return allowed;
9032    }
9033
9034    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9035            BasePermission bp, PermissionsState origPermissions) {
9036        boolean allowed;
9037        allowed = (compareSignatures(
9038                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9039                        == PackageManager.SIGNATURE_MATCH)
9040                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9041                        == PackageManager.SIGNATURE_MATCH);
9042        if (!allowed && (bp.protectionLevel
9043                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9044            if (isSystemApp(pkg)) {
9045                // For updated system applications, a system permission
9046                // is granted only if it had been defined by the original application.
9047                if (pkg.isUpdatedSystemApp()) {
9048                    final PackageSetting sysPs = mSettings
9049                            .getDisabledSystemPkgLPr(pkg.packageName);
9050                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9051                        // If the original was granted this permission, we take
9052                        // that grant decision as read and propagate it to the
9053                        // update.
9054                        if (sysPs.isPrivileged()) {
9055                            allowed = true;
9056                        }
9057                    } else {
9058                        // The system apk may have been updated with an older
9059                        // version of the one on the data partition, but which
9060                        // granted a new system permission that it didn't have
9061                        // before.  In this case we do want to allow the app to
9062                        // now get the new permission if the ancestral apk is
9063                        // privileged to get it.
9064                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9065                            for (int j=0;
9066                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9067                                if (perm.equals(
9068                                        sysPs.pkg.requestedPermissions.get(j))) {
9069                                    allowed = true;
9070                                    break;
9071                                }
9072                            }
9073                        }
9074                    }
9075                } else {
9076                    allowed = isPrivilegedApp(pkg);
9077                }
9078            }
9079        }
9080        if (!allowed) {
9081            if (!allowed && (bp.protectionLevel
9082                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9083                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9084                // If this was a previously normal/dangerous permission that got moved
9085                // to a system permission as part of the runtime permission redesign, then
9086                // we still want to blindly grant it to old apps.
9087                allowed = true;
9088            }
9089            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9090                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9091                // If this permission is to be granted to the system installer and
9092                // this app is an installer, then it gets the permission.
9093                allowed = true;
9094            }
9095            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9096                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9097                // If this permission is to be granted to the system verifier and
9098                // this app is a verifier, then it gets the permission.
9099                allowed = true;
9100            }
9101            if (!allowed && (bp.protectionLevel
9102                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9103                    && isSystemApp(pkg)) {
9104                // Any pre-installed system app is allowed to get this permission.
9105                allowed = true;
9106            }
9107            if (!allowed && (bp.protectionLevel
9108                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9109                // For development permissions, a development permission
9110                // is granted only if it was already granted.
9111                allowed = origPermissions.hasInstallPermission(perm);
9112            }
9113        }
9114        return allowed;
9115    }
9116
9117    final class ActivityIntentResolver
9118            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9119        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9120                boolean defaultOnly, int userId) {
9121            if (!sUserManager.exists(userId)) return null;
9122            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9123            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9124        }
9125
9126        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9127                int userId) {
9128            if (!sUserManager.exists(userId)) return null;
9129            mFlags = flags;
9130            return super.queryIntent(intent, resolvedType,
9131                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9132        }
9133
9134        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9135                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9136            if (!sUserManager.exists(userId)) return null;
9137            if (packageActivities == null) {
9138                return null;
9139            }
9140            mFlags = flags;
9141            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9142            final int N = packageActivities.size();
9143            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9144                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9145
9146            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9147            for (int i = 0; i < N; ++i) {
9148                intentFilters = packageActivities.get(i).intents;
9149                if (intentFilters != null && intentFilters.size() > 0) {
9150                    PackageParser.ActivityIntentInfo[] array =
9151                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9152                    intentFilters.toArray(array);
9153                    listCut.add(array);
9154                }
9155            }
9156            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9157        }
9158
9159        public final void addActivity(PackageParser.Activity a, String type) {
9160            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9161            mActivities.put(a.getComponentName(), a);
9162            if (DEBUG_SHOW_INFO)
9163                Log.v(
9164                TAG, "  " + type + " " +
9165                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9166            if (DEBUG_SHOW_INFO)
9167                Log.v(TAG, "    Class=" + a.info.name);
9168            final int NI = a.intents.size();
9169            for (int j=0; j<NI; j++) {
9170                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9171                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9172                    intent.setPriority(0);
9173                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9174                            + a.className + " with priority > 0, forcing to 0");
9175                }
9176                if (DEBUG_SHOW_INFO) {
9177                    Log.v(TAG, "    IntentFilter:");
9178                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9179                }
9180                if (!intent.debugCheck()) {
9181                    Log.w(TAG, "==> For Activity " + a.info.name);
9182                }
9183                addFilter(intent);
9184            }
9185        }
9186
9187        public final void removeActivity(PackageParser.Activity a, String type) {
9188            mActivities.remove(a.getComponentName());
9189            if (DEBUG_SHOW_INFO) {
9190                Log.v(TAG, "  " + type + " "
9191                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9192                                : a.info.name) + ":");
9193                Log.v(TAG, "    Class=" + a.info.name);
9194            }
9195            final int NI = a.intents.size();
9196            for (int j=0; j<NI; j++) {
9197                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9198                if (DEBUG_SHOW_INFO) {
9199                    Log.v(TAG, "    IntentFilter:");
9200                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9201                }
9202                removeFilter(intent);
9203            }
9204        }
9205
9206        @Override
9207        protected boolean allowFilterResult(
9208                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9209            ActivityInfo filterAi = filter.activity.info;
9210            for (int i=dest.size()-1; i>=0; i--) {
9211                ActivityInfo destAi = dest.get(i).activityInfo;
9212                if (destAi.name == filterAi.name
9213                        && destAi.packageName == filterAi.packageName) {
9214                    return false;
9215                }
9216            }
9217            return true;
9218        }
9219
9220        @Override
9221        protected ActivityIntentInfo[] newArray(int size) {
9222            return new ActivityIntentInfo[size];
9223        }
9224
9225        @Override
9226        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9227            if (!sUserManager.exists(userId)) return true;
9228            PackageParser.Package p = filter.activity.owner;
9229            if (p != null) {
9230                PackageSetting ps = (PackageSetting)p.mExtras;
9231                if (ps != null) {
9232                    // System apps are never considered stopped for purposes of
9233                    // filtering, because there may be no way for the user to
9234                    // actually re-launch them.
9235                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9236                            && ps.getStopped(userId);
9237                }
9238            }
9239            return false;
9240        }
9241
9242        @Override
9243        protected boolean isPackageForFilter(String packageName,
9244                PackageParser.ActivityIntentInfo info) {
9245            return packageName.equals(info.activity.owner.packageName);
9246        }
9247
9248        @Override
9249        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9250                int match, int userId) {
9251            if (!sUserManager.exists(userId)) return null;
9252            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9253                return null;
9254            }
9255            final PackageParser.Activity activity = info.activity;
9256            if (mSafeMode && (activity.info.applicationInfo.flags
9257                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9258                return null;
9259            }
9260            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9261            if (ps == null) {
9262                return null;
9263            }
9264            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9265                    ps.readUserState(userId), userId);
9266            if (ai == null) {
9267                return null;
9268            }
9269            final ResolveInfo res = new ResolveInfo();
9270            res.activityInfo = ai;
9271            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9272                res.filter = info;
9273            }
9274            if (info != null) {
9275                res.handleAllWebDataURI = info.handleAllWebDataURI();
9276            }
9277            res.priority = info.getPriority();
9278            res.preferredOrder = activity.owner.mPreferredOrder;
9279            //System.out.println("Result: " + res.activityInfo.className +
9280            //                   " = " + res.priority);
9281            res.match = match;
9282            res.isDefault = info.hasDefault;
9283            res.labelRes = info.labelRes;
9284            res.nonLocalizedLabel = info.nonLocalizedLabel;
9285            if (userNeedsBadging(userId)) {
9286                res.noResourceId = true;
9287            } else {
9288                res.icon = info.icon;
9289            }
9290            res.iconResourceId = info.icon;
9291            res.system = res.activityInfo.applicationInfo.isSystemApp();
9292            return res;
9293        }
9294
9295        @Override
9296        protected void sortResults(List<ResolveInfo> results) {
9297            Collections.sort(results, mResolvePrioritySorter);
9298        }
9299
9300        @Override
9301        protected void dumpFilter(PrintWriter out, String prefix,
9302                PackageParser.ActivityIntentInfo filter) {
9303            out.print(prefix); out.print(
9304                    Integer.toHexString(System.identityHashCode(filter.activity)));
9305                    out.print(' ');
9306                    filter.activity.printComponentShortName(out);
9307                    out.print(" filter ");
9308                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9309        }
9310
9311        @Override
9312        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9313            return filter.activity;
9314        }
9315
9316        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9317            PackageParser.Activity activity = (PackageParser.Activity)label;
9318            out.print(prefix); out.print(
9319                    Integer.toHexString(System.identityHashCode(activity)));
9320                    out.print(' ');
9321                    activity.printComponentShortName(out);
9322            if (count > 1) {
9323                out.print(" ("); out.print(count); out.print(" filters)");
9324            }
9325            out.println();
9326        }
9327
9328//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9329//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9330//            final List<ResolveInfo> retList = Lists.newArrayList();
9331//            while (i.hasNext()) {
9332//                final ResolveInfo resolveInfo = i.next();
9333//                if (isEnabledLP(resolveInfo.activityInfo)) {
9334//                    retList.add(resolveInfo);
9335//                }
9336//            }
9337//            return retList;
9338//        }
9339
9340        // Keys are String (activity class name), values are Activity.
9341        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9342                = new ArrayMap<ComponentName, PackageParser.Activity>();
9343        private int mFlags;
9344    }
9345
9346    private final class ServiceIntentResolver
9347            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9348        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9349                boolean defaultOnly, int userId) {
9350            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9351            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9352        }
9353
9354        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9355                int userId) {
9356            if (!sUserManager.exists(userId)) return null;
9357            mFlags = flags;
9358            return super.queryIntent(intent, resolvedType,
9359                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9360        }
9361
9362        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9363                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9364            if (!sUserManager.exists(userId)) return null;
9365            if (packageServices == null) {
9366                return null;
9367            }
9368            mFlags = flags;
9369            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9370            final int N = packageServices.size();
9371            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9372                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9373
9374            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9375            for (int i = 0; i < N; ++i) {
9376                intentFilters = packageServices.get(i).intents;
9377                if (intentFilters != null && intentFilters.size() > 0) {
9378                    PackageParser.ServiceIntentInfo[] array =
9379                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9380                    intentFilters.toArray(array);
9381                    listCut.add(array);
9382                }
9383            }
9384            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9385        }
9386
9387        public final void addService(PackageParser.Service s) {
9388            mServices.put(s.getComponentName(), s);
9389            if (DEBUG_SHOW_INFO) {
9390                Log.v(TAG, "  "
9391                        + (s.info.nonLocalizedLabel != null
9392                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9393                Log.v(TAG, "    Class=" + s.info.name);
9394            }
9395            final int NI = s.intents.size();
9396            int j;
9397            for (j=0; j<NI; j++) {
9398                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9399                if (DEBUG_SHOW_INFO) {
9400                    Log.v(TAG, "    IntentFilter:");
9401                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9402                }
9403                if (!intent.debugCheck()) {
9404                    Log.w(TAG, "==> For Service " + s.info.name);
9405                }
9406                addFilter(intent);
9407            }
9408        }
9409
9410        public final void removeService(PackageParser.Service s) {
9411            mServices.remove(s.getComponentName());
9412            if (DEBUG_SHOW_INFO) {
9413                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9414                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9415                Log.v(TAG, "    Class=" + s.info.name);
9416            }
9417            final int NI = s.intents.size();
9418            int j;
9419            for (j=0; j<NI; j++) {
9420                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9421                if (DEBUG_SHOW_INFO) {
9422                    Log.v(TAG, "    IntentFilter:");
9423                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9424                }
9425                removeFilter(intent);
9426            }
9427        }
9428
9429        @Override
9430        protected boolean allowFilterResult(
9431                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9432            ServiceInfo filterSi = filter.service.info;
9433            for (int i=dest.size()-1; i>=0; i--) {
9434                ServiceInfo destAi = dest.get(i).serviceInfo;
9435                if (destAi.name == filterSi.name
9436                        && destAi.packageName == filterSi.packageName) {
9437                    return false;
9438                }
9439            }
9440            return true;
9441        }
9442
9443        @Override
9444        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9445            return new PackageParser.ServiceIntentInfo[size];
9446        }
9447
9448        @Override
9449        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9450            if (!sUserManager.exists(userId)) return true;
9451            PackageParser.Package p = filter.service.owner;
9452            if (p != null) {
9453                PackageSetting ps = (PackageSetting)p.mExtras;
9454                if (ps != null) {
9455                    // System apps are never considered stopped for purposes of
9456                    // filtering, because there may be no way for the user to
9457                    // actually re-launch them.
9458                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9459                            && ps.getStopped(userId);
9460                }
9461            }
9462            return false;
9463        }
9464
9465        @Override
9466        protected boolean isPackageForFilter(String packageName,
9467                PackageParser.ServiceIntentInfo info) {
9468            return packageName.equals(info.service.owner.packageName);
9469        }
9470
9471        @Override
9472        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9473                int match, int userId) {
9474            if (!sUserManager.exists(userId)) return null;
9475            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9476            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9477                return null;
9478            }
9479            final PackageParser.Service service = info.service;
9480            if (mSafeMode && (service.info.applicationInfo.flags
9481                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9482                return null;
9483            }
9484            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9485            if (ps == null) {
9486                return null;
9487            }
9488            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9489                    ps.readUserState(userId), userId);
9490            if (si == null) {
9491                return null;
9492            }
9493            final ResolveInfo res = new ResolveInfo();
9494            res.serviceInfo = si;
9495            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9496                res.filter = filter;
9497            }
9498            res.priority = info.getPriority();
9499            res.preferredOrder = service.owner.mPreferredOrder;
9500            res.match = match;
9501            res.isDefault = info.hasDefault;
9502            res.labelRes = info.labelRes;
9503            res.nonLocalizedLabel = info.nonLocalizedLabel;
9504            res.icon = info.icon;
9505            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9506            return res;
9507        }
9508
9509        @Override
9510        protected void sortResults(List<ResolveInfo> results) {
9511            Collections.sort(results, mResolvePrioritySorter);
9512        }
9513
9514        @Override
9515        protected void dumpFilter(PrintWriter out, String prefix,
9516                PackageParser.ServiceIntentInfo filter) {
9517            out.print(prefix); out.print(
9518                    Integer.toHexString(System.identityHashCode(filter.service)));
9519                    out.print(' ');
9520                    filter.service.printComponentShortName(out);
9521                    out.print(" filter ");
9522                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9523        }
9524
9525        @Override
9526        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9527            return filter.service;
9528        }
9529
9530        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9531            PackageParser.Service service = (PackageParser.Service)label;
9532            out.print(prefix); out.print(
9533                    Integer.toHexString(System.identityHashCode(service)));
9534                    out.print(' ');
9535                    service.printComponentShortName(out);
9536            if (count > 1) {
9537                out.print(" ("); out.print(count); out.print(" filters)");
9538            }
9539            out.println();
9540        }
9541
9542//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9543//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9544//            final List<ResolveInfo> retList = Lists.newArrayList();
9545//            while (i.hasNext()) {
9546//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9547//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9548//                    retList.add(resolveInfo);
9549//                }
9550//            }
9551//            return retList;
9552//        }
9553
9554        // Keys are String (activity class name), values are Activity.
9555        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9556                = new ArrayMap<ComponentName, PackageParser.Service>();
9557        private int mFlags;
9558    };
9559
9560    private final class ProviderIntentResolver
9561            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9562        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9563                boolean defaultOnly, int userId) {
9564            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9565            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9566        }
9567
9568        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9569                int userId) {
9570            if (!sUserManager.exists(userId))
9571                return null;
9572            mFlags = flags;
9573            return super.queryIntent(intent, resolvedType,
9574                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9575        }
9576
9577        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9578                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9579            if (!sUserManager.exists(userId))
9580                return null;
9581            if (packageProviders == null) {
9582                return null;
9583            }
9584            mFlags = flags;
9585            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9586            final int N = packageProviders.size();
9587            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9588                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9589
9590            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9591            for (int i = 0; i < N; ++i) {
9592                intentFilters = packageProviders.get(i).intents;
9593                if (intentFilters != null && intentFilters.size() > 0) {
9594                    PackageParser.ProviderIntentInfo[] array =
9595                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9596                    intentFilters.toArray(array);
9597                    listCut.add(array);
9598                }
9599            }
9600            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9601        }
9602
9603        public final void addProvider(PackageParser.Provider p) {
9604            if (mProviders.containsKey(p.getComponentName())) {
9605                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9606                return;
9607            }
9608
9609            mProviders.put(p.getComponentName(), p);
9610            if (DEBUG_SHOW_INFO) {
9611                Log.v(TAG, "  "
9612                        + (p.info.nonLocalizedLabel != null
9613                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9614                Log.v(TAG, "    Class=" + p.info.name);
9615            }
9616            final int NI = p.intents.size();
9617            int j;
9618            for (j = 0; j < NI; j++) {
9619                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9620                if (DEBUG_SHOW_INFO) {
9621                    Log.v(TAG, "    IntentFilter:");
9622                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9623                }
9624                if (!intent.debugCheck()) {
9625                    Log.w(TAG, "==> For Provider " + p.info.name);
9626                }
9627                addFilter(intent);
9628            }
9629        }
9630
9631        public final void removeProvider(PackageParser.Provider p) {
9632            mProviders.remove(p.getComponentName());
9633            if (DEBUG_SHOW_INFO) {
9634                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9635                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9636                Log.v(TAG, "    Class=" + p.info.name);
9637            }
9638            final int NI = p.intents.size();
9639            int j;
9640            for (j = 0; j < NI; j++) {
9641                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9642                if (DEBUG_SHOW_INFO) {
9643                    Log.v(TAG, "    IntentFilter:");
9644                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9645                }
9646                removeFilter(intent);
9647            }
9648        }
9649
9650        @Override
9651        protected boolean allowFilterResult(
9652                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9653            ProviderInfo filterPi = filter.provider.info;
9654            for (int i = dest.size() - 1; i >= 0; i--) {
9655                ProviderInfo destPi = dest.get(i).providerInfo;
9656                if (destPi.name == filterPi.name
9657                        && destPi.packageName == filterPi.packageName) {
9658                    return false;
9659                }
9660            }
9661            return true;
9662        }
9663
9664        @Override
9665        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9666            return new PackageParser.ProviderIntentInfo[size];
9667        }
9668
9669        @Override
9670        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9671            if (!sUserManager.exists(userId))
9672                return true;
9673            PackageParser.Package p = filter.provider.owner;
9674            if (p != null) {
9675                PackageSetting ps = (PackageSetting) p.mExtras;
9676                if (ps != null) {
9677                    // System apps are never considered stopped for purposes of
9678                    // filtering, because there may be no way for the user to
9679                    // actually re-launch them.
9680                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9681                            && ps.getStopped(userId);
9682                }
9683            }
9684            return false;
9685        }
9686
9687        @Override
9688        protected boolean isPackageForFilter(String packageName,
9689                PackageParser.ProviderIntentInfo info) {
9690            return packageName.equals(info.provider.owner.packageName);
9691        }
9692
9693        @Override
9694        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9695                int match, int userId) {
9696            if (!sUserManager.exists(userId))
9697                return null;
9698            final PackageParser.ProviderIntentInfo info = filter;
9699            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9700                return null;
9701            }
9702            final PackageParser.Provider provider = info.provider;
9703            if (mSafeMode && (provider.info.applicationInfo.flags
9704                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9705                return null;
9706            }
9707            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9708            if (ps == null) {
9709                return null;
9710            }
9711            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9712                    ps.readUserState(userId), userId);
9713            if (pi == null) {
9714                return null;
9715            }
9716            final ResolveInfo res = new ResolveInfo();
9717            res.providerInfo = pi;
9718            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9719                res.filter = filter;
9720            }
9721            res.priority = info.getPriority();
9722            res.preferredOrder = provider.owner.mPreferredOrder;
9723            res.match = match;
9724            res.isDefault = info.hasDefault;
9725            res.labelRes = info.labelRes;
9726            res.nonLocalizedLabel = info.nonLocalizedLabel;
9727            res.icon = info.icon;
9728            res.system = res.providerInfo.applicationInfo.isSystemApp();
9729            return res;
9730        }
9731
9732        @Override
9733        protected void sortResults(List<ResolveInfo> results) {
9734            Collections.sort(results, mResolvePrioritySorter);
9735        }
9736
9737        @Override
9738        protected void dumpFilter(PrintWriter out, String prefix,
9739                PackageParser.ProviderIntentInfo filter) {
9740            out.print(prefix);
9741            out.print(
9742                    Integer.toHexString(System.identityHashCode(filter.provider)));
9743            out.print(' ');
9744            filter.provider.printComponentShortName(out);
9745            out.print(" filter ");
9746            out.println(Integer.toHexString(System.identityHashCode(filter)));
9747        }
9748
9749        @Override
9750        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9751            return filter.provider;
9752        }
9753
9754        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9755            PackageParser.Provider provider = (PackageParser.Provider)label;
9756            out.print(prefix); out.print(
9757                    Integer.toHexString(System.identityHashCode(provider)));
9758                    out.print(' ');
9759                    provider.printComponentShortName(out);
9760            if (count > 1) {
9761                out.print(" ("); out.print(count); out.print(" filters)");
9762            }
9763            out.println();
9764        }
9765
9766        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9767                = new ArrayMap<ComponentName, PackageParser.Provider>();
9768        private int mFlags;
9769    }
9770
9771    private static final class EphemeralIntentResolver
9772            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9773        @Override
9774        protected EphemeralResolveIntentInfo[] newArray(int size) {
9775            return new EphemeralResolveIntentInfo[size];
9776        }
9777
9778        @Override
9779        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9780            return true;
9781        }
9782
9783        @Override
9784        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9785                int userId) {
9786            if (!sUserManager.exists(userId)) {
9787                return null;
9788            }
9789            return info.getEphemeralResolveInfo();
9790        }
9791    }
9792
9793    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9794            new Comparator<ResolveInfo>() {
9795        public int compare(ResolveInfo r1, ResolveInfo r2) {
9796            int v1 = r1.priority;
9797            int v2 = r2.priority;
9798            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9799            if (v1 != v2) {
9800                return (v1 > v2) ? -1 : 1;
9801            }
9802            v1 = r1.preferredOrder;
9803            v2 = r2.preferredOrder;
9804            if (v1 != v2) {
9805                return (v1 > v2) ? -1 : 1;
9806            }
9807            if (r1.isDefault != r2.isDefault) {
9808                return r1.isDefault ? -1 : 1;
9809            }
9810            v1 = r1.match;
9811            v2 = r2.match;
9812            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9813            if (v1 != v2) {
9814                return (v1 > v2) ? -1 : 1;
9815            }
9816            if (r1.system != r2.system) {
9817                return r1.system ? -1 : 1;
9818            }
9819            if (r1.activityInfo != null) {
9820                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9821            }
9822            if (r1.serviceInfo != null) {
9823                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9824            }
9825            if (r1.providerInfo != null) {
9826                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9827            }
9828            return 0;
9829        }
9830    };
9831
9832    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9833            new Comparator<ProviderInfo>() {
9834        public int compare(ProviderInfo p1, ProviderInfo p2) {
9835            final int v1 = p1.initOrder;
9836            final int v2 = p2.initOrder;
9837            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9838        }
9839    };
9840
9841    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9842            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9843            final int[] userIds) {
9844        mHandler.post(new Runnable() {
9845            @Override
9846            public void run() {
9847                try {
9848                    final IActivityManager am = ActivityManagerNative.getDefault();
9849                    if (am == null) return;
9850                    final int[] resolvedUserIds;
9851                    if (userIds == null) {
9852                        resolvedUserIds = am.getRunningUserIds();
9853                    } else {
9854                        resolvedUserIds = userIds;
9855                    }
9856                    for (int id : resolvedUserIds) {
9857                        final Intent intent = new Intent(action,
9858                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9859                        if (extras != null) {
9860                            intent.putExtras(extras);
9861                        }
9862                        if (targetPkg != null) {
9863                            intent.setPackage(targetPkg);
9864                        }
9865                        // Modify the UID when posting to other users
9866                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9867                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9868                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9869                            intent.putExtra(Intent.EXTRA_UID, uid);
9870                        }
9871                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9872                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9873                        if (DEBUG_BROADCASTS) {
9874                            RuntimeException here = new RuntimeException("here");
9875                            here.fillInStackTrace();
9876                            Slog.d(TAG, "Sending to user " + id + ": "
9877                                    + intent.toShortString(false, true, false, false)
9878                                    + " " + intent.getExtras(), here);
9879                        }
9880                        am.broadcastIntent(null, intent, null, finishedReceiver,
9881                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9882                                null, finishedReceiver != null, false, id);
9883                    }
9884                } catch (RemoteException ex) {
9885                }
9886            }
9887        });
9888    }
9889
9890    /**
9891     * Check if the external storage media is available. This is true if there
9892     * is a mounted external storage medium or if the external storage is
9893     * emulated.
9894     */
9895    private boolean isExternalMediaAvailable() {
9896        return mMediaMounted || Environment.isExternalStorageEmulated();
9897    }
9898
9899    @Override
9900    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9901        // writer
9902        synchronized (mPackages) {
9903            if (!isExternalMediaAvailable()) {
9904                // If the external storage is no longer mounted at this point,
9905                // the caller may not have been able to delete all of this
9906                // packages files and can not delete any more.  Bail.
9907                return null;
9908            }
9909            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9910            if (lastPackage != null) {
9911                pkgs.remove(lastPackage);
9912            }
9913            if (pkgs.size() > 0) {
9914                return pkgs.get(0);
9915            }
9916        }
9917        return null;
9918    }
9919
9920    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9921        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9922                userId, andCode ? 1 : 0, packageName);
9923        if (mSystemReady) {
9924            msg.sendToTarget();
9925        } else {
9926            if (mPostSystemReadyMessages == null) {
9927                mPostSystemReadyMessages = new ArrayList<>();
9928            }
9929            mPostSystemReadyMessages.add(msg);
9930        }
9931    }
9932
9933    void startCleaningPackages() {
9934        // reader
9935        synchronized (mPackages) {
9936            if (!isExternalMediaAvailable()) {
9937                return;
9938            }
9939            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9940                return;
9941            }
9942        }
9943        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9944        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9945        IActivityManager am = ActivityManagerNative.getDefault();
9946        if (am != null) {
9947            try {
9948                am.startService(null, intent, null, mContext.getOpPackageName(),
9949                        UserHandle.USER_SYSTEM);
9950            } catch (RemoteException e) {
9951            }
9952        }
9953    }
9954
9955    @Override
9956    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9957            int installFlags, String installerPackageName, VerificationParams verificationParams,
9958            String packageAbiOverride) {
9959        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9960                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9961    }
9962
9963    @Override
9964    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9965            int installFlags, String installerPackageName, VerificationParams verificationParams,
9966            String packageAbiOverride, int userId) {
9967        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9968
9969        final int callingUid = Binder.getCallingUid();
9970        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9971
9972        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9973            try {
9974                if (observer != null) {
9975                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9976                }
9977            } catch (RemoteException re) {
9978            }
9979            return;
9980        }
9981
9982        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9983            installFlags |= PackageManager.INSTALL_FROM_ADB;
9984
9985        } else {
9986            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9987            // about installerPackageName.
9988
9989            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9990            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9991        }
9992
9993        UserHandle user;
9994        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9995            user = UserHandle.ALL;
9996        } else {
9997            user = new UserHandle(userId);
9998        }
9999
10000        // Only system components can circumvent runtime permissions when installing.
10001        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10002                && mContext.checkCallingOrSelfPermission(Manifest.permission
10003                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10004            throw new SecurityException("You need the "
10005                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10006                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10007        }
10008
10009        verificationParams.setInstallerUid(callingUid);
10010
10011        final File originFile = new File(originPath);
10012        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10013
10014        final Message msg = mHandler.obtainMessage(INIT_COPY);
10015        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10016                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10017        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10018        msg.obj = params;
10019
10020        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10021                System.identityHashCode(msg.obj));
10022        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10023                System.identityHashCode(msg.obj));
10024
10025        mHandler.sendMessage(msg);
10026    }
10027
10028    void installStage(String packageName, File stagedDir, String stagedCid,
10029            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10030            String installerPackageName, int installerUid, UserHandle user) {
10031        if (DEBUG_EPHEMERAL) {
10032            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10033                Slog.d(TAG, "Ephemeral install of " + packageName);
10034            }
10035        }
10036        final VerificationParams verifParams = new VerificationParams(
10037                null, sessionParams.originatingUri, sessionParams.referrerUri,
10038                sessionParams.originatingUid);
10039        verifParams.setInstallerUid(installerUid);
10040
10041        final OriginInfo origin;
10042        if (stagedDir != null) {
10043            origin = OriginInfo.fromStagedFile(stagedDir);
10044        } else {
10045            origin = OriginInfo.fromStagedContainer(stagedCid);
10046        }
10047
10048        final Message msg = mHandler.obtainMessage(INIT_COPY);
10049        final InstallParams params = new InstallParams(origin, null, observer,
10050                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10051                verifParams, user, sessionParams.abiOverride,
10052                sessionParams.grantedRuntimePermissions);
10053        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10054        msg.obj = params;
10055
10056        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10057                System.identityHashCode(msg.obj));
10058        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10059                System.identityHashCode(msg.obj));
10060
10061        mHandler.sendMessage(msg);
10062    }
10063
10064    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10065        Bundle extras = new Bundle(1);
10066        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10067
10068        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10069                packageName, extras, 0, null, null, new int[] {userId});
10070        try {
10071            IActivityManager am = ActivityManagerNative.getDefault();
10072            final boolean isSystem =
10073                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10074            if (isSystem && am.isUserRunning(userId, 0)) {
10075                // The just-installed/enabled app is bundled on the system, so presumed
10076                // to be able to run automatically without needing an explicit launch.
10077                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10078                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10079                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10080                        .setPackage(packageName);
10081                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10082                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10083            }
10084        } catch (RemoteException e) {
10085            // shouldn't happen
10086            Slog.w(TAG, "Unable to bootstrap installed package", e);
10087        }
10088    }
10089
10090    @Override
10091    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10092            int userId) {
10093        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10094        PackageSetting pkgSetting;
10095        final int uid = Binder.getCallingUid();
10096        enforceCrossUserPermission(uid, userId, true, true,
10097                "setApplicationHiddenSetting for user " + userId);
10098
10099        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10100            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10101            return false;
10102        }
10103
10104        long callingId = Binder.clearCallingIdentity();
10105        try {
10106            boolean sendAdded = false;
10107            boolean sendRemoved = false;
10108            // writer
10109            synchronized (mPackages) {
10110                pkgSetting = mSettings.mPackages.get(packageName);
10111                if (pkgSetting == null) {
10112                    return false;
10113                }
10114                if (pkgSetting.getHidden(userId) != hidden) {
10115                    pkgSetting.setHidden(hidden, userId);
10116                    mSettings.writePackageRestrictionsLPr(userId);
10117                    if (hidden) {
10118                        sendRemoved = true;
10119                    } else {
10120                        sendAdded = true;
10121                    }
10122                }
10123            }
10124            if (sendAdded) {
10125                sendPackageAddedForUser(packageName, pkgSetting, userId);
10126                return true;
10127            }
10128            if (sendRemoved) {
10129                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10130                        "hiding pkg");
10131                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10132                return true;
10133            }
10134        } finally {
10135            Binder.restoreCallingIdentity(callingId);
10136        }
10137        return false;
10138    }
10139
10140    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10141            int userId) {
10142        final PackageRemovedInfo info = new PackageRemovedInfo();
10143        info.removedPackage = packageName;
10144        info.removedUsers = new int[] {userId};
10145        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10146        info.sendBroadcast(false, false, false);
10147    }
10148
10149    /**
10150     * Returns true if application is not found or there was an error. Otherwise it returns
10151     * the hidden state of the package for the given user.
10152     */
10153    @Override
10154    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10155        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10156        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10157                false, "getApplicationHidden for user " + userId);
10158        PackageSetting pkgSetting;
10159        long callingId = Binder.clearCallingIdentity();
10160        try {
10161            // writer
10162            synchronized (mPackages) {
10163                pkgSetting = mSettings.mPackages.get(packageName);
10164                if (pkgSetting == null) {
10165                    return true;
10166                }
10167                return pkgSetting.getHidden(userId);
10168            }
10169        } finally {
10170            Binder.restoreCallingIdentity(callingId);
10171        }
10172    }
10173
10174    /**
10175     * @hide
10176     */
10177    @Override
10178    public int installExistingPackageAsUser(String packageName, int userId) {
10179        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10180                null);
10181        PackageSetting pkgSetting;
10182        final int uid = Binder.getCallingUid();
10183        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10184                + userId);
10185        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10186            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10187        }
10188
10189        long callingId = Binder.clearCallingIdentity();
10190        try {
10191            boolean sendAdded = false;
10192
10193            // writer
10194            synchronized (mPackages) {
10195                pkgSetting = mSettings.mPackages.get(packageName);
10196                if (pkgSetting == null) {
10197                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10198                }
10199                if (!pkgSetting.getInstalled(userId)) {
10200                    pkgSetting.setInstalled(true, userId);
10201                    pkgSetting.setHidden(false, userId);
10202                    mSettings.writePackageRestrictionsLPr(userId);
10203                    sendAdded = true;
10204                }
10205            }
10206
10207            if (sendAdded) {
10208                sendPackageAddedForUser(packageName, pkgSetting, userId);
10209            }
10210        } finally {
10211            Binder.restoreCallingIdentity(callingId);
10212        }
10213
10214        return PackageManager.INSTALL_SUCCEEDED;
10215    }
10216
10217    boolean isUserRestricted(int userId, String restrictionKey) {
10218        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10219        if (restrictions.getBoolean(restrictionKey, false)) {
10220            Log.w(TAG, "User is restricted: " + restrictionKey);
10221            return true;
10222        }
10223        return false;
10224    }
10225
10226    @Override
10227    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10228        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10229        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10230                "setPackageSuspended for user " + userId);
10231
10232        long callingId = Binder.clearCallingIdentity();
10233        try {
10234            synchronized (mPackages) {
10235                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10236                if (pkgSetting != null) {
10237                    if (pkgSetting.getSuspended(userId) != suspended) {
10238                        pkgSetting.setSuspended(suspended, userId);
10239                        mSettings.writePackageRestrictionsLPr(userId);
10240                    }
10241
10242                    // TODO:
10243                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10244                    // * remove app from recents (kill app it if it is running)
10245                    // * erase existing notifications for this app
10246                    return true;
10247                }
10248
10249                return false;
10250            }
10251        } finally {
10252            Binder.restoreCallingIdentity(callingId);
10253        }
10254    }
10255
10256    @Override
10257    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10258        mContext.enforceCallingOrSelfPermission(
10259                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10260                "Only package verification agents can verify applications");
10261
10262        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10263        final PackageVerificationResponse response = new PackageVerificationResponse(
10264                verificationCode, Binder.getCallingUid());
10265        msg.arg1 = id;
10266        msg.obj = response;
10267        mHandler.sendMessage(msg);
10268    }
10269
10270    @Override
10271    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10272            long millisecondsToDelay) {
10273        mContext.enforceCallingOrSelfPermission(
10274                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10275                "Only package verification agents can extend verification timeouts");
10276
10277        final PackageVerificationState state = mPendingVerification.get(id);
10278        final PackageVerificationResponse response = new PackageVerificationResponse(
10279                verificationCodeAtTimeout, Binder.getCallingUid());
10280
10281        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10282            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10283        }
10284        if (millisecondsToDelay < 0) {
10285            millisecondsToDelay = 0;
10286        }
10287        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10288                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10289            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10290        }
10291
10292        if ((state != null) && !state.timeoutExtended()) {
10293            state.extendTimeout();
10294
10295            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10296            msg.arg1 = id;
10297            msg.obj = response;
10298            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10299        }
10300    }
10301
10302    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10303            int verificationCode, UserHandle user) {
10304        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10305        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10306        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10307        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10308        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10309
10310        mContext.sendBroadcastAsUser(intent, user,
10311                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10312    }
10313
10314    private ComponentName matchComponentForVerifier(String packageName,
10315            List<ResolveInfo> receivers) {
10316        ActivityInfo targetReceiver = null;
10317
10318        final int NR = receivers.size();
10319        for (int i = 0; i < NR; i++) {
10320            final ResolveInfo info = receivers.get(i);
10321            if (info.activityInfo == null) {
10322                continue;
10323            }
10324
10325            if (packageName.equals(info.activityInfo.packageName)) {
10326                targetReceiver = info.activityInfo;
10327                break;
10328            }
10329        }
10330
10331        if (targetReceiver == null) {
10332            return null;
10333        }
10334
10335        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10336    }
10337
10338    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10339            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10340        if (pkgInfo.verifiers.length == 0) {
10341            return null;
10342        }
10343
10344        final int N = pkgInfo.verifiers.length;
10345        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10346        for (int i = 0; i < N; i++) {
10347            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10348
10349            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10350                    receivers);
10351            if (comp == null) {
10352                continue;
10353            }
10354
10355            final int verifierUid = getUidForVerifier(verifierInfo);
10356            if (verifierUid == -1) {
10357                continue;
10358            }
10359
10360            if (DEBUG_VERIFY) {
10361                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10362                        + " with the correct signature");
10363            }
10364            sufficientVerifiers.add(comp);
10365            verificationState.addSufficientVerifier(verifierUid);
10366        }
10367
10368        return sufficientVerifiers;
10369    }
10370
10371    private int getUidForVerifier(VerifierInfo verifierInfo) {
10372        synchronized (mPackages) {
10373            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10374            if (pkg == null) {
10375                return -1;
10376            } else if (pkg.mSignatures.length != 1) {
10377                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10378                        + " has more than one signature; ignoring");
10379                return -1;
10380            }
10381
10382            /*
10383             * If the public key of the package's signature does not match
10384             * our expected public key, then this is a different package and
10385             * we should skip.
10386             */
10387
10388            final byte[] expectedPublicKey;
10389            try {
10390                final Signature verifierSig = pkg.mSignatures[0];
10391                final PublicKey publicKey = verifierSig.getPublicKey();
10392                expectedPublicKey = publicKey.getEncoded();
10393            } catch (CertificateException e) {
10394                return -1;
10395            }
10396
10397            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10398
10399            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10400                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10401                        + " does not have the expected public key; ignoring");
10402                return -1;
10403            }
10404
10405            return pkg.applicationInfo.uid;
10406        }
10407    }
10408
10409    @Override
10410    public void finishPackageInstall(int token) {
10411        enforceSystemOrRoot("Only the system is allowed to finish installs");
10412
10413        if (DEBUG_INSTALL) {
10414            Slog.v(TAG, "BM finishing package install for " + token);
10415        }
10416        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10417
10418        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10419        mHandler.sendMessage(msg);
10420    }
10421
10422    /**
10423     * Get the verification agent timeout.
10424     *
10425     * @return verification timeout in milliseconds
10426     */
10427    private long getVerificationTimeout() {
10428        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10429                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10430                DEFAULT_VERIFICATION_TIMEOUT);
10431    }
10432
10433    /**
10434     * Get the default verification agent response code.
10435     *
10436     * @return default verification response code
10437     */
10438    private int getDefaultVerificationResponse() {
10439        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10440                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10441                DEFAULT_VERIFICATION_RESPONSE);
10442    }
10443
10444    /**
10445     * Check whether or not package verification has been enabled.
10446     *
10447     * @return true if verification should be performed
10448     */
10449    private boolean isVerificationEnabled(int userId, int installFlags) {
10450        if (!DEFAULT_VERIFY_ENABLE) {
10451            return false;
10452        }
10453        // Ephemeral apps don't get the full verification treatment
10454        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10455            if (DEBUG_EPHEMERAL) {
10456                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10457            }
10458            return false;
10459        }
10460
10461        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10462
10463        // Check if installing from ADB
10464        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10465            // Do not run verification in a test harness environment
10466            if (ActivityManager.isRunningInTestHarness()) {
10467                return false;
10468            }
10469            if (ensureVerifyAppsEnabled) {
10470                return true;
10471            }
10472            // Check if the developer does not want package verification for ADB installs
10473            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10474                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10475                return false;
10476            }
10477        }
10478
10479        if (ensureVerifyAppsEnabled) {
10480            return true;
10481        }
10482
10483        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10484                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10485    }
10486
10487    @Override
10488    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10489            throws RemoteException {
10490        mContext.enforceCallingOrSelfPermission(
10491                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10492                "Only intentfilter verification agents can verify applications");
10493
10494        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10495        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10496                Binder.getCallingUid(), verificationCode, failedDomains);
10497        msg.arg1 = id;
10498        msg.obj = response;
10499        mHandler.sendMessage(msg);
10500    }
10501
10502    @Override
10503    public int getIntentVerificationStatus(String packageName, int userId) {
10504        synchronized (mPackages) {
10505            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10506        }
10507    }
10508
10509    @Override
10510    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10511        mContext.enforceCallingOrSelfPermission(
10512                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10513
10514        boolean result = false;
10515        synchronized (mPackages) {
10516            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10517        }
10518        if (result) {
10519            scheduleWritePackageRestrictionsLocked(userId);
10520        }
10521        return result;
10522    }
10523
10524    @Override
10525    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10526        synchronized (mPackages) {
10527            return mSettings.getIntentFilterVerificationsLPr(packageName);
10528        }
10529    }
10530
10531    @Override
10532    public List<IntentFilter> getAllIntentFilters(String packageName) {
10533        if (TextUtils.isEmpty(packageName)) {
10534            return Collections.<IntentFilter>emptyList();
10535        }
10536        synchronized (mPackages) {
10537            PackageParser.Package pkg = mPackages.get(packageName);
10538            if (pkg == null || pkg.activities == null) {
10539                return Collections.<IntentFilter>emptyList();
10540            }
10541            final int count = pkg.activities.size();
10542            ArrayList<IntentFilter> result = new ArrayList<>();
10543            for (int n=0; n<count; n++) {
10544                PackageParser.Activity activity = pkg.activities.get(n);
10545                if (activity.intents != null && activity.intents.size() > 0) {
10546                    result.addAll(activity.intents);
10547                }
10548            }
10549            return result;
10550        }
10551    }
10552
10553    @Override
10554    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10555        mContext.enforceCallingOrSelfPermission(
10556                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10557
10558        synchronized (mPackages) {
10559            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10560            if (packageName != null) {
10561                result |= updateIntentVerificationStatus(packageName,
10562                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10563                        userId);
10564                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10565                        packageName, userId);
10566            }
10567            return result;
10568        }
10569    }
10570
10571    @Override
10572    public String getDefaultBrowserPackageName(int userId) {
10573        synchronized (mPackages) {
10574            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10575        }
10576    }
10577
10578    /**
10579     * Get the "allow unknown sources" setting.
10580     *
10581     * @return the current "allow unknown sources" setting
10582     */
10583    private int getUnknownSourcesSettings() {
10584        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10585                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10586                -1);
10587    }
10588
10589    @Override
10590    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10591        final int uid = Binder.getCallingUid();
10592        // writer
10593        synchronized (mPackages) {
10594            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10595            if (targetPackageSetting == null) {
10596                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10597            }
10598
10599            PackageSetting installerPackageSetting;
10600            if (installerPackageName != null) {
10601                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10602                if (installerPackageSetting == null) {
10603                    throw new IllegalArgumentException("Unknown installer package: "
10604                            + installerPackageName);
10605                }
10606            } else {
10607                installerPackageSetting = null;
10608            }
10609
10610            Signature[] callerSignature;
10611            Object obj = mSettings.getUserIdLPr(uid);
10612            if (obj != null) {
10613                if (obj instanceof SharedUserSetting) {
10614                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10615                } else if (obj instanceof PackageSetting) {
10616                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10617                } else {
10618                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10619                }
10620            } else {
10621                throw new SecurityException("Unknown calling uid " + uid);
10622            }
10623
10624            // Verify: can't set installerPackageName to a package that is
10625            // not signed with the same cert as the caller.
10626            if (installerPackageSetting != null) {
10627                if (compareSignatures(callerSignature,
10628                        installerPackageSetting.signatures.mSignatures)
10629                        != PackageManager.SIGNATURE_MATCH) {
10630                    throw new SecurityException(
10631                            "Caller does not have same cert as new installer package "
10632                            + installerPackageName);
10633                }
10634            }
10635
10636            // Verify: if target already has an installer package, it must
10637            // be signed with the same cert as the caller.
10638            if (targetPackageSetting.installerPackageName != null) {
10639                PackageSetting setting = mSettings.mPackages.get(
10640                        targetPackageSetting.installerPackageName);
10641                // If the currently set package isn't valid, then it's always
10642                // okay to change it.
10643                if (setting != null) {
10644                    if (compareSignatures(callerSignature,
10645                            setting.signatures.mSignatures)
10646                            != PackageManager.SIGNATURE_MATCH) {
10647                        throw new SecurityException(
10648                                "Caller does not have same cert as old installer package "
10649                                + targetPackageSetting.installerPackageName);
10650                    }
10651                }
10652            }
10653
10654            // Okay!
10655            targetPackageSetting.installerPackageName = installerPackageName;
10656            scheduleWriteSettingsLocked();
10657        }
10658    }
10659
10660    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10661        // Queue up an async operation since the package installation may take a little while.
10662        mHandler.post(new Runnable() {
10663            public void run() {
10664                mHandler.removeCallbacks(this);
10665                 // Result object to be returned
10666                PackageInstalledInfo res = new PackageInstalledInfo();
10667                res.returnCode = currentStatus;
10668                res.uid = -1;
10669                res.pkg = null;
10670                res.removedInfo = new PackageRemovedInfo();
10671                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10672                    args.doPreInstall(res.returnCode);
10673                    synchronized (mInstallLock) {
10674                        installPackageTracedLI(args, res);
10675                    }
10676                    args.doPostInstall(res.returnCode, res.uid);
10677                }
10678
10679                // A restore should be performed at this point if (a) the install
10680                // succeeded, (b) the operation is not an update, and (c) the new
10681                // package has not opted out of backup participation.
10682                final boolean update = res.removedInfo.removedPackage != null;
10683                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10684                boolean doRestore = !update
10685                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10686
10687                // Set up the post-install work request bookkeeping.  This will be used
10688                // and cleaned up by the post-install event handling regardless of whether
10689                // there's a restore pass performed.  Token values are >= 1.
10690                int token;
10691                if (mNextInstallToken < 0) mNextInstallToken = 1;
10692                token = mNextInstallToken++;
10693
10694                PostInstallData data = new PostInstallData(args, res);
10695                mRunningInstalls.put(token, data);
10696                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10697
10698                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10699                    // Pass responsibility to the Backup Manager.  It will perform a
10700                    // restore if appropriate, then pass responsibility back to the
10701                    // Package Manager to run the post-install observer callbacks
10702                    // and broadcasts.
10703                    IBackupManager bm = IBackupManager.Stub.asInterface(
10704                            ServiceManager.getService(Context.BACKUP_SERVICE));
10705                    if (bm != null) {
10706                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10707                                + " to BM for possible restore");
10708                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10709                        try {
10710                            // TODO: http://b/22388012
10711                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10712                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10713                            } else {
10714                                doRestore = false;
10715                            }
10716                        } catch (RemoteException e) {
10717                            // can't happen; the backup manager is local
10718                        } catch (Exception e) {
10719                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10720                            doRestore = false;
10721                        }
10722                    } else {
10723                        Slog.e(TAG, "Backup Manager not found!");
10724                        doRestore = false;
10725                    }
10726                }
10727
10728                if (!doRestore) {
10729                    // No restore possible, or the Backup Manager was mysteriously not
10730                    // available -- just fire the post-install work request directly.
10731                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10732
10733                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10734
10735                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10736                    mHandler.sendMessage(msg);
10737                }
10738            }
10739        });
10740    }
10741
10742    private abstract class HandlerParams {
10743        private static final int MAX_RETRIES = 4;
10744
10745        /**
10746         * Number of times startCopy() has been attempted and had a non-fatal
10747         * error.
10748         */
10749        private int mRetries = 0;
10750
10751        /** User handle for the user requesting the information or installation. */
10752        private final UserHandle mUser;
10753        String traceMethod;
10754        int traceCookie;
10755
10756        HandlerParams(UserHandle user) {
10757            mUser = user;
10758        }
10759
10760        UserHandle getUser() {
10761            return mUser;
10762        }
10763
10764        HandlerParams setTraceMethod(String traceMethod) {
10765            this.traceMethod = traceMethod;
10766            return this;
10767        }
10768
10769        HandlerParams setTraceCookie(int traceCookie) {
10770            this.traceCookie = traceCookie;
10771            return this;
10772        }
10773
10774        final boolean startCopy() {
10775            boolean res;
10776            try {
10777                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10778
10779                if (++mRetries > MAX_RETRIES) {
10780                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10781                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10782                    handleServiceError();
10783                    return false;
10784                } else {
10785                    handleStartCopy();
10786                    res = true;
10787                }
10788            } catch (RemoteException e) {
10789                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10790                mHandler.sendEmptyMessage(MCS_RECONNECT);
10791                res = false;
10792            }
10793            handleReturnCode();
10794            return res;
10795        }
10796
10797        final void serviceError() {
10798            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10799            handleServiceError();
10800            handleReturnCode();
10801        }
10802
10803        abstract void handleStartCopy() throws RemoteException;
10804        abstract void handleServiceError();
10805        abstract void handleReturnCode();
10806    }
10807
10808    class MeasureParams extends HandlerParams {
10809        private final PackageStats mStats;
10810        private boolean mSuccess;
10811
10812        private final IPackageStatsObserver mObserver;
10813
10814        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10815            super(new UserHandle(stats.userHandle));
10816            mObserver = observer;
10817            mStats = stats;
10818        }
10819
10820        @Override
10821        public String toString() {
10822            return "MeasureParams{"
10823                + Integer.toHexString(System.identityHashCode(this))
10824                + " " + mStats.packageName + "}";
10825        }
10826
10827        @Override
10828        void handleStartCopy() throws RemoteException {
10829            synchronized (mInstallLock) {
10830                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10831            }
10832
10833            if (mSuccess) {
10834                final boolean mounted;
10835                if (Environment.isExternalStorageEmulated()) {
10836                    mounted = true;
10837                } else {
10838                    final String status = Environment.getExternalStorageState();
10839                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10840                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10841                }
10842
10843                if (mounted) {
10844                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10845
10846                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10847                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10848
10849                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10850                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10851
10852                    // Always subtract cache size, since it's a subdirectory
10853                    mStats.externalDataSize -= mStats.externalCacheSize;
10854
10855                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10856                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10857
10858                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10859                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10860                }
10861            }
10862        }
10863
10864        @Override
10865        void handleReturnCode() {
10866            if (mObserver != null) {
10867                try {
10868                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10869                } catch (RemoteException e) {
10870                    Slog.i(TAG, "Observer no longer exists.");
10871                }
10872            }
10873        }
10874
10875        @Override
10876        void handleServiceError() {
10877            Slog.e(TAG, "Could not measure application " + mStats.packageName
10878                            + " external storage");
10879        }
10880    }
10881
10882    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10883            throws RemoteException {
10884        long result = 0;
10885        for (File path : paths) {
10886            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10887        }
10888        return result;
10889    }
10890
10891    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10892        for (File path : paths) {
10893            try {
10894                mcs.clearDirectory(path.getAbsolutePath());
10895            } catch (RemoteException e) {
10896            }
10897        }
10898    }
10899
10900    static class OriginInfo {
10901        /**
10902         * Location where install is coming from, before it has been
10903         * copied/renamed into place. This could be a single monolithic APK
10904         * file, or a cluster directory. This location may be untrusted.
10905         */
10906        final File file;
10907        final String cid;
10908
10909        /**
10910         * Flag indicating that {@link #file} or {@link #cid} has already been
10911         * staged, meaning downstream users don't need to defensively copy the
10912         * contents.
10913         */
10914        final boolean staged;
10915
10916        /**
10917         * Flag indicating that {@link #file} or {@link #cid} is an already
10918         * installed app that is being moved.
10919         */
10920        final boolean existing;
10921
10922        final String resolvedPath;
10923        final File resolvedFile;
10924
10925        static OriginInfo fromNothing() {
10926            return new OriginInfo(null, null, false, false);
10927        }
10928
10929        static OriginInfo fromUntrustedFile(File file) {
10930            return new OriginInfo(file, null, false, false);
10931        }
10932
10933        static OriginInfo fromExistingFile(File file) {
10934            return new OriginInfo(file, null, false, true);
10935        }
10936
10937        static OriginInfo fromStagedFile(File file) {
10938            return new OriginInfo(file, null, true, false);
10939        }
10940
10941        static OriginInfo fromStagedContainer(String cid) {
10942            return new OriginInfo(null, cid, true, false);
10943        }
10944
10945        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10946            this.file = file;
10947            this.cid = cid;
10948            this.staged = staged;
10949            this.existing = existing;
10950
10951            if (cid != null) {
10952                resolvedPath = PackageHelper.getSdDir(cid);
10953                resolvedFile = new File(resolvedPath);
10954            } else if (file != null) {
10955                resolvedPath = file.getAbsolutePath();
10956                resolvedFile = file;
10957            } else {
10958                resolvedPath = null;
10959                resolvedFile = null;
10960            }
10961        }
10962    }
10963
10964    static class MoveInfo {
10965        final int moveId;
10966        final String fromUuid;
10967        final String toUuid;
10968        final String packageName;
10969        final String dataAppName;
10970        final int appId;
10971        final String seinfo;
10972
10973        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10974                String dataAppName, int appId, String seinfo) {
10975            this.moveId = moveId;
10976            this.fromUuid = fromUuid;
10977            this.toUuid = toUuid;
10978            this.packageName = packageName;
10979            this.dataAppName = dataAppName;
10980            this.appId = appId;
10981            this.seinfo = seinfo;
10982        }
10983    }
10984
10985    class InstallParams extends HandlerParams {
10986        final OriginInfo origin;
10987        final MoveInfo move;
10988        final IPackageInstallObserver2 observer;
10989        int installFlags;
10990        final String installerPackageName;
10991        final String volumeUuid;
10992        final VerificationParams verificationParams;
10993        private InstallArgs mArgs;
10994        private int mRet;
10995        final String packageAbiOverride;
10996        final String[] grantedRuntimePermissions;
10997
10998        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10999                int installFlags, String installerPackageName, String volumeUuid,
11000                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
11001                String[] grantedPermissions) {
11002            super(user);
11003            this.origin = origin;
11004            this.move = move;
11005            this.observer = observer;
11006            this.installFlags = installFlags;
11007            this.installerPackageName = installerPackageName;
11008            this.volumeUuid = volumeUuid;
11009            this.verificationParams = verificationParams;
11010            this.packageAbiOverride = packageAbiOverride;
11011            this.grantedRuntimePermissions = grantedPermissions;
11012        }
11013
11014        @Override
11015        public String toString() {
11016            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11017                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11018        }
11019
11020        private int installLocationPolicy(PackageInfoLite pkgLite) {
11021            String packageName = pkgLite.packageName;
11022            int installLocation = pkgLite.installLocation;
11023            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11024            // reader
11025            synchronized (mPackages) {
11026                PackageParser.Package pkg = mPackages.get(packageName);
11027                if (pkg != null) {
11028                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11029                        // Check for downgrading.
11030                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11031                            try {
11032                                checkDowngrade(pkg, pkgLite);
11033                            } catch (PackageManagerException e) {
11034                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11035                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11036                            }
11037                        }
11038                        // Check for updated system application.
11039                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11040                            if (onSd) {
11041                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11042                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11043                            }
11044                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11045                        } else {
11046                            if (onSd) {
11047                                // Install flag overrides everything.
11048                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11049                            }
11050                            // If current upgrade specifies particular preference
11051                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11052                                // Application explicitly specified internal.
11053                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11054                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11055                                // App explictly prefers external. Let policy decide
11056                            } else {
11057                                // Prefer previous location
11058                                if (isExternal(pkg)) {
11059                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11060                                }
11061                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11062                            }
11063                        }
11064                    } else {
11065                        // Invalid install. Return error code
11066                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11067                    }
11068                }
11069            }
11070            // All the special cases have been taken care of.
11071            // Return result based on recommended install location.
11072            if (onSd) {
11073                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11074            }
11075            return pkgLite.recommendedInstallLocation;
11076        }
11077
11078        /*
11079         * Invoke remote method to get package information and install
11080         * location values. Override install location based on default
11081         * policy if needed and then create install arguments based
11082         * on the install location.
11083         */
11084        public void handleStartCopy() throws RemoteException {
11085            int ret = PackageManager.INSTALL_SUCCEEDED;
11086
11087            // If we're already staged, we've firmly committed to an install location
11088            if (origin.staged) {
11089                if (origin.file != null) {
11090                    installFlags |= PackageManager.INSTALL_INTERNAL;
11091                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11092                } else if (origin.cid != null) {
11093                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11094                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11095                } else {
11096                    throw new IllegalStateException("Invalid stage location");
11097                }
11098            }
11099
11100            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11101            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11102            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11103            PackageInfoLite pkgLite = null;
11104
11105            if (onInt && onSd) {
11106                // Check if both bits are set.
11107                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11108                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11109            } else if (onSd && ephemeral) {
11110                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11111                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11112            } else {
11113                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11114                        packageAbiOverride);
11115
11116                if (DEBUG_EPHEMERAL && ephemeral) {
11117                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11118                }
11119
11120                /*
11121                 * If we have too little free space, try to free cache
11122                 * before giving up.
11123                 */
11124                if (!origin.staged && pkgLite.recommendedInstallLocation
11125                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11126                    // TODO: focus freeing disk space on the target device
11127                    final StorageManager storage = StorageManager.from(mContext);
11128                    final long lowThreshold = storage.getStorageLowBytes(
11129                            Environment.getDataDirectory());
11130
11131                    final long sizeBytes = mContainerService.calculateInstalledSize(
11132                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11133
11134                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11135                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11136                                installFlags, packageAbiOverride);
11137                    }
11138
11139                    /*
11140                     * The cache free must have deleted the file we
11141                     * downloaded to install.
11142                     *
11143                     * TODO: fix the "freeCache" call to not delete
11144                     *       the file we care about.
11145                     */
11146                    if (pkgLite.recommendedInstallLocation
11147                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11148                        pkgLite.recommendedInstallLocation
11149                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11150                    }
11151                }
11152            }
11153
11154            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11155                int loc = pkgLite.recommendedInstallLocation;
11156                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11157                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11158                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11159                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11160                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11161                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11162                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11163                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11164                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11165                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11166                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11167                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11168                } else {
11169                    // Override with defaults if needed.
11170                    loc = installLocationPolicy(pkgLite);
11171                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11172                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11173                    } else if (!onSd && !onInt) {
11174                        // Override install location with flags
11175                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11176                            // Set the flag to install on external media.
11177                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11178                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11179                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11180                            if (DEBUG_EPHEMERAL) {
11181                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11182                            }
11183                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11184                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11185                                    |PackageManager.INSTALL_INTERNAL);
11186                        } else {
11187                            // Make sure the flag for installing on external
11188                            // media is unset
11189                            installFlags |= PackageManager.INSTALL_INTERNAL;
11190                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11191                        }
11192                    }
11193                }
11194            }
11195
11196            final InstallArgs args = createInstallArgs(this);
11197            mArgs = args;
11198
11199            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11200                // TODO: http://b/22976637
11201                // Apps installed for "all" users use the device owner to verify the app
11202                UserHandle verifierUser = getUser();
11203                if (verifierUser == UserHandle.ALL) {
11204                    verifierUser = UserHandle.SYSTEM;
11205                }
11206
11207                /*
11208                 * Determine if we have any installed package verifiers. If we
11209                 * do, then we'll defer to them to verify the packages.
11210                 */
11211                final int requiredUid = mRequiredVerifierPackage == null ? -1
11212                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
11213                if (!origin.existing && requiredUid != -1
11214                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11215                    final Intent verification = new Intent(
11216                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11217                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11218                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11219                            PACKAGE_MIME_TYPE);
11220                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11221
11222                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11223                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
11224                            verifierUser.getIdentifier());
11225
11226                    if (DEBUG_VERIFY) {
11227                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11228                                + verification.toString() + " with " + pkgLite.verifiers.length
11229                                + " optional verifiers");
11230                    }
11231
11232                    final int verificationId = mPendingVerificationToken++;
11233
11234                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11235
11236                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11237                            installerPackageName);
11238
11239                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11240                            installFlags);
11241
11242                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11243                            pkgLite.packageName);
11244
11245                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11246                            pkgLite.versionCode);
11247
11248                    if (verificationParams != null) {
11249                        if (verificationParams.getVerificationURI() != null) {
11250                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11251                                 verificationParams.getVerificationURI());
11252                        }
11253                        if (verificationParams.getOriginatingURI() != null) {
11254                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11255                                  verificationParams.getOriginatingURI());
11256                        }
11257                        if (verificationParams.getReferrer() != null) {
11258                            verification.putExtra(Intent.EXTRA_REFERRER,
11259                                  verificationParams.getReferrer());
11260                        }
11261                        if (verificationParams.getOriginatingUid() >= 0) {
11262                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11263                                  verificationParams.getOriginatingUid());
11264                        }
11265                        if (verificationParams.getInstallerUid() >= 0) {
11266                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11267                                  verificationParams.getInstallerUid());
11268                        }
11269                    }
11270
11271                    final PackageVerificationState verificationState = new PackageVerificationState(
11272                            requiredUid, args);
11273
11274                    mPendingVerification.append(verificationId, verificationState);
11275
11276                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11277                            receivers, verificationState);
11278
11279                    /*
11280                     * If any sufficient verifiers were listed in the package
11281                     * manifest, attempt to ask them.
11282                     */
11283                    if (sufficientVerifiers != null) {
11284                        final int N = sufficientVerifiers.size();
11285                        if (N == 0) {
11286                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11287                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11288                        } else {
11289                            for (int i = 0; i < N; i++) {
11290                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11291
11292                                final Intent sufficientIntent = new Intent(verification);
11293                                sufficientIntent.setComponent(verifierComponent);
11294                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11295                            }
11296                        }
11297                    }
11298
11299                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11300                            mRequiredVerifierPackage, receivers);
11301                    if (ret == PackageManager.INSTALL_SUCCEEDED
11302                            && mRequiredVerifierPackage != null) {
11303                        Trace.asyncTraceBegin(
11304                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11305                        /*
11306                         * Send the intent to the required verification agent,
11307                         * but only start the verification timeout after the
11308                         * target BroadcastReceivers have run.
11309                         */
11310                        verification.setComponent(requiredVerifierComponent);
11311                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11312                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11313                                new BroadcastReceiver() {
11314                                    @Override
11315                                    public void onReceive(Context context, Intent intent) {
11316                                        final Message msg = mHandler
11317                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11318                                        msg.arg1 = verificationId;
11319                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11320                                    }
11321                                }, null, 0, null, null);
11322
11323                        /*
11324                         * We don't want the copy to proceed until verification
11325                         * succeeds, so null out this field.
11326                         */
11327                        mArgs = null;
11328                    }
11329                } else {
11330                    /*
11331                     * No package verification is enabled, so immediately start
11332                     * the remote call to initiate copy using temporary file.
11333                     */
11334                    ret = args.copyApk(mContainerService, true);
11335                }
11336            }
11337
11338            mRet = ret;
11339        }
11340
11341        @Override
11342        void handleReturnCode() {
11343            // If mArgs is null, then MCS couldn't be reached. When it
11344            // reconnects, it will try again to install. At that point, this
11345            // will succeed.
11346            if (mArgs != null) {
11347                processPendingInstall(mArgs, mRet);
11348            }
11349        }
11350
11351        @Override
11352        void handleServiceError() {
11353            mArgs = createInstallArgs(this);
11354            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11355        }
11356
11357        public boolean isForwardLocked() {
11358            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11359        }
11360    }
11361
11362    /**
11363     * Used during creation of InstallArgs
11364     *
11365     * @param installFlags package installation flags
11366     * @return true if should be installed on external storage
11367     */
11368    private static boolean installOnExternalAsec(int installFlags) {
11369        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11370            return false;
11371        }
11372        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11373            return true;
11374        }
11375        return false;
11376    }
11377
11378    /**
11379     * Used during creation of InstallArgs
11380     *
11381     * @param installFlags package installation flags
11382     * @return true if should be installed as forward locked
11383     */
11384    private static boolean installForwardLocked(int installFlags) {
11385        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11386    }
11387
11388    private InstallArgs createInstallArgs(InstallParams params) {
11389        if (params.move != null) {
11390            return new MoveInstallArgs(params);
11391        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11392            return new AsecInstallArgs(params);
11393        } else {
11394            return new FileInstallArgs(params);
11395        }
11396    }
11397
11398    /**
11399     * Create args that describe an existing installed package. Typically used
11400     * when cleaning up old installs, or used as a move source.
11401     */
11402    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11403            String resourcePath, String[] instructionSets) {
11404        final boolean isInAsec;
11405        if (installOnExternalAsec(installFlags)) {
11406            /* Apps on SD card are always in ASEC containers. */
11407            isInAsec = true;
11408        } else if (installForwardLocked(installFlags)
11409                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11410            /*
11411             * Forward-locked apps are only in ASEC containers if they're the
11412             * new style
11413             */
11414            isInAsec = true;
11415        } else {
11416            isInAsec = false;
11417        }
11418
11419        if (isInAsec) {
11420            return new AsecInstallArgs(codePath, instructionSets,
11421                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11422        } else {
11423            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11424        }
11425    }
11426
11427    static abstract class InstallArgs {
11428        /** @see InstallParams#origin */
11429        final OriginInfo origin;
11430        /** @see InstallParams#move */
11431        final MoveInfo move;
11432
11433        final IPackageInstallObserver2 observer;
11434        // Always refers to PackageManager flags only
11435        final int installFlags;
11436        final String installerPackageName;
11437        final String volumeUuid;
11438        final UserHandle user;
11439        final String abiOverride;
11440        final String[] installGrantPermissions;
11441        /** If non-null, drop an async trace when the install completes */
11442        final String traceMethod;
11443        final int traceCookie;
11444
11445        // The list of instruction sets supported by this app. This is currently
11446        // only used during the rmdex() phase to clean up resources. We can get rid of this
11447        // if we move dex files under the common app path.
11448        /* nullable */ String[] instructionSets;
11449
11450        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11451                int installFlags, String installerPackageName, String volumeUuid,
11452                UserHandle user, String[] instructionSets,
11453                String abiOverride, String[] installGrantPermissions,
11454                String traceMethod, int traceCookie) {
11455            this.origin = origin;
11456            this.move = move;
11457            this.installFlags = installFlags;
11458            this.observer = observer;
11459            this.installerPackageName = installerPackageName;
11460            this.volumeUuid = volumeUuid;
11461            this.user = user;
11462            this.instructionSets = instructionSets;
11463            this.abiOverride = abiOverride;
11464            this.installGrantPermissions = installGrantPermissions;
11465            this.traceMethod = traceMethod;
11466            this.traceCookie = traceCookie;
11467        }
11468
11469        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11470        abstract int doPreInstall(int status);
11471
11472        /**
11473         * Rename package into final resting place. All paths on the given
11474         * scanned package should be updated to reflect the rename.
11475         */
11476        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11477        abstract int doPostInstall(int status, int uid);
11478
11479        /** @see PackageSettingBase#codePathString */
11480        abstract String getCodePath();
11481        /** @see PackageSettingBase#resourcePathString */
11482        abstract String getResourcePath();
11483
11484        // Need installer lock especially for dex file removal.
11485        abstract void cleanUpResourcesLI();
11486        abstract boolean doPostDeleteLI(boolean delete);
11487
11488        /**
11489         * Called before the source arguments are copied. This is used mostly
11490         * for MoveParams when it needs to read the source file to put it in the
11491         * destination.
11492         */
11493        int doPreCopy() {
11494            return PackageManager.INSTALL_SUCCEEDED;
11495        }
11496
11497        /**
11498         * Called after the source arguments are copied. This is used mostly for
11499         * MoveParams when it needs to read the source file to put it in the
11500         * destination.
11501         *
11502         * @return
11503         */
11504        int doPostCopy(int uid) {
11505            return PackageManager.INSTALL_SUCCEEDED;
11506        }
11507
11508        protected boolean isFwdLocked() {
11509            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11510        }
11511
11512        protected boolean isExternalAsec() {
11513            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11514        }
11515
11516        protected boolean isEphemeral() {
11517            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11518        }
11519
11520        UserHandle getUser() {
11521            return user;
11522        }
11523    }
11524
11525    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11526        if (!allCodePaths.isEmpty()) {
11527            if (instructionSets == null) {
11528                throw new IllegalStateException("instructionSet == null");
11529            }
11530            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11531            for (String codePath : allCodePaths) {
11532                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11533                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11534                    if (retCode < 0) {
11535                        Slog.w(TAG, "Couldn't remove dex file for package: "
11536                                + " at location " + codePath + ", retcode=" + retCode);
11537                        // we don't consider this to be a failure of the core package deletion
11538                    }
11539                }
11540            }
11541        }
11542    }
11543
11544    /**
11545     * Logic to handle installation of non-ASEC applications, including copying
11546     * and renaming logic.
11547     */
11548    class FileInstallArgs extends InstallArgs {
11549        private File codeFile;
11550        private File resourceFile;
11551
11552        // Example topology:
11553        // /data/app/com.example/base.apk
11554        // /data/app/com.example/split_foo.apk
11555        // /data/app/com.example/lib/arm/libfoo.so
11556        // /data/app/com.example/lib/arm64/libfoo.so
11557        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11558
11559        /** New install */
11560        FileInstallArgs(InstallParams params) {
11561            super(params.origin, params.move, params.observer, params.installFlags,
11562                    params.installerPackageName, params.volumeUuid,
11563                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11564                    params.grantedRuntimePermissions,
11565                    params.traceMethod, params.traceCookie);
11566            if (isFwdLocked()) {
11567                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11568            }
11569        }
11570
11571        /** Existing install */
11572        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11573            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11574                    null, null, null, 0);
11575            this.codeFile = (codePath != null) ? new File(codePath) : null;
11576            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11577        }
11578
11579        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11580            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11581            try {
11582                return doCopyApk(imcs, temp);
11583            } finally {
11584                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11585            }
11586        }
11587
11588        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11589            if (origin.staged) {
11590                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11591                codeFile = origin.file;
11592                resourceFile = origin.file;
11593                return PackageManager.INSTALL_SUCCEEDED;
11594            }
11595
11596            try {
11597                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11598                final File tempDir =
11599                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11600                codeFile = tempDir;
11601                resourceFile = tempDir;
11602            } catch (IOException e) {
11603                Slog.w(TAG, "Failed to create copy file: " + e);
11604                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11605            }
11606
11607            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11608                @Override
11609                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11610                    if (!FileUtils.isValidExtFilename(name)) {
11611                        throw new IllegalArgumentException("Invalid filename: " + name);
11612                    }
11613                    try {
11614                        final File file = new File(codeFile, name);
11615                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11616                                O_RDWR | O_CREAT, 0644);
11617                        Os.chmod(file.getAbsolutePath(), 0644);
11618                        return new ParcelFileDescriptor(fd);
11619                    } catch (ErrnoException e) {
11620                        throw new RemoteException("Failed to open: " + e.getMessage());
11621                    }
11622                }
11623            };
11624
11625            int ret = PackageManager.INSTALL_SUCCEEDED;
11626            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11627            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11628                Slog.e(TAG, "Failed to copy package");
11629                return ret;
11630            }
11631
11632            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11633            NativeLibraryHelper.Handle handle = null;
11634            try {
11635                handle = NativeLibraryHelper.Handle.create(codeFile);
11636                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11637                        abiOverride);
11638            } catch (IOException e) {
11639                Slog.e(TAG, "Copying native libraries failed", e);
11640                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11641            } finally {
11642                IoUtils.closeQuietly(handle);
11643            }
11644
11645            return ret;
11646        }
11647
11648        int doPreInstall(int status) {
11649            if (status != PackageManager.INSTALL_SUCCEEDED) {
11650                cleanUp();
11651            }
11652            return status;
11653        }
11654
11655        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11656            if (status != PackageManager.INSTALL_SUCCEEDED) {
11657                cleanUp();
11658                return false;
11659            }
11660
11661            final File targetDir = codeFile.getParentFile();
11662            final File beforeCodeFile = codeFile;
11663            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11664
11665            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11666            try {
11667                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11668            } catch (ErrnoException e) {
11669                Slog.w(TAG, "Failed to rename", e);
11670                return false;
11671            }
11672
11673            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11674                Slog.w(TAG, "Failed to restorecon");
11675                return false;
11676            }
11677
11678            // Reflect the rename internally
11679            codeFile = afterCodeFile;
11680            resourceFile = afterCodeFile;
11681
11682            // Reflect the rename in scanned details
11683            pkg.codePath = afterCodeFile.getAbsolutePath();
11684            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11685                    pkg.baseCodePath);
11686            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11687                    pkg.splitCodePaths);
11688
11689            // Reflect the rename in app info
11690            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11691            pkg.applicationInfo.setCodePath(pkg.codePath);
11692            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11693            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11694            pkg.applicationInfo.setResourcePath(pkg.codePath);
11695            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11696            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11697
11698            return true;
11699        }
11700
11701        int doPostInstall(int status, int uid) {
11702            if (status != PackageManager.INSTALL_SUCCEEDED) {
11703                cleanUp();
11704            }
11705            return status;
11706        }
11707
11708        @Override
11709        String getCodePath() {
11710            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11711        }
11712
11713        @Override
11714        String getResourcePath() {
11715            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11716        }
11717
11718        private boolean cleanUp() {
11719            if (codeFile == null || !codeFile.exists()) {
11720                return false;
11721            }
11722
11723            if (codeFile.isDirectory()) {
11724                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11725            } else {
11726                codeFile.delete();
11727            }
11728
11729            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11730                resourceFile.delete();
11731            }
11732
11733            return true;
11734        }
11735
11736        void cleanUpResourcesLI() {
11737            // Try enumerating all code paths before deleting
11738            List<String> allCodePaths = Collections.EMPTY_LIST;
11739            if (codeFile != null && codeFile.exists()) {
11740                try {
11741                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11742                    allCodePaths = pkg.getAllCodePaths();
11743                } catch (PackageParserException e) {
11744                    // Ignored; we tried our best
11745                }
11746            }
11747
11748            cleanUp();
11749            removeDexFiles(allCodePaths, instructionSets);
11750        }
11751
11752        boolean doPostDeleteLI(boolean delete) {
11753            // XXX err, shouldn't we respect the delete flag?
11754            cleanUpResourcesLI();
11755            return true;
11756        }
11757    }
11758
11759    private boolean isAsecExternal(String cid) {
11760        final String asecPath = PackageHelper.getSdFilesystem(cid);
11761        return !asecPath.startsWith(mAsecInternalPath);
11762    }
11763
11764    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11765            PackageManagerException {
11766        if (copyRet < 0) {
11767            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11768                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11769                throw new PackageManagerException(copyRet, message);
11770            }
11771        }
11772    }
11773
11774    /**
11775     * Extract the MountService "container ID" from the full code path of an
11776     * .apk.
11777     */
11778    static String cidFromCodePath(String fullCodePath) {
11779        int eidx = fullCodePath.lastIndexOf("/");
11780        String subStr1 = fullCodePath.substring(0, eidx);
11781        int sidx = subStr1.lastIndexOf("/");
11782        return subStr1.substring(sidx+1, eidx);
11783    }
11784
11785    /**
11786     * Logic to handle installation of ASEC applications, including copying and
11787     * renaming logic.
11788     */
11789    class AsecInstallArgs extends InstallArgs {
11790        static final String RES_FILE_NAME = "pkg.apk";
11791        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11792
11793        String cid;
11794        String packagePath;
11795        String resourcePath;
11796
11797        /** New install */
11798        AsecInstallArgs(InstallParams params) {
11799            super(params.origin, params.move, params.observer, params.installFlags,
11800                    params.installerPackageName, params.volumeUuid,
11801                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11802                    params.grantedRuntimePermissions,
11803                    params.traceMethod, params.traceCookie);
11804        }
11805
11806        /** Existing install */
11807        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11808                        boolean isExternal, boolean isForwardLocked) {
11809            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11810                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11811                    instructionSets, null, null, null, 0);
11812            // Hackily pretend we're still looking at a full code path
11813            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11814                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11815            }
11816
11817            // Extract cid from fullCodePath
11818            int eidx = fullCodePath.lastIndexOf("/");
11819            String subStr1 = fullCodePath.substring(0, eidx);
11820            int sidx = subStr1.lastIndexOf("/");
11821            cid = subStr1.substring(sidx+1, eidx);
11822            setMountPath(subStr1);
11823        }
11824
11825        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11826            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11827                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11828                    instructionSets, null, null, null, 0);
11829            this.cid = cid;
11830            setMountPath(PackageHelper.getSdDir(cid));
11831        }
11832
11833        void createCopyFile() {
11834            cid = mInstallerService.allocateExternalStageCidLegacy();
11835        }
11836
11837        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11838            if (origin.staged && origin.cid != null) {
11839                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11840                cid = origin.cid;
11841                setMountPath(PackageHelper.getSdDir(cid));
11842                return PackageManager.INSTALL_SUCCEEDED;
11843            }
11844
11845            if (temp) {
11846                createCopyFile();
11847            } else {
11848                /*
11849                 * Pre-emptively destroy the container since it's destroyed if
11850                 * copying fails due to it existing anyway.
11851                 */
11852                PackageHelper.destroySdDir(cid);
11853            }
11854
11855            final String newMountPath = imcs.copyPackageToContainer(
11856                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11857                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11858
11859            if (newMountPath != null) {
11860                setMountPath(newMountPath);
11861                return PackageManager.INSTALL_SUCCEEDED;
11862            } else {
11863                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11864            }
11865        }
11866
11867        @Override
11868        String getCodePath() {
11869            return packagePath;
11870        }
11871
11872        @Override
11873        String getResourcePath() {
11874            return resourcePath;
11875        }
11876
11877        int doPreInstall(int status) {
11878            if (status != PackageManager.INSTALL_SUCCEEDED) {
11879                // Destroy container
11880                PackageHelper.destroySdDir(cid);
11881            } else {
11882                boolean mounted = PackageHelper.isContainerMounted(cid);
11883                if (!mounted) {
11884                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11885                            Process.SYSTEM_UID);
11886                    if (newMountPath != null) {
11887                        setMountPath(newMountPath);
11888                    } else {
11889                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11890                    }
11891                }
11892            }
11893            return status;
11894        }
11895
11896        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11897            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11898            String newMountPath = null;
11899            if (PackageHelper.isContainerMounted(cid)) {
11900                // Unmount the container
11901                if (!PackageHelper.unMountSdDir(cid)) {
11902                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11903                    return false;
11904                }
11905            }
11906            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11907                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11908                        " which might be stale. Will try to clean up.");
11909                // Clean up the stale container and proceed to recreate.
11910                if (!PackageHelper.destroySdDir(newCacheId)) {
11911                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11912                    return false;
11913                }
11914                // Successfully cleaned up stale container. Try to rename again.
11915                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11916                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11917                            + " inspite of cleaning it up.");
11918                    return false;
11919                }
11920            }
11921            if (!PackageHelper.isContainerMounted(newCacheId)) {
11922                Slog.w(TAG, "Mounting container " + newCacheId);
11923                newMountPath = PackageHelper.mountSdDir(newCacheId,
11924                        getEncryptKey(), Process.SYSTEM_UID);
11925            } else {
11926                newMountPath = PackageHelper.getSdDir(newCacheId);
11927            }
11928            if (newMountPath == null) {
11929                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11930                return false;
11931            }
11932            Log.i(TAG, "Succesfully renamed " + cid +
11933                    " to " + newCacheId +
11934                    " at new path: " + newMountPath);
11935            cid = newCacheId;
11936
11937            final File beforeCodeFile = new File(packagePath);
11938            setMountPath(newMountPath);
11939            final File afterCodeFile = new File(packagePath);
11940
11941            // Reflect the rename in scanned details
11942            pkg.codePath = afterCodeFile.getAbsolutePath();
11943            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11944                    pkg.baseCodePath);
11945            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11946                    pkg.splitCodePaths);
11947
11948            // Reflect the rename in app info
11949            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11950            pkg.applicationInfo.setCodePath(pkg.codePath);
11951            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11952            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11953            pkg.applicationInfo.setResourcePath(pkg.codePath);
11954            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11955            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11956
11957            return true;
11958        }
11959
11960        private void setMountPath(String mountPath) {
11961            final File mountFile = new File(mountPath);
11962
11963            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11964            if (monolithicFile.exists()) {
11965                packagePath = monolithicFile.getAbsolutePath();
11966                if (isFwdLocked()) {
11967                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11968                } else {
11969                    resourcePath = packagePath;
11970                }
11971            } else {
11972                packagePath = mountFile.getAbsolutePath();
11973                resourcePath = packagePath;
11974            }
11975        }
11976
11977        int doPostInstall(int status, int uid) {
11978            if (status != PackageManager.INSTALL_SUCCEEDED) {
11979                cleanUp();
11980            } else {
11981                final int groupOwner;
11982                final String protectedFile;
11983                if (isFwdLocked()) {
11984                    groupOwner = UserHandle.getSharedAppGid(uid);
11985                    protectedFile = RES_FILE_NAME;
11986                } else {
11987                    groupOwner = -1;
11988                    protectedFile = null;
11989                }
11990
11991                if (uid < Process.FIRST_APPLICATION_UID
11992                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11993                    Slog.e(TAG, "Failed to finalize " + cid);
11994                    PackageHelper.destroySdDir(cid);
11995                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11996                }
11997
11998                boolean mounted = PackageHelper.isContainerMounted(cid);
11999                if (!mounted) {
12000                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12001                }
12002            }
12003            return status;
12004        }
12005
12006        private void cleanUp() {
12007            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12008
12009            // Destroy secure container
12010            PackageHelper.destroySdDir(cid);
12011        }
12012
12013        private List<String> getAllCodePaths() {
12014            final File codeFile = new File(getCodePath());
12015            if (codeFile != null && codeFile.exists()) {
12016                try {
12017                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12018                    return pkg.getAllCodePaths();
12019                } catch (PackageParserException e) {
12020                    // Ignored; we tried our best
12021                }
12022            }
12023            return Collections.EMPTY_LIST;
12024        }
12025
12026        void cleanUpResourcesLI() {
12027            // Enumerate all code paths before deleting
12028            cleanUpResourcesLI(getAllCodePaths());
12029        }
12030
12031        private void cleanUpResourcesLI(List<String> allCodePaths) {
12032            cleanUp();
12033            removeDexFiles(allCodePaths, instructionSets);
12034        }
12035
12036        String getPackageName() {
12037            return getAsecPackageName(cid);
12038        }
12039
12040        boolean doPostDeleteLI(boolean delete) {
12041            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12042            final List<String> allCodePaths = getAllCodePaths();
12043            boolean mounted = PackageHelper.isContainerMounted(cid);
12044            if (mounted) {
12045                // Unmount first
12046                if (PackageHelper.unMountSdDir(cid)) {
12047                    mounted = false;
12048                }
12049            }
12050            if (!mounted && delete) {
12051                cleanUpResourcesLI(allCodePaths);
12052            }
12053            return !mounted;
12054        }
12055
12056        @Override
12057        int doPreCopy() {
12058            if (isFwdLocked()) {
12059                if (!PackageHelper.fixSdPermissions(cid,
12060                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
12061                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12062                }
12063            }
12064
12065            return PackageManager.INSTALL_SUCCEEDED;
12066        }
12067
12068        @Override
12069        int doPostCopy(int uid) {
12070            if (isFwdLocked()) {
12071                if (uid < Process.FIRST_APPLICATION_UID
12072                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12073                                RES_FILE_NAME)) {
12074                    Slog.e(TAG, "Failed to finalize " + cid);
12075                    PackageHelper.destroySdDir(cid);
12076                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12077                }
12078            }
12079
12080            return PackageManager.INSTALL_SUCCEEDED;
12081        }
12082    }
12083
12084    /**
12085     * Logic to handle movement of existing installed applications.
12086     */
12087    class MoveInstallArgs extends InstallArgs {
12088        private File codeFile;
12089        private File resourceFile;
12090
12091        /** New install */
12092        MoveInstallArgs(InstallParams params) {
12093            super(params.origin, params.move, params.observer, params.installFlags,
12094                    params.installerPackageName, params.volumeUuid,
12095                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12096                    params.grantedRuntimePermissions,
12097                    params.traceMethod, params.traceCookie);
12098        }
12099
12100        int copyApk(IMediaContainerService imcs, boolean temp) {
12101            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12102                    + move.fromUuid + " to " + move.toUuid);
12103            synchronized (mInstaller) {
12104                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12105                        move.dataAppName, move.appId, move.seinfo) != 0) {
12106                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12107                }
12108            }
12109
12110            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12111            resourceFile = codeFile;
12112            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12113
12114            return PackageManager.INSTALL_SUCCEEDED;
12115        }
12116
12117        int doPreInstall(int status) {
12118            if (status != PackageManager.INSTALL_SUCCEEDED) {
12119                cleanUp(move.toUuid);
12120            }
12121            return status;
12122        }
12123
12124        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12125            if (status != PackageManager.INSTALL_SUCCEEDED) {
12126                cleanUp(move.toUuid);
12127                return false;
12128            }
12129
12130            // Reflect the move in app info
12131            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12132            pkg.applicationInfo.setCodePath(pkg.codePath);
12133            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12134            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12135            pkg.applicationInfo.setResourcePath(pkg.codePath);
12136            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12137            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12138
12139            return true;
12140        }
12141
12142        int doPostInstall(int status, int uid) {
12143            if (status == PackageManager.INSTALL_SUCCEEDED) {
12144                cleanUp(move.fromUuid);
12145            } else {
12146                cleanUp(move.toUuid);
12147            }
12148            return status;
12149        }
12150
12151        @Override
12152        String getCodePath() {
12153            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12154        }
12155
12156        @Override
12157        String getResourcePath() {
12158            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12159        }
12160
12161        private boolean cleanUp(String volumeUuid) {
12162            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12163                    move.dataAppName);
12164            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12165            synchronized (mInstallLock) {
12166                // Clean up both app data and code
12167                removeDataDirsLI(volumeUuid, move.packageName);
12168                if (codeFile.isDirectory()) {
12169                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12170                } else {
12171                    codeFile.delete();
12172                }
12173            }
12174            return true;
12175        }
12176
12177        void cleanUpResourcesLI() {
12178            throw new UnsupportedOperationException();
12179        }
12180
12181        boolean doPostDeleteLI(boolean delete) {
12182            throw new UnsupportedOperationException();
12183        }
12184    }
12185
12186    static String getAsecPackageName(String packageCid) {
12187        int idx = packageCid.lastIndexOf("-");
12188        if (idx == -1) {
12189            return packageCid;
12190        }
12191        return packageCid.substring(0, idx);
12192    }
12193
12194    // Utility method used to create code paths based on package name and available index.
12195    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12196        String idxStr = "";
12197        int idx = 1;
12198        // Fall back to default value of idx=1 if prefix is not
12199        // part of oldCodePath
12200        if (oldCodePath != null) {
12201            String subStr = oldCodePath;
12202            // Drop the suffix right away
12203            if (suffix != null && subStr.endsWith(suffix)) {
12204                subStr = subStr.substring(0, subStr.length() - suffix.length());
12205            }
12206            // If oldCodePath already contains prefix find out the
12207            // ending index to either increment or decrement.
12208            int sidx = subStr.lastIndexOf(prefix);
12209            if (sidx != -1) {
12210                subStr = subStr.substring(sidx + prefix.length());
12211                if (subStr != null) {
12212                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12213                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12214                    }
12215                    try {
12216                        idx = Integer.parseInt(subStr);
12217                        if (idx <= 1) {
12218                            idx++;
12219                        } else {
12220                            idx--;
12221                        }
12222                    } catch(NumberFormatException e) {
12223                    }
12224                }
12225            }
12226        }
12227        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12228        return prefix + idxStr;
12229    }
12230
12231    private File getNextCodePath(File targetDir, String packageName) {
12232        int suffix = 1;
12233        File result;
12234        do {
12235            result = new File(targetDir, packageName + "-" + suffix);
12236            suffix++;
12237        } while (result.exists());
12238        return result;
12239    }
12240
12241    // Utility method that returns the relative package path with respect
12242    // to the installation directory. Like say for /data/data/com.test-1.apk
12243    // string com.test-1 is returned.
12244    static String deriveCodePathName(String codePath) {
12245        if (codePath == null) {
12246            return null;
12247        }
12248        final File codeFile = new File(codePath);
12249        final String name = codeFile.getName();
12250        if (codeFile.isDirectory()) {
12251            return name;
12252        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12253            final int lastDot = name.lastIndexOf('.');
12254            return name.substring(0, lastDot);
12255        } else {
12256            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12257            return null;
12258        }
12259    }
12260
12261    static class PackageInstalledInfo {
12262        String name;
12263        int uid;
12264        // The set of users that originally had this package installed.
12265        int[] origUsers;
12266        // The set of users that now have this package installed.
12267        int[] newUsers;
12268        PackageParser.Package pkg;
12269        int returnCode;
12270        String returnMsg;
12271        PackageRemovedInfo removedInfo;
12272
12273        public void setError(int code, String msg) {
12274            returnCode = code;
12275            returnMsg = msg;
12276            Slog.w(TAG, msg);
12277        }
12278
12279        public void setError(String msg, PackageParserException e) {
12280            returnCode = e.error;
12281            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12282            Slog.w(TAG, msg, e);
12283        }
12284
12285        public void setError(String msg, PackageManagerException e) {
12286            returnCode = e.error;
12287            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12288            Slog.w(TAG, msg, e);
12289        }
12290
12291        // In some error cases we want to convey more info back to the observer
12292        String origPackage;
12293        String origPermission;
12294    }
12295
12296    /*
12297     * Install a non-existing package.
12298     */
12299    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12300            UserHandle user, String installerPackageName, String volumeUuid,
12301            PackageInstalledInfo res) {
12302        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12303
12304        // Remember this for later, in case we need to rollback this install
12305        String pkgName = pkg.packageName;
12306
12307        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12308        // TODO: b/23350563
12309        final boolean dataDirExists = Environment
12310                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12311
12312        synchronized(mPackages) {
12313            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12314                // A package with the same name is already installed, though
12315                // it has been renamed to an older name.  The package we
12316                // are trying to install should be installed as an update to
12317                // the existing one, but that has not been requested, so bail.
12318                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12319                        + " without first uninstalling package running as "
12320                        + mSettings.mRenamedPackages.get(pkgName));
12321                return;
12322            }
12323            if (mPackages.containsKey(pkgName)) {
12324                // Don't allow installation over an existing package with the same name.
12325                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12326                        + " without first uninstalling.");
12327                return;
12328            }
12329        }
12330
12331        try {
12332            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12333                    System.currentTimeMillis(), user);
12334
12335            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12336            // delete the partially installed application. the data directory will have to be
12337            // restored if it was already existing
12338            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12339                // remove package from internal structures.  Note that we want deletePackageX to
12340                // delete the package data and cache directories that it created in
12341                // scanPackageLocked, unless those directories existed before we even tried to
12342                // install.
12343                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12344                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12345                                res.removedInfo, true);
12346            }
12347
12348        } catch (PackageManagerException e) {
12349            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12350        }
12351
12352        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12353    }
12354
12355    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12356        // Can't rotate keys during boot or if sharedUser.
12357        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12358                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12359            return false;
12360        }
12361        // app is using upgradeKeySets; make sure all are valid
12362        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12363        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12364        for (int i = 0; i < upgradeKeySets.length; i++) {
12365            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12366                Slog.wtf(TAG, "Package "
12367                         + (oldPs.name != null ? oldPs.name : "<null>")
12368                         + " contains upgrade-key-set reference to unknown key-set: "
12369                         + upgradeKeySets[i]
12370                         + " reverting to signatures check.");
12371                return false;
12372            }
12373        }
12374        return true;
12375    }
12376
12377    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12378        // Upgrade keysets are being used.  Determine if new package has a superset of the
12379        // required keys.
12380        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12381        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12382        for (int i = 0; i < upgradeKeySets.length; i++) {
12383            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12384            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12385                return true;
12386            }
12387        }
12388        return false;
12389    }
12390
12391    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12392            UserHandle user, String installerPackageName, String volumeUuid,
12393            PackageInstalledInfo res) {
12394        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12395
12396        final PackageParser.Package oldPackage;
12397        final String pkgName = pkg.packageName;
12398        final int[] allUsers;
12399        final boolean[] perUserInstalled;
12400
12401        // First find the old package info and check signatures
12402        synchronized(mPackages) {
12403            oldPackage = mPackages.get(pkgName);
12404            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12405            if (isEphemeral && !oldIsEphemeral) {
12406                // can't downgrade from full to ephemeral
12407                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12408                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12409                return;
12410            }
12411            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12412            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12413            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12414                if(!checkUpgradeKeySetLP(ps, pkg)) {
12415                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12416                            "New package not signed by keys specified by upgrade-keysets: "
12417                            + pkgName);
12418                    return;
12419                }
12420            } else {
12421                // default to original signature matching
12422                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12423                    != PackageManager.SIGNATURE_MATCH) {
12424                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12425                            "New package has a different signature: " + pkgName);
12426                    return;
12427                }
12428            }
12429
12430            // In case of rollback, remember per-user/profile install state
12431            allUsers = sUserManager.getUserIds();
12432            perUserInstalled = new boolean[allUsers.length];
12433            for (int i = 0; i < allUsers.length; i++) {
12434                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12435            }
12436        }
12437
12438        boolean sysPkg = (isSystemApp(oldPackage));
12439        if (sysPkg) {
12440            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12441                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12442        } else {
12443            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12444                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12445        }
12446    }
12447
12448    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12449            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12450            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12451            String volumeUuid, PackageInstalledInfo res) {
12452        String pkgName = deletedPackage.packageName;
12453        boolean deletedPkg = true;
12454        boolean updatedSettings = false;
12455
12456        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12457                + deletedPackage);
12458        long origUpdateTime;
12459        if (pkg.mExtras != null) {
12460            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12461        } else {
12462            origUpdateTime = 0;
12463        }
12464
12465        // First delete the existing package while retaining the data directory
12466        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12467                res.removedInfo, true)) {
12468            // If the existing package wasn't successfully deleted
12469            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12470            deletedPkg = false;
12471        } else {
12472            // Successfully deleted the old package; proceed with replace.
12473
12474            // If deleted package lived in a container, give users a chance to
12475            // relinquish resources before killing.
12476            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12477                if (DEBUG_INSTALL) {
12478                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12479                }
12480                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12481                final ArrayList<String> pkgList = new ArrayList<String>(1);
12482                pkgList.add(deletedPackage.applicationInfo.packageName);
12483                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12484            }
12485
12486            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12487            try {
12488                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12489                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12490                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12491                        perUserInstalled, res, user);
12492                updatedSettings = true;
12493            } catch (PackageManagerException e) {
12494                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12495            }
12496        }
12497
12498        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12499            // remove package from internal structures.  Note that we want deletePackageX to
12500            // delete the package data and cache directories that it created in
12501            // scanPackageLocked, unless those directories existed before we even tried to
12502            // install.
12503            if(updatedSettings) {
12504                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12505                deletePackageLI(
12506                        pkgName, null, true, allUsers, perUserInstalled,
12507                        PackageManager.DELETE_KEEP_DATA,
12508                                res.removedInfo, true);
12509            }
12510            // Since we failed to install the new package we need to restore the old
12511            // package that we deleted.
12512            if (deletedPkg) {
12513                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12514                File restoreFile = new File(deletedPackage.codePath);
12515                // Parse old package
12516                boolean oldExternal = isExternal(deletedPackage);
12517                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12518                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12519                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12520                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12521                try {
12522                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12523                            null);
12524                } catch (PackageManagerException e) {
12525                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12526                            + e.getMessage());
12527                    return;
12528                }
12529                // Restore of old package succeeded. Update permissions.
12530                // writer
12531                synchronized (mPackages) {
12532                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12533                            UPDATE_PERMISSIONS_ALL);
12534                    // can downgrade to reader
12535                    mSettings.writeLPr();
12536                }
12537                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12538            }
12539        }
12540    }
12541
12542    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12543            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12544            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12545            String volumeUuid, PackageInstalledInfo res) {
12546        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12547                + ", old=" + deletedPackage);
12548        boolean disabledSystem = false;
12549        boolean updatedSettings = false;
12550        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12551        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12552                != 0) {
12553            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12554        }
12555        String packageName = deletedPackage.packageName;
12556        if (packageName == null) {
12557            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12558                    "Attempt to delete null packageName.");
12559            return;
12560        }
12561        PackageParser.Package oldPkg;
12562        PackageSetting oldPkgSetting;
12563        // reader
12564        synchronized (mPackages) {
12565            oldPkg = mPackages.get(packageName);
12566            oldPkgSetting = mSettings.mPackages.get(packageName);
12567            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12568                    (oldPkgSetting == null)) {
12569                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12570                        "Couldn't find package:" + packageName + " information");
12571                return;
12572            }
12573        }
12574
12575        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12576
12577        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12578        res.removedInfo.removedPackage = packageName;
12579        // Remove existing system package
12580        removePackageLI(oldPkgSetting, true);
12581        // writer
12582        synchronized (mPackages) {
12583            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12584            if (!disabledSystem && deletedPackage != null) {
12585                // We didn't need to disable the .apk as a current system package,
12586                // which means we are replacing another update that is already
12587                // installed.  We need to make sure to delete the older one's .apk.
12588                res.removedInfo.args = createInstallArgsForExisting(0,
12589                        deletedPackage.applicationInfo.getCodePath(),
12590                        deletedPackage.applicationInfo.getResourcePath(),
12591                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12592            } else {
12593                res.removedInfo.args = null;
12594            }
12595        }
12596
12597        // Successfully disabled the old package. Now proceed with re-installation
12598        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12599
12600        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12601        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12602
12603        PackageParser.Package newPackage = null;
12604        try {
12605            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12606            if (newPackage.mExtras != null) {
12607                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12608                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12609                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12610
12611                // is the update attempting to change shared user? that isn't going to work...
12612                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12613                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12614                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12615                            + " to " + newPkgSetting.sharedUser);
12616                    updatedSettings = true;
12617                }
12618            }
12619
12620            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12621                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12622                        perUserInstalled, res, user);
12623                updatedSettings = true;
12624            }
12625
12626        } catch (PackageManagerException e) {
12627            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12628        }
12629
12630        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12631            // Re installation failed. Restore old information
12632            // Remove new pkg information
12633            if (newPackage != null) {
12634                removeInstalledPackageLI(newPackage, true);
12635            }
12636            // Add back the old system package
12637            try {
12638                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12639            } catch (PackageManagerException e) {
12640                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12641            }
12642            // Restore the old system information in Settings
12643            synchronized (mPackages) {
12644                if (disabledSystem) {
12645                    mSettings.enableSystemPackageLPw(packageName);
12646                }
12647                if (updatedSettings) {
12648                    mSettings.setInstallerPackageName(packageName,
12649                            oldPkgSetting.installerPackageName);
12650                }
12651                mSettings.writeLPr();
12652            }
12653        }
12654    }
12655
12656    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12657        // Collect all used permissions in the UID
12658        ArraySet<String> usedPermissions = new ArraySet<>();
12659        final int packageCount = su.packages.size();
12660        for (int i = 0; i < packageCount; i++) {
12661            PackageSetting ps = su.packages.valueAt(i);
12662            if (ps.pkg == null) {
12663                continue;
12664            }
12665            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12666            for (int j = 0; j < requestedPermCount; j++) {
12667                String permission = ps.pkg.requestedPermissions.get(j);
12668                BasePermission bp = mSettings.mPermissions.get(permission);
12669                if (bp != null) {
12670                    usedPermissions.add(permission);
12671                }
12672            }
12673        }
12674
12675        PermissionsState permissionsState = su.getPermissionsState();
12676        // Prune install permissions
12677        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12678        final int installPermCount = installPermStates.size();
12679        for (int i = installPermCount - 1; i >= 0;  i--) {
12680            PermissionState permissionState = installPermStates.get(i);
12681            if (!usedPermissions.contains(permissionState.getName())) {
12682                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12683                if (bp != null) {
12684                    permissionsState.revokeInstallPermission(bp);
12685                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12686                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12687                }
12688            }
12689        }
12690
12691        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12692
12693        // Prune runtime permissions
12694        for (int userId : allUserIds) {
12695            List<PermissionState> runtimePermStates = permissionsState
12696                    .getRuntimePermissionStates(userId);
12697            final int runtimePermCount = runtimePermStates.size();
12698            for (int i = runtimePermCount - 1; i >= 0; i--) {
12699                PermissionState permissionState = runtimePermStates.get(i);
12700                if (!usedPermissions.contains(permissionState.getName())) {
12701                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12702                    if (bp != null) {
12703                        permissionsState.revokeRuntimePermission(bp, userId);
12704                        permissionsState.updatePermissionFlags(bp, userId,
12705                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12706                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12707                                runtimePermissionChangedUserIds, userId);
12708                    }
12709                }
12710            }
12711        }
12712
12713        return runtimePermissionChangedUserIds;
12714    }
12715
12716    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12717            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12718            UserHandle user) {
12719        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12720
12721        String pkgName = newPackage.packageName;
12722        synchronized (mPackages) {
12723            //write settings. the installStatus will be incomplete at this stage.
12724            //note that the new package setting would have already been
12725            //added to mPackages. It hasn't been persisted yet.
12726            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12727            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12728            mSettings.writeLPr();
12729            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12730        }
12731
12732        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12733        synchronized (mPackages) {
12734            updatePermissionsLPw(newPackage.packageName, newPackage,
12735                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12736                            ? UPDATE_PERMISSIONS_ALL : 0));
12737            // For system-bundled packages, we assume that installing an upgraded version
12738            // of the package implies that the user actually wants to run that new code,
12739            // so we enable the package.
12740            PackageSetting ps = mSettings.mPackages.get(pkgName);
12741            if (ps != null) {
12742                if (isSystemApp(newPackage)) {
12743                    // NB: implicit assumption that system package upgrades apply to all users
12744                    if (DEBUG_INSTALL) {
12745                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12746                    }
12747                    if (res.origUsers != null) {
12748                        for (int userHandle : res.origUsers) {
12749                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12750                                    userHandle, installerPackageName);
12751                        }
12752                    }
12753                    // Also convey the prior install/uninstall state
12754                    if (allUsers != null && perUserInstalled != null) {
12755                        for (int i = 0; i < allUsers.length; i++) {
12756                            if (DEBUG_INSTALL) {
12757                                Slog.d(TAG, "    user " + allUsers[i]
12758                                        + " => " + perUserInstalled[i]);
12759                            }
12760                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12761                        }
12762                        // these install state changes will be persisted in the
12763                        // upcoming call to mSettings.writeLPr().
12764                    }
12765                }
12766                // It's implied that when a user requests installation, they want the app to be
12767                // installed and enabled.
12768                int userId = user.getIdentifier();
12769                if (userId != UserHandle.USER_ALL) {
12770                    ps.setInstalled(true, userId);
12771                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12772                }
12773            }
12774            res.name = pkgName;
12775            res.uid = newPackage.applicationInfo.uid;
12776            res.pkg = newPackage;
12777            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12778            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12779            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12780            //to update install status
12781            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12782            mSettings.writeLPr();
12783            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12784        }
12785
12786        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12787    }
12788
12789    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12790        try {
12791            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12792            installPackageLI(args, res);
12793        } finally {
12794            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12795        }
12796    }
12797
12798    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12799        final int installFlags = args.installFlags;
12800        final String installerPackageName = args.installerPackageName;
12801        final String volumeUuid = args.volumeUuid;
12802        final File tmpPackageFile = new File(args.getCodePath());
12803        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12804        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12805                || (args.volumeUuid != null));
12806        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12807        boolean replace = false;
12808        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12809        if (args.move != null) {
12810            // moving a complete application; perfom an initial scan on the new install location
12811            scanFlags |= SCAN_INITIAL;
12812        }
12813        // Result object to be returned
12814        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12815
12816        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12817
12818        // Sanity check
12819        if (ephemeral && (forwardLocked || onExternal)) {
12820            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12821                    + " external=" + onExternal);
12822            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12823            return;
12824        }
12825
12826        // Retrieve PackageSettings and parse package
12827        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12828                | PackageParser.PARSE_ENFORCE_CODE
12829                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12830                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12831                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12832        PackageParser pp = new PackageParser();
12833        pp.setSeparateProcesses(mSeparateProcesses);
12834        pp.setDisplayMetrics(mMetrics);
12835
12836        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12837        final PackageParser.Package pkg;
12838        try {
12839            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12840        } catch (PackageParserException e) {
12841            res.setError("Failed parse during installPackageLI", e);
12842            return;
12843        } finally {
12844            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12845        }
12846
12847        // Mark that we have an install time CPU ABI override.
12848        pkg.cpuAbiOverride = args.abiOverride;
12849
12850        String pkgName = res.name = pkg.packageName;
12851        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12852            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12853                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12854                return;
12855            }
12856        }
12857
12858        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12859        try {
12860            pp.collectCertificates(pkg, parseFlags);
12861        } catch (PackageParserException e) {
12862            res.setError("Failed collect during installPackageLI", e);
12863            return;
12864        } finally {
12865            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12866        }
12867
12868        // Get rid of all references to package scan path via parser.
12869        pp = null;
12870        String oldCodePath = null;
12871        boolean systemApp = false;
12872        synchronized (mPackages) {
12873            // Check if installing already existing package
12874            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12875                String oldName = mSettings.mRenamedPackages.get(pkgName);
12876                if (pkg.mOriginalPackages != null
12877                        && pkg.mOriginalPackages.contains(oldName)
12878                        && mPackages.containsKey(oldName)) {
12879                    // This package is derived from an original package,
12880                    // and this device has been updating from that original
12881                    // name.  We must continue using the original name, so
12882                    // rename the new package here.
12883                    pkg.setPackageName(oldName);
12884                    pkgName = pkg.packageName;
12885                    replace = true;
12886                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12887                            + oldName + " pkgName=" + pkgName);
12888                } else if (mPackages.containsKey(pkgName)) {
12889                    // This package, under its official name, already exists
12890                    // on the device; we should replace it.
12891                    replace = true;
12892                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12893                }
12894
12895                // Prevent apps opting out from runtime permissions
12896                if (replace) {
12897                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12898                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12899                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12900                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12901                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12902                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12903                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12904                                        + " doesn't support runtime permissions but the old"
12905                                        + " target SDK " + oldTargetSdk + " does.");
12906                        return;
12907                    }
12908                }
12909            }
12910
12911            PackageSetting ps = mSettings.mPackages.get(pkgName);
12912            if (ps != null) {
12913                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12914
12915                // Quick sanity check that we're signed correctly if updating;
12916                // we'll check this again later when scanning, but we want to
12917                // bail early here before tripping over redefined permissions.
12918                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12919                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12920                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12921                                + pkg.packageName + " upgrade keys do not match the "
12922                                + "previously installed version");
12923                        return;
12924                    }
12925                } else {
12926                    try {
12927                        verifySignaturesLP(ps, pkg);
12928                    } catch (PackageManagerException e) {
12929                        res.setError(e.error, e.getMessage());
12930                        return;
12931                    }
12932                }
12933
12934                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12935                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12936                    systemApp = (ps.pkg.applicationInfo.flags &
12937                            ApplicationInfo.FLAG_SYSTEM) != 0;
12938                }
12939                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12940            }
12941
12942            // Check whether the newly-scanned package wants to define an already-defined perm
12943            int N = pkg.permissions.size();
12944            for (int i = N-1; i >= 0; i--) {
12945                PackageParser.Permission perm = pkg.permissions.get(i);
12946                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12947                if (bp != null) {
12948                    // If the defining package is signed with our cert, it's okay.  This
12949                    // also includes the "updating the same package" case, of course.
12950                    // "updating same package" could also involve key-rotation.
12951                    final boolean sigsOk;
12952                    if (bp.sourcePackage.equals(pkg.packageName)
12953                            && (bp.packageSetting instanceof PackageSetting)
12954                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12955                                    scanFlags))) {
12956                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12957                    } else {
12958                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12959                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12960                    }
12961                    if (!sigsOk) {
12962                        // If the owning package is the system itself, we log but allow
12963                        // install to proceed; we fail the install on all other permission
12964                        // redefinitions.
12965                        if (!bp.sourcePackage.equals("android")) {
12966                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12967                                    + pkg.packageName + " attempting to redeclare permission "
12968                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12969                            res.origPermission = perm.info.name;
12970                            res.origPackage = bp.sourcePackage;
12971                            return;
12972                        } else {
12973                            Slog.w(TAG, "Package " + pkg.packageName
12974                                    + " attempting to redeclare system permission "
12975                                    + perm.info.name + "; ignoring new declaration");
12976                            pkg.permissions.remove(i);
12977                        }
12978                    }
12979                }
12980            }
12981
12982        }
12983
12984        if (systemApp) {
12985            if (onExternal) {
12986                // Abort update; system app can't be replaced with app on sdcard
12987                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12988                        "Cannot install updates to system apps on sdcard");
12989                return;
12990            } else if (ephemeral) {
12991                // Abort update; system app can't be replaced with an ephemeral app
12992                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12993                        "Cannot update a system app with an ephemeral app");
12994                return;
12995            }
12996        }
12997
12998        if (args.move != null) {
12999            // We did an in-place move, so dex is ready to roll
13000            scanFlags |= SCAN_NO_DEX;
13001            scanFlags |= SCAN_MOVE;
13002
13003            synchronized (mPackages) {
13004                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13005                if (ps == null) {
13006                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13007                            "Missing settings for moved package " + pkgName);
13008                }
13009
13010                // We moved the entire application as-is, so bring over the
13011                // previously derived ABI information.
13012                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13013                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13014            }
13015
13016        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13017            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13018            scanFlags |= SCAN_NO_DEX;
13019
13020            try {
13021                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13022                        true /* extract libs */);
13023            } catch (PackageManagerException pme) {
13024                Slog.e(TAG, "Error deriving application ABI", pme);
13025                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13026                return;
13027            }
13028        }
13029
13030        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13031            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13032            return;
13033        }
13034
13035        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13036
13037        if (replace) {
13038            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13039                    installerPackageName, volumeUuid, res);
13040        } else {
13041            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13042                    args.user, installerPackageName, volumeUuid, res);
13043        }
13044        synchronized (mPackages) {
13045            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13046            if (ps != null) {
13047                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13048            }
13049        }
13050    }
13051
13052    private void startIntentFilterVerifications(int userId, boolean replacing,
13053            PackageParser.Package pkg) {
13054        if (mIntentFilterVerifierComponent == null) {
13055            Slog.w(TAG, "No IntentFilter verification will not be done as "
13056                    + "there is no IntentFilterVerifier available!");
13057            return;
13058        }
13059
13060        final int verifierUid = getPackageUid(
13061                mIntentFilterVerifierComponent.getPackageName(),
13062                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13063
13064        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13065        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13066        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13067        mHandler.sendMessage(msg);
13068    }
13069
13070    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13071            PackageParser.Package pkg) {
13072        int size = pkg.activities.size();
13073        if (size == 0) {
13074            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13075                    "No activity, so no need to verify any IntentFilter!");
13076            return;
13077        }
13078
13079        final boolean hasDomainURLs = hasDomainURLs(pkg);
13080        if (!hasDomainURLs) {
13081            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13082                    "No domain URLs, so no need to verify any IntentFilter!");
13083            return;
13084        }
13085
13086        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13087                + " if any IntentFilter from the " + size
13088                + " Activities needs verification ...");
13089
13090        int count = 0;
13091        final String packageName = pkg.packageName;
13092
13093        synchronized (mPackages) {
13094            // If this is a new install and we see that we've already run verification for this
13095            // package, we have nothing to do: it means the state was restored from backup.
13096            if (!replacing) {
13097                IntentFilterVerificationInfo ivi =
13098                        mSettings.getIntentFilterVerificationLPr(packageName);
13099                if (ivi != null) {
13100                    if (DEBUG_DOMAIN_VERIFICATION) {
13101                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13102                                + ivi.getStatusString());
13103                    }
13104                    return;
13105                }
13106            }
13107
13108            // If any filters need to be verified, then all need to be.
13109            boolean needToVerify = false;
13110            for (PackageParser.Activity a : pkg.activities) {
13111                for (ActivityIntentInfo filter : a.intents) {
13112                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13113                        if (DEBUG_DOMAIN_VERIFICATION) {
13114                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13115                        }
13116                        needToVerify = true;
13117                        break;
13118                    }
13119                }
13120            }
13121
13122            if (needToVerify) {
13123                final int verificationId = mIntentFilterVerificationToken++;
13124                for (PackageParser.Activity a : pkg.activities) {
13125                    for (ActivityIntentInfo filter : a.intents) {
13126                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13127                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13128                                    "Verification needed for IntentFilter:" + filter.toString());
13129                            mIntentFilterVerifier.addOneIntentFilterVerification(
13130                                    verifierUid, userId, verificationId, filter, packageName);
13131                            count++;
13132                        }
13133                    }
13134                }
13135            }
13136        }
13137
13138        if (count > 0) {
13139            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13140                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13141                    +  " for userId:" + userId);
13142            mIntentFilterVerifier.startVerifications(userId);
13143        } else {
13144            if (DEBUG_DOMAIN_VERIFICATION) {
13145                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13146            }
13147        }
13148    }
13149
13150    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13151        final ComponentName cn  = filter.activity.getComponentName();
13152        final String packageName = cn.getPackageName();
13153
13154        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13155                packageName);
13156        if (ivi == null) {
13157            return true;
13158        }
13159        int status = ivi.getStatus();
13160        switch (status) {
13161            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13162            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13163                return true;
13164
13165            default:
13166                // Nothing to do
13167                return false;
13168        }
13169    }
13170
13171    private static boolean isMultiArch(ApplicationInfo info) {
13172        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13173    }
13174
13175    private static boolean isExternal(PackageParser.Package pkg) {
13176        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13177    }
13178
13179    private static boolean isExternal(PackageSetting ps) {
13180        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13181    }
13182
13183    private static boolean isEphemeral(PackageParser.Package pkg) {
13184        return pkg.applicationInfo.isEphemeralApp();
13185    }
13186
13187    private static boolean isEphemeral(PackageSetting ps) {
13188        return ps.pkg != null && isEphemeral(ps.pkg);
13189    }
13190
13191    private static boolean isSystemApp(PackageParser.Package pkg) {
13192        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13193    }
13194
13195    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13196        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13197    }
13198
13199    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13200        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13201    }
13202
13203    private static boolean isSystemApp(PackageSetting ps) {
13204        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13205    }
13206
13207    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13208        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13209    }
13210
13211    private int packageFlagsToInstallFlags(PackageSetting ps) {
13212        int installFlags = 0;
13213        if (isEphemeral(ps)) {
13214            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13215        }
13216        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13217            // This existing package was an external ASEC install when we have
13218            // the external flag without a UUID
13219            installFlags |= PackageManager.INSTALL_EXTERNAL;
13220        }
13221        if (ps.isForwardLocked()) {
13222            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13223        }
13224        return installFlags;
13225    }
13226
13227    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13228        if (isExternal(pkg)) {
13229            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13230                return StorageManager.UUID_PRIMARY_PHYSICAL;
13231            } else {
13232                return pkg.volumeUuid;
13233            }
13234        } else {
13235            return StorageManager.UUID_PRIVATE_INTERNAL;
13236        }
13237    }
13238
13239    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13240        if (isExternal(pkg)) {
13241            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13242                return mSettings.getExternalVersion();
13243            } else {
13244                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13245            }
13246        } else {
13247            return mSettings.getInternalVersion();
13248        }
13249    }
13250
13251    private void deleteTempPackageFiles() {
13252        final FilenameFilter filter = new FilenameFilter() {
13253            public boolean accept(File dir, String name) {
13254                return name.startsWith("vmdl") && name.endsWith(".tmp");
13255            }
13256        };
13257        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13258            file.delete();
13259        }
13260    }
13261
13262    @Override
13263    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13264            int flags) {
13265        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13266                flags);
13267    }
13268
13269    @Override
13270    public void deletePackage(final String packageName,
13271            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13272        mContext.enforceCallingOrSelfPermission(
13273                android.Manifest.permission.DELETE_PACKAGES, null);
13274        Preconditions.checkNotNull(packageName);
13275        Preconditions.checkNotNull(observer);
13276        final int uid = Binder.getCallingUid();
13277        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13278        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13279        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13280            mContext.enforceCallingOrSelfPermission(
13281                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13282                    "deletePackage for user " + userId);
13283        }
13284
13285        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13286            try {
13287                observer.onPackageDeleted(packageName,
13288                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13289            } catch (RemoteException re) {
13290            }
13291            return;
13292        }
13293
13294        for (int currentUserId : users) {
13295            if (getBlockUninstallForUser(packageName, currentUserId)) {
13296                try {
13297                    observer.onPackageDeleted(packageName,
13298                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13299                } catch (RemoteException re) {
13300                }
13301                return;
13302            }
13303        }
13304
13305        if (DEBUG_REMOVE) {
13306            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13307        }
13308        // Queue up an async operation since the package deletion may take a little while.
13309        mHandler.post(new Runnable() {
13310            public void run() {
13311                mHandler.removeCallbacks(this);
13312                final int returnCode = deletePackageX(packageName, userId, flags);
13313                try {
13314                    observer.onPackageDeleted(packageName, returnCode, null);
13315                } catch (RemoteException e) {
13316                    Log.i(TAG, "Observer no longer exists.");
13317                } //end catch
13318            } //end run
13319        });
13320    }
13321
13322    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13323        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13324                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13325        try {
13326            if (dpm != null) {
13327                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13328                        /* callingUserOnly =*/ false);
13329                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13330                        : deviceOwnerComponentName.getPackageName();
13331                // Does the package contains the device owner?
13332                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13333                // this check is probably not needed, since DO should be registered as a device
13334                // admin on some user too. (Original bug for this: b/17657954)
13335                if (packageName.equals(deviceOwnerPackageName)) {
13336                    return true;
13337                }
13338                // Does it contain a device admin for any user?
13339                int[] users;
13340                if (userId == UserHandle.USER_ALL) {
13341                    users = sUserManager.getUserIds();
13342                } else {
13343                    users = new int[]{userId};
13344                }
13345                for (int i = 0; i < users.length; ++i) {
13346                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13347                        return true;
13348                    }
13349                }
13350            }
13351        } catch (RemoteException e) {
13352        }
13353        return false;
13354    }
13355
13356    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13357        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13358    }
13359
13360    /**
13361     *  This method is an internal method that could be get invoked either
13362     *  to delete an installed package or to clean up a failed installation.
13363     *  After deleting an installed package, a broadcast is sent to notify any
13364     *  listeners that the package has been installed. For cleaning up a failed
13365     *  installation, the broadcast is not necessary since the package's
13366     *  installation wouldn't have sent the initial broadcast either
13367     *  The key steps in deleting a package are
13368     *  deleting the package information in internal structures like mPackages,
13369     *  deleting the packages base directories through installd
13370     *  updating mSettings to reflect current status
13371     *  persisting settings for later use
13372     *  sending a broadcast if necessary
13373     */
13374    private int deletePackageX(String packageName, int userId, int flags) {
13375        final PackageRemovedInfo info = new PackageRemovedInfo();
13376        final boolean res;
13377
13378        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13379                ? UserHandle.ALL : new UserHandle(userId);
13380
13381        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13382            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13383            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13384        }
13385
13386        boolean removedForAllUsers = false;
13387        boolean systemUpdate = false;
13388
13389        PackageParser.Package uninstalledPkg;
13390
13391        // for the uninstall-updates case and restricted profiles, remember the per-
13392        // userhandle installed state
13393        int[] allUsers;
13394        boolean[] perUserInstalled;
13395        synchronized (mPackages) {
13396            uninstalledPkg = mPackages.get(packageName);
13397            PackageSetting ps = mSettings.mPackages.get(packageName);
13398            allUsers = sUserManager.getUserIds();
13399            perUserInstalled = new boolean[allUsers.length];
13400            for (int i = 0; i < allUsers.length; i++) {
13401                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13402            }
13403        }
13404
13405        synchronized (mInstallLock) {
13406            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13407            res = deletePackageLI(packageName, removeForUser,
13408                    true, allUsers, perUserInstalled,
13409                    flags | REMOVE_CHATTY, info, true);
13410            systemUpdate = info.isRemovedPackageSystemUpdate;
13411            synchronized (mPackages) {
13412                if (res) {
13413                    if (!systemUpdate && mPackages.get(packageName) == null) {
13414                        removedForAllUsers = true;
13415                    }
13416                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13417                }
13418            }
13419            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13420                    + " removedForAllUsers=" + removedForAllUsers);
13421        }
13422
13423        if (res) {
13424            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13425
13426            // If the removed package was a system update, the old system package
13427            // was re-enabled; we need to broadcast this information
13428            if (systemUpdate) {
13429                Bundle extras = new Bundle(1);
13430                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13431                        ? info.removedAppId : info.uid);
13432                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13433
13434                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13435                        extras, 0, null, null, null);
13436                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13437                        extras, 0, null, null, null);
13438                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13439                        null, 0, packageName, null, null);
13440            }
13441        }
13442        // Force a gc here.
13443        Runtime.getRuntime().gc();
13444        // Delete the resources here after sending the broadcast to let
13445        // other processes clean up before deleting resources.
13446        if (info.args != null) {
13447            synchronized (mInstallLock) {
13448                info.args.doPostDeleteLI(true);
13449            }
13450        }
13451
13452        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13453    }
13454
13455    class PackageRemovedInfo {
13456        String removedPackage;
13457        int uid = -1;
13458        int removedAppId = -1;
13459        int[] removedUsers = null;
13460        boolean isRemovedPackageSystemUpdate = false;
13461        // Clean up resources deleted packages.
13462        InstallArgs args = null;
13463
13464        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13465            Bundle extras = new Bundle(1);
13466            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13467            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13468            if (replacing) {
13469                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13470            }
13471            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13472            if (removedPackage != null) {
13473                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13474                        extras, 0, null, null, removedUsers);
13475                if (fullRemove && !replacing) {
13476                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13477                            extras, 0, null, null, removedUsers);
13478                }
13479            }
13480            if (removedAppId >= 0) {
13481                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13482                        removedUsers);
13483            }
13484        }
13485    }
13486
13487    /*
13488     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13489     * flag is not set, the data directory is removed as well.
13490     * make sure this flag is set for partially installed apps. If not its meaningless to
13491     * delete a partially installed application.
13492     */
13493    private void removePackageDataLI(PackageSetting ps,
13494            int[] allUserHandles, boolean[] perUserInstalled,
13495            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13496        String packageName = ps.name;
13497        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13498        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13499        // Retrieve object to delete permissions for shared user later on
13500        final PackageSetting deletedPs;
13501        // reader
13502        synchronized (mPackages) {
13503            deletedPs = mSettings.mPackages.get(packageName);
13504            if (outInfo != null) {
13505                outInfo.removedPackage = packageName;
13506                outInfo.removedUsers = deletedPs != null
13507                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13508                        : null;
13509            }
13510        }
13511        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13512            removeDataDirsLI(ps.volumeUuid, packageName);
13513            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13514        }
13515        // writer
13516        synchronized (mPackages) {
13517            if (deletedPs != null) {
13518                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13519                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13520                    clearDefaultBrowserIfNeeded(packageName);
13521                    if (outInfo != null) {
13522                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13523                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13524                    }
13525                    updatePermissionsLPw(deletedPs.name, null, 0);
13526                    if (deletedPs.sharedUser != null) {
13527                        // Remove permissions associated with package. Since runtime
13528                        // permissions are per user we have to kill the removed package
13529                        // or packages running under the shared user of the removed
13530                        // package if revoking the permissions requested only by the removed
13531                        // package is successful and this causes a change in gids.
13532                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13533                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13534                                    userId);
13535                            if (userIdToKill == UserHandle.USER_ALL
13536                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13537                                // If gids changed for this user, kill all affected packages.
13538                                mHandler.post(new Runnable() {
13539                                    @Override
13540                                    public void run() {
13541                                        // This has to happen with no lock held.
13542                                        killApplication(deletedPs.name, deletedPs.appId,
13543                                                KILL_APP_REASON_GIDS_CHANGED);
13544                                    }
13545                                });
13546                                break;
13547                            }
13548                        }
13549                    }
13550                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13551                }
13552                // make sure to preserve per-user disabled state if this removal was just
13553                // a downgrade of a system app to the factory package
13554                if (allUserHandles != null && perUserInstalled != null) {
13555                    if (DEBUG_REMOVE) {
13556                        Slog.d(TAG, "Propagating install state across downgrade");
13557                    }
13558                    for (int i = 0; i < allUserHandles.length; i++) {
13559                        if (DEBUG_REMOVE) {
13560                            Slog.d(TAG, "    user " + allUserHandles[i]
13561                                    + " => " + perUserInstalled[i]);
13562                        }
13563                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13564                    }
13565                }
13566            }
13567            // can downgrade to reader
13568            if (writeSettings) {
13569                // Save settings now
13570                mSettings.writeLPr();
13571            }
13572        }
13573        if (outInfo != null) {
13574            // A user ID was deleted here. Go through all users and remove it
13575            // from KeyStore.
13576            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13577        }
13578    }
13579
13580    static boolean locationIsPrivileged(File path) {
13581        try {
13582            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13583                    .getCanonicalPath();
13584            return path.getCanonicalPath().startsWith(privilegedAppDir);
13585        } catch (IOException e) {
13586            Slog.e(TAG, "Unable to access code path " + path);
13587        }
13588        return false;
13589    }
13590
13591    /*
13592     * Tries to delete system package.
13593     */
13594    private boolean deleteSystemPackageLI(PackageSetting newPs,
13595            int[] allUserHandles, boolean[] perUserInstalled,
13596            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13597        final boolean applyUserRestrictions
13598                = (allUserHandles != null) && (perUserInstalled != null);
13599        PackageSetting disabledPs = null;
13600        // Confirm if the system package has been updated
13601        // An updated system app can be deleted. This will also have to restore
13602        // the system pkg from system partition
13603        // reader
13604        synchronized (mPackages) {
13605            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13606        }
13607        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13608                + " disabledPs=" + disabledPs);
13609        if (disabledPs == null) {
13610            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13611            return false;
13612        } else if (DEBUG_REMOVE) {
13613            Slog.d(TAG, "Deleting system pkg from data partition");
13614        }
13615        if (DEBUG_REMOVE) {
13616            if (applyUserRestrictions) {
13617                Slog.d(TAG, "Remembering install states:");
13618                for (int i = 0; i < allUserHandles.length; i++) {
13619                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13620                }
13621            }
13622        }
13623        // Delete the updated package
13624        outInfo.isRemovedPackageSystemUpdate = true;
13625        if (disabledPs.versionCode < newPs.versionCode) {
13626            // Delete data for downgrades
13627            flags &= ~PackageManager.DELETE_KEEP_DATA;
13628        } else {
13629            // Preserve data by setting flag
13630            flags |= PackageManager.DELETE_KEEP_DATA;
13631        }
13632        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13633                allUserHandles, perUserInstalled, outInfo, writeSettings);
13634        if (!ret) {
13635            return false;
13636        }
13637        // writer
13638        synchronized (mPackages) {
13639            // Reinstate the old system package
13640            mSettings.enableSystemPackageLPw(newPs.name);
13641            // Remove any native libraries from the upgraded package.
13642            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13643        }
13644        // Install the system package
13645        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13646        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13647        if (locationIsPrivileged(disabledPs.codePath)) {
13648            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13649        }
13650
13651        final PackageParser.Package newPkg;
13652        try {
13653            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13654        } catch (PackageManagerException e) {
13655            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13656            return false;
13657        }
13658
13659        // writer
13660        synchronized (mPackages) {
13661            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13662
13663            // Propagate the permissions state as we do not want to drop on the floor
13664            // runtime permissions. The update permissions method below will take
13665            // care of removing obsolete permissions and grant install permissions.
13666            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13667            updatePermissionsLPw(newPkg.packageName, newPkg,
13668                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13669
13670            if (applyUserRestrictions) {
13671                if (DEBUG_REMOVE) {
13672                    Slog.d(TAG, "Propagating install state across reinstall");
13673                }
13674                for (int i = 0; i < allUserHandles.length; i++) {
13675                    if (DEBUG_REMOVE) {
13676                        Slog.d(TAG, "    user " + allUserHandles[i]
13677                                + " => " + perUserInstalled[i]);
13678                    }
13679                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13680
13681                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13682                }
13683                // Regardless of writeSettings we need to ensure that this restriction
13684                // state propagation is persisted
13685                mSettings.writeAllUsersPackageRestrictionsLPr();
13686            }
13687            // can downgrade to reader here
13688            if (writeSettings) {
13689                mSettings.writeLPr();
13690            }
13691        }
13692        return true;
13693    }
13694
13695    private boolean deleteInstalledPackageLI(PackageSetting ps,
13696            boolean deleteCodeAndResources, int flags,
13697            int[] allUserHandles, boolean[] perUserInstalled,
13698            PackageRemovedInfo outInfo, boolean writeSettings) {
13699        if (outInfo != null) {
13700            outInfo.uid = ps.appId;
13701        }
13702
13703        // Delete package data from internal structures and also remove data if flag is set
13704        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13705
13706        // Delete application code and resources
13707        if (deleteCodeAndResources && (outInfo != null)) {
13708            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13709                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13710            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13711        }
13712        return true;
13713    }
13714
13715    @Override
13716    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13717            int userId) {
13718        mContext.enforceCallingOrSelfPermission(
13719                android.Manifest.permission.DELETE_PACKAGES, null);
13720        synchronized (mPackages) {
13721            PackageSetting ps = mSettings.mPackages.get(packageName);
13722            if (ps == null) {
13723                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13724                return false;
13725            }
13726            if (!ps.getInstalled(userId)) {
13727                // Can't block uninstall for an app that is not installed or enabled.
13728                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13729                return false;
13730            }
13731            ps.setBlockUninstall(blockUninstall, userId);
13732            mSettings.writePackageRestrictionsLPr(userId);
13733        }
13734        return true;
13735    }
13736
13737    @Override
13738    public boolean getBlockUninstallForUser(String packageName, int userId) {
13739        synchronized (mPackages) {
13740            PackageSetting ps = mSettings.mPackages.get(packageName);
13741            if (ps == null) {
13742                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13743                return false;
13744            }
13745            return ps.getBlockUninstall(userId);
13746        }
13747    }
13748
13749    @Override
13750    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13751        int callingUid = Binder.getCallingUid();
13752        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13753            throw new SecurityException(
13754                    "setRequiredForSystemUser can only be run by the system or root");
13755        }
13756        synchronized (mPackages) {
13757            PackageSetting ps = mSettings.mPackages.get(packageName);
13758            if (ps == null) {
13759                Log.w(TAG, "Package doesn't exist: " + packageName);
13760                return false;
13761            }
13762            if (systemUserApp) {
13763                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13764            } else {
13765                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13766            }
13767            mSettings.writeLPr();
13768        }
13769        return true;
13770    }
13771
13772    /*
13773     * This method handles package deletion in general
13774     */
13775    private boolean deletePackageLI(String packageName, UserHandle user,
13776            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13777            int flags, PackageRemovedInfo outInfo,
13778            boolean writeSettings) {
13779        if (packageName == null) {
13780            Slog.w(TAG, "Attempt to delete null packageName.");
13781            return false;
13782        }
13783        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13784        PackageSetting ps;
13785        boolean dataOnly = false;
13786        int removeUser = -1;
13787        int appId = -1;
13788        synchronized (mPackages) {
13789            ps = mSettings.mPackages.get(packageName);
13790            if (ps == null) {
13791                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13792                return false;
13793            }
13794            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13795                    && user.getIdentifier() != UserHandle.USER_ALL) {
13796                // The caller is asking that the package only be deleted for a single
13797                // user.  To do this, we just mark its uninstalled state and delete
13798                // its data.  If this is a system app, we only allow this to happen if
13799                // they have set the special DELETE_SYSTEM_APP which requests different
13800                // semantics than normal for uninstalling system apps.
13801                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13802                final int userId = user.getIdentifier();
13803                ps.setUserState(userId,
13804                        COMPONENT_ENABLED_STATE_DEFAULT,
13805                        false, //installed
13806                        true,  //stopped
13807                        true,  //notLaunched
13808                        false, //hidden
13809                        false, //suspended
13810                        null, null, null,
13811                        false, // blockUninstall
13812                        ps.readUserState(userId).domainVerificationStatus, 0);
13813                if (!isSystemApp(ps)) {
13814                    // Do not uninstall the APK if an app should be cached
13815                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13816                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13817                        // Other user still have this package installed, so all
13818                        // we need to do is clear this user's data and save that
13819                        // it is uninstalled.
13820                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13821                        removeUser = user.getIdentifier();
13822                        appId = ps.appId;
13823                        scheduleWritePackageRestrictionsLocked(removeUser);
13824                    } else {
13825                        // We need to set it back to 'installed' so the uninstall
13826                        // broadcasts will be sent correctly.
13827                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13828                        ps.setInstalled(true, user.getIdentifier());
13829                    }
13830                } else {
13831                    // This is a system app, so we assume that the
13832                    // other users still have this package installed, so all
13833                    // we need to do is clear this user's data and save that
13834                    // it is uninstalled.
13835                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13836                    removeUser = user.getIdentifier();
13837                    appId = ps.appId;
13838                    scheduleWritePackageRestrictionsLocked(removeUser);
13839                }
13840            }
13841        }
13842
13843        if (removeUser >= 0) {
13844            // From above, we determined that we are deleting this only
13845            // for a single user.  Continue the work here.
13846            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13847            if (outInfo != null) {
13848                outInfo.removedPackage = packageName;
13849                outInfo.removedAppId = appId;
13850                outInfo.removedUsers = new int[] {removeUser};
13851            }
13852            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13853            removeKeystoreDataIfNeeded(removeUser, appId);
13854            schedulePackageCleaning(packageName, removeUser, false);
13855            synchronized (mPackages) {
13856                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13857                    scheduleWritePackageRestrictionsLocked(removeUser);
13858                }
13859                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13860            }
13861            return true;
13862        }
13863
13864        if (dataOnly) {
13865            // Delete application data first
13866            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13867            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13868            return true;
13869        }
13870
13871        boolean ret = false;
13872        if (isSystemApp(ps)) {
13873            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13874            // When an updated system application is deleted we delete the existing resources as well and
13875            // fall back to existing code in system partition
13876            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13877                    flags, outInfo, writeSettings);
13878        } else {
13879            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13880            // Kill application pre-emptively especially for apps on sd.
13881            killApplication(packageName, ps.appId, "uninstall pkg");
13882            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13883                    allUserHandles, perUserInstalled,
13884                    outInfo, writeSettings);
13885        }
13886
13887        return ret;
13888    }
13889
13890    private final static class ClearStorageConnection implements ServiceConnection {
13891        IMediaContainerService mContainerService;
13892
13893        @Override
13894        public void onServiceConnected(ComponentName name, IBinder service) {
13895            synchronized (this) {
13896                mContainerService = IMediaContainerService.Stub.asInterface(service);
13897                notifyAll();
13898            }
13899        }
13900
13901        @Override
13902        public void onServiceDisconnected(ComponentName name) {
13903        }
13904    }
13905
13906    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13907        final boolean mounted;
13908        if (Environment.isExternalStorageEmulated()) {
13909            mounted = true;
13910        } else {
13911            final String status = Environment.getExternalStorageState();
13912
13913            mounted = status.equals(Environment.MEDIA_MOUNTED)
13914                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13915        }
13916
13917        if (!mounted) {
13918            return;
13919        }
13920
13921        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13922        int[] users;
13923        if (userId == UserHandle.USER_ALL) {
13924            users = sUserManager.getUserIds();
13925        } else {
13926            users = new int[] { userId };
13927        }
13928        final ClearStorageConnection conn = new ClearStorageConnection();
13929        if (mContext.bindServiceAsUser(
13930                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13931            try {
13932                for (int curUser : users) {
13933                    long timeout = SystemClock.uptimeMillis() + 5000;
13934                    synchronized (conn) {
13935                        long now = SystemClock.uptimeMillis();
13936                        while (conn.mContainerService == null && now < timeout) {
13937                            try {
13938                                conn.wait(timeout - now);
13939                            } catch (InterruptedException e) {
13940                            }
13941                        }
13942                    }
13943                    if (conn.mContainerService == null) {
13944                        return;
13945                    }
13946
13947                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13948                    clearDirectory(conn.mContainerService,
13949                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13950                    if (allData) {
13951                        clearDirectory(conn.mContainerService,
13952                                userEnv.buildExternalStorageAppDataDirs(packageName));
13953                        clearDirectory(conn.mContainerService,
13954                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13955                    }
13956                }
13957            } finally {
13958                mContext.unbindService(conn);
13959            }
13960        }
13961    }
13962
13963    @Override
13964    public void clearApplicationUserData(final String packageName,
13965            final IPackageDataObserver observer, final int userId) {
13966        mContext.enforceCallingOrSelfPermission(
13967                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13968        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13969        // Queue up an async operation since the package deletion may take a little while.
13970        mHandler.post(new Runnable() {
13971            public void run() {
13972                mHandler.removeCallbacks(this);
13973                final boolean succeeded;
13974                synchronized (mInstallLock) {
13975                    succeeded = clearApplicationUserDataLI(packageName, userId);
13976                }
13977                clearExternalStorageDataSync(packageName, userId, true);
13978                if (succeeded) {
13979                    // invoke DeviceStorageMonitor's update method to clear any notifications
13980                    DeviceStorageMonitorInternal
13981                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13982                    if (dsm != null) {
13983                        dsm.checkMemory();
13984                    }
13985                }
13986                if(observer != null) {
13987                    try {
13988                        observer.onRemoveCompleted(packageName, succeeded);
13989                    } catch (RemoteException e) {
13990                        Log.i(TAG, "Observer no longer exists.");
13991                    }
13992                } //end if observer
13993            } //end run
13994        });
13995    }
13996
13997    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13998        if (packageName == null) {
13999            Slog.w(TAG, "Attempt to delete null packageName.");
14000            return false;
14001        }
14002
14003        // Try finding details about the requested package
14004        PackageParser.Package pkg;
14005        synchronized (mPackages) {
14006            pkg = mPackages.get(packageName);
14007            if (pkg == null) {
14008                final PackageSetting ps = mSettings.mPackages.get(packageName);
14009                if (ps != null) {
14010                    pkg = ps.pkg;
14011                }
14012            }
14013
14014            if (pkg == null) {
14015                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14016                return false;
14017            }
14018
14019            PackageSetting ps = (PackageSetting) pkg.mExtras;
14020            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14021        }
14022
14023        // Always delete data directories for package, even if we found no other
14024        // record of app. This helps users recover from UID mismatches without
14025        // resorting to a full data wipe.
14026        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14027        if (retCode < 0) {
14028            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
14029            return false;
14030        }
14031
14032        final int appId = pkg.applicationInfo.uid;
14033        removeKeystoreDataIfNeeded(userId, appId);
14034
14035        // Create a native library symlink only if we have native libraries
14036        // and if the native libraries are 32 bit libraries. We do not provide
14037        // this symlink for 64 bit libraries.
14038        if (pkg.applicationInfo.primaryCpuAbi != null &&
14039                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14040            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14041            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14042                    nativeLibPath, userId) < 0) {
14043                Slog.w(TAG, "Failed linking native library dir");
14044                return false;
14045            }
14046        }
14047
14048        return true;
14049    }
14050
14051    /**
14052     * Reverts user permission state changes (permissions and flags) in
14053     * all packages for a given user.
14054     *
14055     * @param userId The device user for which to do a reset.
14056     */
14057    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14058        final int packageCount = mPackages.size();
14059        for (int i = 0; i < packageCount; i++) {
14060            PackageParser.Package pkg = mPackages.valueAt(i);
14061            PackageSetting ps = (PackageSetting) pkg.mExtras;
14062            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14063        }
14064    }
14065
14066    /**
14067     * Reverts user permission state changes (permissions and flags).
14068     *
14069     * @param ps The package for which to reset.
14070     * @param userId The device user for which to do a reset.
14071     */
14072    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14073            final PackageSetting ps, final int userId) {
14074        if (ps.pkg == null) {
14075            return;
14076        }
14077
14078        // These are flags that can change base on user actions.
14079        final int userSettableMask = FLAG_PERMISSION_USER_SET
14080                | FLAG_PERMISSION_USER_FIXED
14081                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14082                | FLAG_PERMISSION_REVIEW_REQUIRED;
14083
14084        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14085                | FLAG_PERMISSION_POLICY_FIXED;
14086
14087        boolean writeInstallPermissions = false;
14088        boolean writeRuntimePermissions = false;
14089
14090        final int permissionCount = ps.pkg.requestedPermissions.size();
14091        for (int i = 0; i < permissionCount; i++) {
14092            String permission = ps.pkg.requestedPermissions.get(i);
14093
14094            BasePermission bp = mSettings.mPermissions.get(permission);
14095            if (bp == null) {
14096                continue;
14097            }
14098
14099            // If shared user we just reset the state to which only this app contributed.
14100            if (ps.sharedUser != null) {
14101                boolean used = false;
14102                final int packageCount = ps.sharedUser.packages.size();
14103                for (int j = 0; j < packageCount; j++) {
14104                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14105                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14106                            && pkg.pkg.requestedPermissions.contains(permission)) {
14107                        used = true;
14108                        break;
14109                    }
14110                }
14111                if (used) {
14112                    continue;
14113                }
14114            }
14115
14116            PermissionsState permissionsState = ps.getPermissionsState();
14117
14118            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14119
14120            // Always clear the user settable flags.
14121            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14122                    bp.name) != null;
14123            // If permission review is enabled and this is a legacy app, mark the
14124            // permission as requiring a review as this is the initial state.
14125            int flags = 0;
14126            if (Build.PERMISSIONS_REVIEW_REQUIRED
14127                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14128                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14129            }
14130            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14131                if (hasInstallState) {
14132                    writeInstallPermissions = true;
14133                } else {
14134                    writeRuntimePermissions = true;
14135                }
14136            }
14137
14138            // Below is only runtime permission handling.
14139            if (!bp.isRuntime()) {
14140                continue;
14141            }
14142
14143            // Never clobber system or policy.
14144            if ((oldFlags & policyOrSystemFlags) != 0) {
14145                continue;
14146            }
14147
14148            // If this permission was granted by default, make sure it is.
14149            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14150                if (permissionsState.grantRuntimePermission(bp, userId)
14151                        != PERMISSION_OPERATION_FAILURE) {
14152                    writeRuntimePermissions = true;
14153                }
14154            // If permission review is enabled the permissions for a legacy apps
14155            // are represented as constantly granted runtime ones, so don't revoke.
14156            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14157                // Otherwise, reset the permission.
14158                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14159                switch (revokeResult) {
14160                    case PERMISSION_OPERATION_SUCCESS: {
14161                        writeRuntimePermissions = true;
14162                    } break;
14163
14164                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14165                        writeRuntimePermissions = true;
14166                        final int appId = ps.appId;
14167                        mHandler.post(new Runnable() {
14168                            @Override
14169                            public void run() {
14170                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14171                            }
14172                        });
14173                    } break;
14174                }
14175            }
14176        }
14177
14178        // Synchronously write as we are taking permissions away.
14179        if (writeRuntimePermissions) {
14180            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14181        }
14182
14183        // Synchronously write as we are taking permissions away.
14184        if (writeInstallPermissions) {
14185            mSettings.writeLPr();
14186        }
14187    }
14188
14189    /**
14190     * Remove entries from the keystore daemon. Will only remove it if the
14191     * {@code appId} is valid.
14192     */
14193    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14194        if (appId < 0) {
14195            return;
14196        }
14197
14198        final KeyStore keyStore = KeyStore.getInstance();
14199        if (keyStore != null) {
14200            if (userId == UserHandle.USER_ALL) {
14201                for (final int individual : sUserManager.getUserIds()) {
14202                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14203                }
14204            } else {
14205                keyStore.clearUid(UserHandle.getUid(userId, appId));
14206            }
14207        } else {
14208            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14209        }
14210    }
14211
14212    @Override
14213    public void deleteApplicationCacheFiles(final String packageName,
14214            final IPackageDataObserver observer) {
14215        mContext.enforceCallingOrSelfPermission(
14216                android.Manifest.permission.DELETE_CACHE_FILES, null);
14217        // Queue up an async operation since the package deletion may take a little while.
14218        final int userId = UserHandle.getCallingUserId();
14219        mHandler.post(new Runnable() {
14220            public void run() {
14221                mHandler.removeCallbacks(this);
14222                final boolean succeded;
14223                synchronized (mInstallLock) {
14224                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14225                }
14226                clearExternalStorageDataSync(packageName, userId, false);
14227                if (observer != null) {
14228                    try {
14229                        observer.onRemoveCompleted(packageName, succeded);
14230                    } catch (RemoteException e) {
14231                        Log.i(TAG, "Observer no longer exists.");
14232                    }
14233                } //end if observer
14234            } //end run
14235        });
14236    }
14237
14238    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14239        if (packageName == null) {
14240            Slog.w(TAG, "Attempt to delete null packageName.");
14241            return false;
14242        }
14243        PackageParser.Package p;
14244        synchronized (mPackages) {
14245            p = mPackages.get(packageName);
14246        }
14247        if (p == null) {
14248            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14249            return false;
14250        }
14251        final ApplicationInfo applicationInfo = p.applicationInfo;
14252        if (applicationInfo == null) {
14253            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14254            return false;
14255        }
14256        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14257        if (retCode < 0) {
14258            Slog.w(TAG, "Couldn't remove cache files for package: "
14259                       + packageName + " u" + userId);
14260            return false;
14261        }
14262        return true;
14263    }
14264
14265    @Override
14266    public void getPackageSizeInfo(final String packageName, int userHandle,
14267            final IPackageStatsObserver observer) {
14268        mContext.enforceCallingOrSelfPermission(
14269                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14270        if (packageName == null) {
14271            throw new IllegalArgumentException("Attempt to get size of null packageName");
14272        }
14273
14274        PackageStats stats = new PackageStats(packageName, userHandle);
14275
14276        /*
14277         * Queue up an async operation since the package measurement may take a
14278         * little while.
14279         */
14280        Message msg = mHandler.obtainMessage(INIT_COPY);
14281        msg.obj = new MeasureParams(stats, observer);
14282        mHandler.sendMessage(msg);
14283    }
14284
14285    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14286            PackageStats pStats) {
14287        if (packageName == null) {
14288            Slog.w(TAG, "Attempt to get size of null packageName.");
14289            return false;
14290        }
14291        PackageParser.Package p;
14292        boolean dataOnly = false;
14293        String libDirRoot = null;
14294        String asecPath = null;
14295        PackageSetting ps = null;
14296        synchronized (mPackages) {
14297            p = mPackages.get(packageName);
14298            ps = mSettings.mPackages.get(packageName);
14299            if(p == null) {
14300                dataOnly = true;
14301                if((ps == null) || (ps.pkg == null)) {
14302                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14303                    return false;
14304                }
14305                p = ps.pkg;
14306            }
14307            if (ps != null) {
14308                libDirRoot = ps.legacyNativeLibraryPathString;
14309            }
14310            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14311                final long token = Binder.clearCallingIdentity();
14312                try {
14313                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14314                    if (secureContainerId != null) {
14315                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14316                    }
14317                } finally {
14318                    Binder.restoreCallingIdentity(token);
14319                }
14320            }
14321        }
14322        String publicSrcDir = null;
14323        if(!dataOnly) {
14324            final ApplicationInfo applicationInfo = p.applicationInfo;
14325            if (applicationInfo == null) {
14326                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14327                return false;
14328            }
14329            if (p.isForwardLocked()) {
14330                publicSrcDir = applicationInfo.getBaseResourcePath();
14331            }
14332        }
14333        // TODO: extend to measure size of split APKs
14334        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14335        // not just the first level.
14336        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14337        // just the primary.
14338        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14339
14340        String apkPath;
14341        File packageDir = new File(p.codePath);
14342
14343        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14344            apkPath = packageDir.getAbsolutePath();
14345            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14346            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14347                libDirRoot = null;
14348            }
14349        } else {
14350            apkPath = p.baseCodePath;
14351        }
14352
14353        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14354                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14355        if (res < 0) {
14356            return false;
14357        }
14358
14359        // Fix-up for forward-locked applications in ASEC containers.
14360        if (!isExternal(p)) {
14361            pStats.codeSize += pStats.externalCodeSize;
14362            pStats.externalCodeSize = 0L;
14363        }
14364
14365        return true;
14366    }
14367
14368
14369    @Override
14370    public void addPackageToPreferred(String packageName) {
14371        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14372    }
14373
14374    @Override
14375    public void removePackageFromPreferred(String packageName) {
14376        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14377    }
14378
14379    @Override
14380    public List<PackageInfo> getPreferredPackages(int flags) {
14381        return new ArrayList<PackageInfo>();
14382    }
14383
14384    private int getUidTargetSdkVersionLockedLPr(int uid) {
14385        Object obj = mSettings.getUserIdLPr(uid);
14386        if (obj instanceof SharedUserSetting) {
14387            final SharedUserSetting sus = (SharedUserSetting) obj;
14388            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14389            final Iterator<PackageSetting> it = sus.packages.iterator();
14390            while (it.hasNext()) {
14391                final PackageSetting ps = it.next();
14392                if (ps.pkg != null) {
14393                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14394                    if (v < vers) vers = v;
14395                }
14396            }
14397            return vers;
14398        } else if (obj instanceof PackageSetting) {
14399            final PackageSetting ps = (PackageSetting) obj;
14400            if (ps.pkg != null) {
14401                return ps.pkg.applicationInfo.targetSdkVersion;
14402            }
14403        }
14404        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14405    }
14406
14407    @Override
14408    public void addPreferredActivity(IntentFilter filter, int match,
14409            ComponentName[] set, ComponentName activity, int userId) {
14410        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14411                "Adding preferred");
14412    }
14413
14414    private void addPreferredActivityInternal(IntentFilter filter, int match,
14415            ComponentName[] set, ComponentName activity, boolean always, int userId,
14416            String opname) {
14417        // writer
14418        int callingUid = Binder.getCallingUid();
14419        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14420        if (filter.countActions() == 0) {
14421            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14422            return;
14423        }
14424        synchronized (mPackages) {
14425            if (mContext.checkCallingOrSelfPermission(
14426                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14427                    != PackageManager.PERMISSION_GRANTED) {
14428                if (getUidTargetSdkVersionLockedLPr(callingUid)
14429                        < Build.VERSION_CODES.FROYO) {
14430                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14431                            + callingUid);
14432                    return;
14433                }
14434                mContext.enforceCallingOrSelfPermission(
14435                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14436            }
14437
14438            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14439            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14440                    + userId + ":");
14441            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14442            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14443            scheduleWritePackageRestrictionsLocked(userId);
14444        }
14445    }
14446
14447    @Override
14448    public void replacePreferredActivity(IntentFilter filter, int match,
14449            ComponentName[] set, ComponentName activity, int userId) {
14450        if (filter.countActions() != 1) {
14451            throw new IllegalArgumentException(
14452                    "replacePreferredActivity expects filter to have only 1 action.");
14453        }
14454        if (filter.countDataAuthorities() != 0
14455                || filter.countDataPaths() != 0
14456                || filter.countDataSchemes() > 1
14457                || filter.countDataTypes() != 0) {
14458            throw new IllegalArgumentException(
14459                    "replacePreferredActivity expects filter to have no data authorities, " +
14460                    "paths, or types; and at most one scheme.");
14461        }
14462
14463        final int callingUid = Binder.getCallingUid();
14464        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14465        synchronized (mPackages) {
14466            if (mContext.checkCallingOrSelfPermission(
14467                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14468                    != PackageManager.PERMISSION_GRANTED) {
14469                if (getUidTargetSdkVersionLockedLPr(callingUid)
14470                        < Build.VERSION_CODES.FROYO) {
14471                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14472                            + Binder.getCallingUid());
14473                    return;
14474                }
14475                mContext.enforceCallingOrSelfPermission(
14476                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14477            }
14478
14479            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14480            if (pir != null) {
14481                // Get all of the existing entries that exactly match this filter.
14482                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14483                if (existing != null && existing.size() == 1) {
14484                    PreferredActivity cur = existing.get(0);
14485                    if (DEBUG_PREFERRED) {
14486                        Slog.i(TAG, "Checking replace of preferred:");
14487                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14488                        if (!cur.mPref.mAlways) {
14489                            Slog.i(TAG, "  -- CUR; not mAlways!");
14490                        } else {
14491                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14492                            Slog.i(TAG, "  -- CUR: mSet="
14493                                    + Arrays.toString(cur.mPref.mSetComponents));
14494                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14495                            Slog.i(TAG, "  -- NEW: mMatch="
14496                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14497                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14498                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14499                        }
14500                    }
14501                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14502                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14503                            && cur.mPref.sameSet(set)) {
14504                        // Setting the preferred activity to what it happens to be already
14505                        if (DEBUG_PREFERRED) {
14506                            Slog.i(TAG, "Replacing with same preferred activity "
14507                                    + cur.mPref.mShortComponent + " for user "
14508                                    + userId + ":");
14509                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14510                        }
14511                        return;
14512                    }
14513                }
14514
14515                if (existing != null) {
14516                    if (DEBUG_PREFERRED) {
14517                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14518                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14519                    }
14520                    for (int i = 0; i < existing.size(); i++) {
14521                        PreferredActivity pa = existing.get(i);
14522                        if (DEBUG_PREFERRED) {
14523                            Slog.i(TAG, "Removing existing preferred activity "
14524                                    + pa.mPref.mComponent + ":");
14525                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14526                        }
14527                        pir.removeFilter(pa);
14528                    }
14529                }
14530            }
14531            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14532                    "Replacing preferred");
14533        }
14534    }
14535
14536    @Override
14537    public void clearPackagePreferredActivities(String packageName) {
14538        final int uid = Binder.getCallingUid();
14539        // writer
14540        synchronized (mPackages) {
14541            PackageParser.Package pkg = mPackages.get(packageName);
14542            if (pkg == null || pkg.applicationInfo.uid != uid) {
14543                if (mContext.checkCallingOrSelfPermission(
14544                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14545                        != PackageManager.PERMISSION_GRANTED) {
14546                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14547                            < Build.VERSION_CODES.FROYO) {
14548                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14549                                + Binder.getCallingUid());
14550                        return;
14551                    }
14552                    mContext.enforceCallingOrSelfPermission(
14553                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14554                }
14555            }
14556
14557            int user = UserHandle.getCallingUserId();
14558            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14559                scheduleWritePackageRestrictionsLocked(user);
14560            }
14561        }
14562    }
14563
14564    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14565    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14566        ArrayList<PreferredActivity> removed = null;
14567        boolean changed = false;
14568        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14569            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14570            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14571            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14572                continue;
14573            }
14574            Iterator<PreferredActivity> it = pir.filterIterator();
14575            while (it.hasNext()) {
14576                PreferredActivity pa = it.next();
14577                // Mark entry for removal only if it matches the package name
14578                // and the entry is of type "always".
14579                if (packageName == null ||
14580                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14581                                && pa.mPref.mAlways)) {
14582                    if (removed == null) {
14583                        removed = new ArrayList<PreferredActivity>();
14584                    }
14585                    removed.add(pa);
14586                }
14587            }
14588            if (removed != null) {
14589                for (int j=0; j<removed.size(); j++) {
14590                    PreferredActivity pa = removed.get(j);
14591                    pir.removeFilter(pa);
14592                }
14593                changed = true;
14594            }
14595        }
14596        return changed;
14597    }
14598
14599    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14600    private void clearIntentFilterVerificationsLPw(int userId) {
14601        final int packageCount = mPackages.size();
14602        for (int i = 0; i < packageCount; i++) {
14603            PackageParser.Package pkg = mPackages.valueAt(i);
14604            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14605        }
14606    }
14607
14608    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14609    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14610        if (userId == UserHandle.USER_ALL) {
14611            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14612                    sUserManager.getUserIds())) {
14613                for (int oneUserId : sUserManager.getUserIds()) {
14614                    scheduleWritePackageRestrictionsLocked(oneUserId);
14615                }
14616            }
14617        } else {
14618            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14619                scheduleWritePackageRestrictionsLocked(userId);
14620            }
14621        }
14622    }
14623
14624    void clearDefaultBrowserIfNeeded(String packageName) {
14625        for (int oneUserId : sUserManager.getUserIds()) {
14626            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14627            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14628            if (packageName.equals(defaultBrowserPackageName)) {
14629                setDefaultBrowserPackageName(null, oneUserId);
14630            }
14631        }
14632    }
14633
14634    @Override
14635    public void resetApplicationPreferences(int userId) {
14636        mContext.enforceCallingOrSelfPermission(
14637                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14638        // writer
14639        synchronized (mPackages) {
14640            final long identity = Binder.clearCallingIdentity();
14641            try {
14642                clearPackagePreferredActivitiesLPw(null, userId);
14643                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14644                // TODO: We have to reset the default SMS and Phone. This requires
14645                // significant refactoring to keep all default apps in the package
14646                // manager (cleaner but more work) or have the services provide
14647                // callbacks to the package manager to request a default app reset.
14648                applyFactoryDefaultBrowserLPw(userId);
14649                clearIntentFilterVerificationsLPw(userId);
14650                primeDomainVerificationsLPw(userId);
14651                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14652                scheduleWritePackageRestrictionsLocked(userId);
14653            } finally {
14654                Binder.restoreCallingIdentity(identity);
14655            }
14656        }
14657    }
14658
14659    @Override
14660    public int getPreferredActivities(List<IntentFilter> outFilters,
14661            List<ComponentName> outActivities, String packageName) {
14662
14663        int num = 0;
14664        final int userId = UserHandle.getCallingUserId();
14665        // reader
14666        synchronized (mPackages) {
14667            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14668            if (pir != null) {
14669                final Iterator<PreferredActivity> it = pir.filterIterator();
14670                while (it.hasNext()) {
14671                    final PreferredActivity pa = it.next();
14672                    if (packageName == null
14673                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14674                                    && pa.mPref.mAlways)) {
14675                        if (outFilters != null) {
14676                            outFilters.add(new IntentFilter(pa));
14677                        }
14678                        if (outActivities != null) {
14679                            outActivities.add(pa.mPref.mComponent);
14680                        }
14681                    }
14682                }
14683            }
14684        }
14685
14686        return num;
14687    }
14688
14689    @Override
14690    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14691            int userId) {
14692        int callingUid = Binder.getCallingUid();
14693        if (callingUid != Process.SYSTEM_UID) {
14694            throw new SecurityException(
14695                    "addPersistentPreferredActivity can only be run by the system");
14696        }
14697        if (filter.countActions() == 0) {
14698            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14699            return;
14700        }
14701        synchronized (mPackages) {
14702            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14703                    " :");
14704            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14705            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14706                    new PersistentPreferredActivity(filter, activity));
14707            scheduleWritePackageRestrictionsLocked(userId);
14708        }
14709    }
14710
14711    @Override
14712    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14713        int callingUid = Binder.getCallingUid();
14714        if (callingUid != Process.SYSTEM_UID) {
14715            throw new SecurityException(
14716                    "clearPackagePersistentPreferredActivities can only be run by the system");
14717        }
14718        ArrayList<PersistentPreferredActivity> removed = null;
14719        boolean changed = false;
14720        synchronized (mPackages) {
14721            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14722                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14723                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14724                        .valueAt(i);
14725                if (userId != thisUserId) {
14726                    continue;
14727                }
14728                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14729                while (it.hasNext()) {
14730                    PersistentPreferredActivity ppa = it.next();
14731                    // Mark entry for removal only if it matches the package name.
14732                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14733                        if (removed == null) {
14734                            removed = new ArrayList<PersistentPreferredActivity>();
14735                        }
14736                        removed.add(ppa);
14737                    }
14738                }
14739                if (removed != null) {
14740                    for (int j=0; j<removed.size(); j++) {
14741                        PersistentPreferredActivity ppa = removed.get(j);
14742                        ppir.removeFilter(ppa);
14743                    }
14744                    changed = true;
14745                }
14746            }
14747
14748            if (changed) {
14749                scheduleWritePackageRestrictionsLocked(userId);
14750            }
14751        }
14752    }
14753
14754    /**
14755     * Common machinery for picking apart a restored XML blob and passing
14756     * it to a caller-supplied functor to be applied to the running system.
14757     */
14758    private void restoreFromXml(XmlPullParser parser, int userId,
14759            String expectedStartTag, BlobXmlRestorer functor)
14760            throws IOException, XmlPullParserException {
14761        int type;
14762        while ((type = parser.next()) != XmlPullParser.START_TAG
14763                && type != XmlPullParser.END_DOCUMENT) {
14764        }
14765        if (type != XmlPullParser.START_TAG) {
14766            // oops didn't find a start tag?!
14767            if (DEBUG_BACKUP) {
14768                Slog.e(TAG, "Didn't find start tag during restore");
14769            }
14770            return;
14771        }
14772
14773        // this is supposed to be TAG_PREFERRED_BACKUP
14774        if (!expectedStartTag.equals(parser.getName())) {
14775            if (DEBUG_BACKUP) {
14776                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14777            }
14778            return;
14779        }
14780
14781        // skip interfering stuff, then we're aligned with the backing implementation
14782        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14783        functor.apply(parser, userId);
14784    }
14785
14786    private interface BlobXmlRestorer {
14787        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14788    }
14789
14790    /**
14791     * Non-Binder method, support for the backup/restore mechanism: write the
14792     * full set of preferred activities in its canonical XML format.  Returns the
14793     * XML output as a byte array, or null if there is none.
14794     */
14795    @Override
14796    public byte[] getPreferredActivityBackup(int userId) {
14797        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14798            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14799        }
14800
14801        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14802        try {
14803            final XmlSerializer serializer = new FastXmlSerializer();
14804            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14805            serializer.startDocument(null, true);
14806            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14807
14808            synchronized (mPackages) {
14809                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14810            }
14811
14812            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14813            serializer.endDocument();
14814            serializer.flush();
14815        } catch (Exception e) {
14816            if (DEBUG_BACKUP) {
14817                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14818            }
14819            return null;
14820        }
14821
14822        return dataStream.toByteArray();
14823    }
14824
14825    @Override
14826    public void restorePreferredActivities(byte[] backup, int userId) {
14827        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14828            throw new SecurityException("Only the system may call restorePreferredActivities()");
14829        }
14830
14831        try {
14832            final XmlPullParser parser = Xml.newPullParser();
14833            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14834            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14835                    new BlobXmlRestorer() {
14836                        @Override
14837                        public void apply(XmlPullParser parser, int userId)
14838                                throws XmlPullParserException, IOException {
14839                            synchronized (mPackages) {
14840                                mSettings.readPreferredActivitiesLPw(parser, userId);
14841                            }
14842                        }
14843                    } );
14844        } catch (Exception e) {
14845            if (DEBUG_BACKUP) {
14846                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14847            }
14848        }
14849    }
14850
14851    /**
14852     * Non-Binder method, support for the backup/restore mechanism: write the
14853     * default browser (etc) settings in its canonical XML format.  Returns the default
14854     * browser XML representation as a byte array, or null if there is none.
14855     */
14856    @Override
14857    public byte[] getDefaultAppsBackup(int userId) {
14858        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14859            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14860        }
14861
14862        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14863        try {
14864            final XmlSerializer serializer = new FastXmlSerializer();
14865            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14866            serializer.startDocument(null, true);
14867            serializer.startTag(null, TAG_DEFAULT_APPS);
14868
14869            synchronized (mPackages) {
14870                mSettings.writeDefaultAppsLPr(serializer, userId);
14871            }
14872
14873            serializer.endTag(null, TAG_DEFAULT_APPS);
14874            serializer.endDocument();
14875            serializer.flush();
14876        } catch (Exception e) {
14877            if (DEBUG_BACKUP) {
14878                Slog.e(TAG, "Unable to write default apps for backup", e);
14879            }
14880            return null;
14881        }
14882
14883        return dataStream.toByteArray();
14884    }
14885
14886    @Override
14887    public void restoreDefaultApps(byte[] backup, int userId) {
14888        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14889            throw new SecurityException("Only the system may call restoreDefaultApps()");
14890        }
14891
14892        try {
14893            final XmlPullParser parser = Xml.newPullParser();
14894            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14895            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14896                    new BlobXmlRestorer() {
14897                        @Override
14898                        public void apply(XmlPullParser parser, int userId)
14899                                throws XmlPullParserException, IOException {
14900                            synchronized (mPackages) {
14901                                mSettings.readDefaultAppsLPw(parser, userId);
14902                            }
14903                        }
14904                    } );
14905        } catch (Exception e) {
14906            if (DEBUG_BACKUP) {
14907                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14908            }
14909        }
14910    }
14911
14912    @Override
14913    public byte[] getIntentFilterVerificationBackup(int userId) {
14914        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14915            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14916        }
14917
14918        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14919        try {
14920            final XmlSerializer serializer = new FastXmlSerializer();
14921            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14922            serializer.startDocument(null, true);
14923            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14924
14925            synchronized (mPackages) {
14926                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14927            }
14928
14929            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14930            serializer.endDocument();
14931            serializer.flush();
14932        } catch (Exception e) {
14933            if (DEBUG_BACKUP) {
14934                Slog.e(TAG, "Unable to write default apps for backup", e);
14935            }
14936            return null;
14937        }
14938
14939        return dataStream.toByteArray();
14940    }
14941
14942    @Override
14943    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14944        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14945            throw new SecurityException("Only the system may call restorePreferredActivities()");
14946        }
14947
14948        try {
14949            final XmlPullParser parser = Xml.newPullParser();
14950            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14951            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14952                    new BlobXmlRestorer() {
14953                        @Override
14954                        public void apply(XmlPullParser parser, int userId)
14955                                throws XmlPullParserException, IOException {
14956                            synchronized (mPackages) {
14957                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14958                                mSettings.writeLPr();
14959                            }
14960                        }
14961                    } );
14962        } catch (Exception e) {
14963            if (DEBUG_BACKUP) {
14964                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14965            }
14966        }
14967    }
14968
14969    @Override
14970    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14971            int sourceUserId, int targetUserId, int flags) {
14972        mContext.enforceCallingOrSelfPermission(
14973                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14974        int callingUid = Binder.getCallingUid();
14975        enforceOwnerRights(ownerPackage, callingUid);
14976        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14977        if (intentFilter.countActions() == 0) {
14978            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14979            return;
14980        }
14981        synchronized (mPackages) {
14982            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14983                    ownerPackage, targetUserId, flags);
14984            CrossProfileIntentResolver resolver =
14985                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14986            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14987            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14988            if (existing != null) {
14989                int size = existing.size();
14990                for (int i = 0; i < size; i++) {
14991                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14992                        return;
14993                    }
14994                }
14995            }
14996            resolver.addFilter(newFilter);
14997            scheduleWritePackageRestrictionsLocked(sourceUserId);
14998        }
14999    }
15000
15001    @Override
15002    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
15003        mContext.enforceCallingOrSelfPermission(
15004                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15005        int callingUid = Binder.getCallingUid();
15006        enforceOwnerRights(ownerPackage, callingUid);
15007        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15008        synchronized (mPackages) {
15009            CrossProfileIntentResolver resolver =
15010                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15011            ArraySet<CrossProfileIntentFilter> set =
15012                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15013            for (CrossProfileIntentFilter filter : set) {
15014                if (filter.getOwnerPackage().equals(ownerPackage)) {
15015                    resolver.removeFilter(filter);
15016                }
15017            }
15018            scheduleWritePackageRestrictionsLocked(sourceUserId);
15019        }
15020    }
15021
15022    // Enforcing that callingUid is owning pkg on userId
15023    private void enforceOwnerRights(String pkg, int callingUid) {
15024        // The system owns everything.
15025        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15026            return;
15027        }
15028        int callingUserId = UserHandle.getUserId(callingUid);
15029        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15030        if (pi == null) {
15031            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15032                    + callingUserId);
15033        }
15034        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15035            throw new SecurityException("Calling uid " + callingUid
15036                    + " does not own package " + pkg);
15037        }
15038    }
15039
15040    @Override
15041    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15042        Intent intent = new Intent(Intent.ACTION_MAIN);
15043        intent.addCategory(Intent.CATEGORY_HOME);
15044
15045        final int callingUserId = UserHandle.getCallingUserId();
15046        List<ResolveInfo> list = queryIntentActivities(intent, null,
15047                PackageManager.GET_META_DATA, callingUserId);
15048        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15049                true, false, false, callingUserId);
15050
15051        allHomeCandidates.clear();
15052        if (list != null) {
15053            for (ResolveInfo ri : list) {
15054                allHomeCandidates.add(ri);
15055            }
15056        }
15057        return (preferred == null || preferred.activityInfo == null)
15058                ? null
15059                : new ComponentName(preferred.activityInfo.packageName,
15060                        preferred.activityInfo.name);
15061    }
15062
15063    @Override
15064    public void setApplicationEnabledSetting(String appPackageName,
15065            int newState, int flags, int userId, String callingPackage) {
15066        if (!sUserManager.exists(userId)) return;
15067        if (callingPackage == null) {
15068            callingPackage = Integer.toString(Binder.getCallingUid());
15069        }
15070        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15071    }
15072
15073    @Override
15074    public void setComponentEnabledSetting(ComponentName componentName,
15075            int newState, int flags, int userId) {
15076        if (!sUserManager.exists(userId)) return;
15077        setEnabledSetting(componentName.getPackageName(),
15078                componentName.getClassName(), newState, flags, userId, null);
15079    }
15080
15081    private void setEnabledSetting(final String packageName, String className, int newState,
15082            final int flags, int userId, String callingPackage) {
15083        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15084              || newState == COMPONENT_ENABLED_STATE_ENABLED
15085              || newState == COMPONENT_ENABLED_STATE_DISABLED
15086              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15087              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15088            throw new IllegalArgumentException("Invalid new component state: "
15089                    + newState);
15090        }
15091        PackageSetting pkgSetting;
15092        final int uid = Binder.getCallingUid();
15093        final int permission = mContext.checkCallingOrSelfPermission(
15094                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15095        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15096        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15097        boolean sendNow = false;
15098        boolean isApp = (className == null);
15099        String componentName = isApp ? packageName : className;
15100        int packageUid = -1;
15101        ArrayList<String> components;
15102
15103        // writer
15104        synchronized (mPackages) {
15105            pkgSetting = mSettings.mPackages.get(packageName);
15106            if (pkgSetting == null) {
15107                if (className == null) {
15108                    throw new IllegalArgumentException(
15109                            "Unknown package: " + packageName);
15110                }
15111                throw new IllegalArgumentException(
15112                        "Unknown component: " + packageName
15113                        + "/" + className);
15114            }
15115            // Allow root and verify that userId is not being specified by a different user
15116            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15117                throw new SecurityException(
15118                        "Permission Denial: attempt to change component state from pid="
15119                        + Binder.getCallingPid()
15120                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15121            }
15122            if (className == null) {
15123                // We're dealing with an application/package level state change
15124                if (pkgSetting.getEnabled(userId) == newState) {
15125                    // Nothing to do
15126                    return;
15127                }
15128                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15129                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15130                    // Don't care about who enables an app.
15131                    callingPackage = null;
15132                }
15133                pkgSetting.setEnabled(newState, userId, callingPackage);
15134                // pkgSetting.pkg.mSetEnabled = newState;
15135            } else {
15136                // We're dealing with a component level state change
15137                // First, verify that this is a valid class name.
15138                PackageParser.Package pkg = pkgSetting.pkg;
15139                if (pkg == null || !pkg.hasComponentClassName(className)) {
15140                    if (pkg != null &&
15141                            pkg.applicationInfo.targetSdkVersion >=
15142                                    Build.VERSION_CODES.JELLY_BEAN) {
15143                        throw new IllegalArgumentException("Component class " + className
15144                                + " does not exist in " + packageName);
15145                    } else {
15146                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15147                                + className + " does not exist in " + packageName);
15148                    }
15149                }
15150                switch (newState) {
15151                case COMPONENT_ENABLED_STATE_ENABLED:
15152                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15153                        return;
15154                    }
15155                    break;
15156                case COMPONENT_ENABLED_STATE_DISABLED:
15157                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15158                        return;
15159                    }
15160                    break;
15161                case COMPONENT_ENABLED_STATE_DEFAULT:
15162                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15163                        return;
15164                    }
15165                    break;
15166                default:
15167                    Slog.e(TAG, "Invalid new component state: " + newState);
15168                    return;
15169                }
15170            }
15171            scheduleWritePackageRestrictionsLocked(userId);
15172            components = mPendingBroadcasts.get(userId, packageName);
15173            final boolean newPackage = components == null;
15174            if (newPackage) {
15175                components = new ArrayList<String>();
15176            }
15177            if (!components.contains(componentName)) {
15178                components.add(componentName);
15179            }
15180            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15181                sendNow = true;
15182                // Purge entry from pending broadcast list if another one exists already
15183                // since we are sending one right away.
15184                mPendingBroadcasts.remove(userId, packageName);
15185            } else {
15186                if (newPackage) {
15187                    mPendingBroadcasts.put(userId, packageName, components);
15188                }
15189                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15190                    // Schedule a message
15191                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15192                }
15193            }
15194        }
15195
15196        long callingId = Binder.clearCallingIdentity();
15197        try {
15198            if (sendNow) {
15199                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15200                sendPackageChangedBroadcast(packageName,
15201                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15202            }
15203        } finally {
15204            Binder.restoreCallingIdentity(callingId);
15205        }
15206    }
15207
15208    private void sendPackageChangedBroadcast(String packageName,
15209            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15210        if (DEBUG_INSTALL)
15211            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15212                    + componentNames);
15213        Bundle extras = new Bundle(4);
15214        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15215        String nameList[] = new String[componentNames.size()];
15216        componentNames.toArray(nameList);
15217        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15218        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15219        extras.putInt(Intent.EXTRA_UID, packageUid);
15220        // If this is not reporting a change of the overall package, then only send it
15221        // to registered receivers.  We don't want to launch a swath of apps for every
15222        // little component state change.
15223        final int flags = !componentNames.contains(packageName)
15224                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15225        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15226                new int[] {UserHandle.getUserId(packageUid)});
15227    }
15228
15229    @Override
15230    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15231        if (!sUserManager.exists(userId)) return;
15232        final int uid = Binder.getCallingUid();
15233        final int permission = mContext.checkCallingOrSelfPermission(
15234                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15235        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15236        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15237        // writer
15238        synchronized (mPackages) {
15239            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15240                    allowedByPermission, uid, userId)) {
15241                scheduleWritePackageRestrictionsLocked(userId);
15242            }
15243        }
15244    }
15245
15246    @Override
15247    public String getInstallerPackageName(String packageName) {
15248        // reader
15249        synchronized (mPackages) {
15250            return mSettings.getInstallerPackageNameLPr(packageName);
15251        }
15252    }
15253
15254    @Override
15255    public int getApplicationEnabledSetting(String packageName, int userId) {
15256        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15257        int uid = Binder.getCallingUid();
15258        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15259        // reader
15260        synchronized (mPackages) {
15261            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15262        }
15263    }
15264
15265    @Override
15266    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15267        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15268        int uid = Binder.getCallingUid();
15269        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15270        // reader
15271        synchronized (mPackages) {
15272            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15273        }
15274    }
15275
15276    @Override
15277    public void enterSafeMode() {
15278        enforceSystemOrRoot("Only the system can request entering safe mode");
15279
15280        if (!mSystemReady) {
15281            mSafeMode = true;
15282        }
15283    }
15284
15285    @Override
15286    public void systemReady() {
15287        mSystemReady = true;
15288
15289        // Read the compatibilty setting when the system is ready.
15290        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15291                mContext.getContentResolver(),
15292                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15293        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15294        if (DEBUG_SETTINGS) {
15295            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15296        }
15297
15298        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15299
15300        synchronized (mPackages) {
15301            // Verify that all of the preferred activity components actually
15302            // exist.  It is possible for applications to be updated and at
15303            // that point remove a previously declared activity component that
15304            // had been set as a preferred activity.  We try to clean this up
15305            // the next time we encounter that preferred activity, but it is
15306            // possible for the user flow to never be able to return to that
15307            // situation so here we do a sanity check to make sure we haven't
15308            // left any junk around.
15309            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15310            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15311                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15312                removed.clear();
15313                for (PreferredActivity pa : pir.filterSet()) {
15314                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15315                        removed.add(pa);
15316                    }
15317                }
15318                if (removed.size() > 0) {
15319                    for (int r=0; r<removed.size(); r++) {
15320                        PreferredActivity pa = removed.get(r);
15321                        Slog.w(TAG, "Removing dangling preferred activity: "
15322                                + pa.mPref.mComponent);
15323                        pir.removeFilter(pa);
15324                    }
15325                    mSettings.writePackageRestrictionsLPr(
15326                            mSettings.mPreferredActivities.keyAt(i));
15327                }
15328            }
15329
15330            for (int userId : UserManagerService.getInstance().getUserIds()) {
15331                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15332                    grantPermissionsUserIds = ArrayUtils.appendInt(
15333                            grantPermissionsUserIds, userId);
15334                }
15335            }
15336        }
15337        sUserManager.systemReady();
15338
15339        // If we upgraded grant all default permissions before kicking off.
15340        for (int userId : grantPermissionsUserIds) {
15341            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15342        }
15343
15344        // Kick off any messages waiting for system ready
15345        if (mPostSystemReadyMessages != null) {
15346            for (Message msg : mPostSystemReadyMessages) {
15347                msg.sendToTarget();
15348            }
15349            mPostSystemReadyMessages = null;
15350        }
15351
15352        // Watch for external volumes that come and go over time
15353        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15354        storage.registerListener(mStorageListener);
15355
15356        mInstallerService.systemReady();
15357        mPackageDexOptimizer.systemReady();
15358
15359        MountServiceInternal mountServiceInternal = LocalServices.getService(
15360                MountServiceInternal.class);
15361        mountServiceInternal.addExternalStoragePolicy(
15362                new MountServiceInternal.ExternalStorageMountPolicy() {
15363            @Override
15364            public int getMountMode(int uid, String packageName) {
15365                if (Process.isIsolated(uid)) {
15366                    return Zygote.MOUNT_EXTERNAL_NONE;
15367                }
15368                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15369                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15370                }
15371                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15372                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15373                }
15374                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15375                    return Zygote.MOUNT_EXTERNAL_READ;
15376                }
15377                return Zygote.MOUNT_EXTERNAL_WRITE;
15378            }
15379
15380            @Override
15381            public boolean hasExternalStorage(int uid, String packageName) {
15382                return true;
15383            }
15384        });
15385    }
15386
15387    @Override
15388    public boolean isSafeMode() {
15389        return mSafeMode;
15390    }
15391
15392    @Override
15393    public boolean hasSystemUidErrors() {
15394        return mHasSystemUidErrors;
15395    }
15396
15397    static String arrayToString(int[] array) {
15398        StringBuffer buf = new StringBuffer(128);
15399        buf.append('[');
15400        if (array != null) {
15401            for (int i=0; i<array.length; i++) {
15402                if (i > 0) buf.append(", ");
15403                buf.append(array[i]);
15404            }
15405        }
15406        buf.append(']');
15407        return buf.toString();
15408    }
15409
15410    static class DumpState {
15411        public static final int DUMP_LIBS = 1 << 0;
15412        public static final int DUMP_FEATURES = 1 << 1;
15413        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15414        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15415        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15416        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15417        public static final int DUMP_PERMISSIONS = 1 << 6;
15418        public static final int DUMP_PACKAGES = 1 << 7;
15419        public static final int DUMP_SHARED_USERS = 1 << 8;
15420        public static final int DUMP_MESSAGES = 1 << 9;
15421        public static final int DUMP_PROVIDERS = 1 << 10;
15422        public static final int DUMP_VERIFIERS = 1 << 11;
15423        public static final int DUMP_PREFERRED = 1 << 12;
15424        public static final int DUMP_PREFERRED_XML = 1 << 13;
15425        public static final int DUMP_KEYSETS = 1 << 14;
15426        public static final int DUMP_VERSION = 1 << 15;
15427        public static final int DUMP_INSTALLS = 1 << 16;
15428        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15429        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15430
15431        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15432
15433        private int mTypes;
15434
15435        private int mOptions;
15436
15437        private boolean mTitlePrinted;
15438
15439        private SharedUserSetting mSharedUser;
15440
15441        public boolean isDumping(int type) {
15442            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15443                return true;
15444            }
15445
15446            return (mTypes & type) != 0;
15447        }
15448
15449        public void setDump(int type) {
15450            mTypes |= type;
15451        }
15452
15453        public boolean isOptionEnabled(int option) {
15454            return (mOptions & option) != 0;
15455        }
15456
15457        public void setOptionEnabled(int option) {
15458            mOptions |= option;
15459        }
15460
15461        public boolean onTitlePrinted() {
15462            final boolean printed = mTitlePrinted;
15463            mTitlePrinted = true;
15464            return printed;
15465        }
15466
15467        public boolean getTitlePrinted() {
15468            return mTitlePrinted;
15469        }
15470
15471        public void setTitlePrinted(boolean enabled) {
15472            mTitlePrinted = enabled;
15473        }
15474
15475        public SharedUserSetting getSharedUser() {
15476            return mSharedUser;
15477        }
15478
15479        public void setSharedUser(SharedUserSetting user) {
15480            mSharedUser = user;
15481        }
15482    }
15483
15484    @Override
15485    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15486            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15487        (new PackageManagerShellCommand(this)).exec(
15488                this, in, out, err, args, resultReceiver);
15489    }
15490
15491    @Override
15492    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15493        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15494                != PackageManager.PERMISSION_GRANTED) {
15495            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15496                    + Binder.getCallingPid()
15497                    + ", uid=" + Binder.getCallingUid()
15498                    + " without permission "
15499                    + android.Manifest.permission.DUMP);
15500            return;
15501        }
15502
15503        DumpState dumpState = new DumpState();
15504        boolean fullPreferred = false;
15505        boolean checkin = false;
15506
15507        String packageName = null;
15508        ArraySet<String> permissionNames = null;
15509
15510        int opti = 0;
15511        while (opti < args.length) {
15512            String opt = args[opti];
15513            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15514                break;
15515            }
15516            opti++;
15517
15518            if ("-a".equals(opt)) {
15519                // Right now we only know how to print all.
15520            } else if ("-h".equals(opt)) {
15521                pw.println("Package manager dump options:");
15522                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15523                pw.println("    --checkin: dump for a checkin");
15524                pw.println("    -f: print details of intent filters");
15525                pw.println("    -h: print this help");
15526                pw.println("  cmd may be one of:");
15527                pw.println("    l[ibraries]: list known shared libraries");
15528                pw.println("    f[eatures]: list device features");
15529                pw.println("    k[eysets]: print known keysets");
15530                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15531                pw.println("    perm[issions]: dump permissions");
15532                pw.println("    permission [name ...]: dump declaration and use of given permission");
15533                pw.println("    pref[erred]: print preferred package settings");
15534                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15535                pw.println("    prov[iders]: dump content providers");
15536                pw.println("    p[ackages]: dump installed packages");
15537                pw.println("    s[hared-users]: dump shared user IDs");
15538                pw.println("    m[essages]: print collected runtime messages");
15539                pw.println("    v[erifiers]: print package verifier info");
15540                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15541                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15542                pw.println("    version: print database version info");
15543                pw.println("    write: write current settings now");
15544                pw.println("    installs: details about install sessions");
15545                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15546                pw.println("    <package.name>: info about given package");
15547                return;
15548            } else if ("--checkin".equals(opt)) {
15549                checkin = true;
15550            } else if ("-f".equals(opt)) {
15551                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15552            } else {
15553                pw.println("Unknown argument: " + opt + "; use -h for help");
15554            }
15555        }
15556
15557        // Is the caller requesting to dump a particular piece of data?
15558        if (opti < args.length) {
15559            String cmd = args[opti];
15560            opti++;
15561            // Is this a package name?
15562            if ("android".equals(cmd) || cmd.contains(".")) {
15563                packageName = cmd;
15564                // When dumping a single package, we always dump all of its
15565                // filter information since the amount of data will be reasonable.
15566                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15567            } else if ("check-permission".equals(cmd)) {
15568                if (opti >= args.length) {
15569                    pw.println("Error: check-permission missing permission argument");
15570                    return;
15571                }
15572                String perm = args[opti];
15573                opti++;
15574                if (opti >= args.length) {
15575                    pw.println("Error: check-permission missing package argument");
15576                    return;
15577                }
15578                String pkg = args[opti];
15579                opti++;
15580                int user = UserHandle.getUserId(Binder.getCallingUid());
15581                if (opti < args.length) {
15582                    try {
15583                        user = Integer.parseInt(args[opti]);
15584                    } catch (NumberFormatException e) {
15585                        pw.println("Error: check-permission user argument is not a number: "
15586                                + args[opti]);
15587                        return;
15588                    }
15589                }
15590                pw.println(checkPermission(perm, pkg, user));
15591                return;
15592            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15593                dumpState.setDump(DumpState.DUMP_LIBS);
15594            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15595                dumpState.setDump(DumpState.DUMP_FEATURES);
15596            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15597                if (opti >= args.length) {
15598                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15599                            | DumpState.DUMP_SERVICE_RESOLVERS
15600                            | DumpState.DUMP_RECEIVER_RESOLVERS
15601                            | DumpState.DUMP_CONTENT_RESOLVERS);
15602                } else {
15603                    while (opti < args.length) {
15604                        String name = args[opti];
15605                        if ("a".equals(name) || "activity".equals(name)) {
15606                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15607                        } else if ("s".equals(name) || "service".equals(name)) {
15608                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15609                        } else if ("r".equals(name) || "receiver".equals(name)) {
15610                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15611                        } else if ("c".equals(name) || "content".equals(name)) {
15612                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15613                        } else {
15614                            pw.println("Error: unknown resolver table type: " + name);
15615                            return;
15616                        }
15617                        opti++;
15618                    }
15619                }
15620            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15621                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15622            } else if ("permission".equals(cmd)) {
15623                if (opti >= args.length) {
15624                    pw.println("Error: permission requires permission name");
15625                    return;
15626                }
15627                permissionNames = new ArraySet<>();
15628                while (opti < args.length) {
15629                    permissionNames.add(args[opti]);
15630                    opti++;
15631                }
15632                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15633                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15634            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15635                dumpState.setDump(DumpState.DUMP_PREFERRED);
15636            } else if ("preferred-xml".equals(cmd)) {
15637                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15638                if (opti < args.length && "--full".equals(args[opti])) {
15639                    fullPreferred = true;
15640                    opti++;
15641                }
15642            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15643                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15644            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15645                dumpState.setDump(DumpState.DUMP_PACKAGES);
15646            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15647                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15648            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15649                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15650            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15651                dumpState.setDump(DumpState.DUMP_MESSAGES);
15652            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15653                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15654            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15655                    || "intent-filter-verifiers".equals(cmd)) {
15656                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15657            } else if ("version".equals(cmd)) {
15658                dumpState.setDump(DumpState.DUMP_VERSION);
15659            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15660                dumpState.setDump(DumpState.DUMP_KEYSETS);
15661            } else if ("installs".equals(cmd)) {
15662                dumpState.setDump(DumpState.DUMP_INSTALLS);
15663            } else if ("write".equals(cmd)) {
15664                synchronized (mPackages) {
15665                    mSettings.writeLPr();
15666                    pw.println("Settings written.");
15667                    return;
15668                }
15669            }
15670        }
15671
15672        if (checkin) {
15673            pw.println("vers,1");
15674        }
15675
15676        // reader
15677        synchronized (mPackages) {
15678            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15679                if (!checkin) {
15680                    if (dumpState.onTitlePrinted())
15681                        pw.println();
15682                    pw.println("Database versions:");
15683                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15684                }
15685            }
15686
15687            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15688                if (!checkin) {
15689                    if (dumpState.onTitlePrinted())
15690                        pw.println();
15691                    pw.println("Verifiers:");
15692                    pw.print("  Required: ");
15693                    pw.print(mRequiredVerifierPackage);
15694                    pw.print(" (uid=");
15695                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15696                    pw.println(")");
15697                } else if (mRequiredVerifierPackage != null) {
15698                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15699                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15700                }
15701            }
15702
15703            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15704                    packageName == null) {
15705                if (mIntentFilterVerifierComponent != null) {
15706                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15707                    if (!checkin) {
15708                        if (dumpState.onTitlePrinted())
15709                            pw.println();
15710                        pw.println("Intent Filter Verifier:");
15711                        pw.print("  Using: ");
15712                        pw.print(verifierPackageName);
15713                        pw.print(" (uid=");
15714                        pw.print(getPackageUid(verifierPackageName, 0));
15715                        pw.println(")");
15716                    } else if (verifierPackageName != null) {
15717                        pw.print("ifv,"); pw.print(verifierPackageName);
15718                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15719                    }
15720                } else {
15721                    pw.println();
15722                    pw.println("No Intent Filter Verifier available!");
15723                }
15724            }
15725
15726            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15727                boolean printedHeader = false;
15728                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15729                while (it.hasNext()) {
15730                    String name = it.next();
15731                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15732                    if (!checkin) {
15733                        if (!printedHeader) {
15734                            if (dumpState.onTitlePrinted())
15735                                pw.println();
15736                            pw.println("Libraries:");
15737                            printedHeader = true;
15738                        }
15739                        pw.print("  ");
15740                    } else {
15741                        pw.print("lib,");
15742                    }
15743                    pw.print(name);
15744                    if (!checkin) {
15745                        pw.print(" -> ");
15746                    }
15747                    if (ent.path != null) {
15748                        if (!checkin) {
15749                            pw.print("(jar) ");
15750                            pw.print(ent.path);
15751                        } else {
15752                            pw.print(",jar,");
15753                            pw.print(ent.path);
15754                        }
15755                    } else {
15756                        if (!checkin) {
15757                            pw.print("(apk) ");
15758                            pw.print(ent.apk);
15759                        } else {
15760                            pw.print(",apk,");
15761                            pw.print(ent.apk);
15762                        }
15763                    }
15764                    pw.println();
15765                }
15766            }
15767
15768            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15769                if (dumpState.onTitlePrinted())
15770                    pw.println();
15771                if (!checkin) {
15772                    pw.println("Features:");
15773                }
15774                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15775                while (it.hasNext()) {
15776                    String name = it.next();
15777                    if (!checkin) {
15778                        pw.print("  ");
15779                    } else {
15780                        pw.print("feat,");
15781                    }
15782                    pw.println(name);
15783                }
15784            }
15785
15786            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15787                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15788                        : "Activity Resolver Table:", "  ", packageName,
15789                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15790                    dumpState.setTitlePrinted(true);
15791                }
15792            }
15793            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15794                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15795                        : "Receiver Resolver Table:", "  ", packageName,
15796                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15797                    dumpState.setTitlePrinted(true);
15798                }
15799            }
15800            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15801                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15802                        : "Service Resolver Table:", "  ", packageName,
15803                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15804                    dumpState.setTitlePrinted(true);
15805                }
15806            }
15807            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15808                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15809                        : "Provider Resolver Table:", "  ", packageName,
15810                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15811                    dumpState.setTitlePrinted(true);
15812                }
15813            }
15814
15815            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15816                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15817                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15818                    int user = mSettings.mPreferredActivities.keyAt(i);
15819                    if (pir.dump(pw,
15820                            dumpState.getTitlePrinted()
15821                                ? "\nPreferred Activities User " + user + ":"
15822                                : "Preferred Activities User " + user + ":", "  ",
15823                            packageName, true, false)) {
15824                        dumpState.setTitlePrinted(true);
15825                    }
15826                }
15827            }
15828
15829            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15830                pw.flush();
15831                FileOutputStream fout = new FileOutputStream(fd);
15832                BufferedOutputStream str = new BufferedOutputStream(fout);
15833                XmlSerializer serializer = new FastXmlSerializer();
15834                try {
15835                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15836                    serializer.startDocument(null, true);
15837                    serializer.setFeature(
15838                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15839                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15840                    serializer.endDocument();
15841                    serializer.flush();
15842                } catch (IllegalArgumentException e) {
15843                    pw.println("Failed writing: " + e);
15844                } catch (IllegalStateException e) {
15845                    pw.println("Failed writing: " + e);
15846                } catch (IOException e) {
15847                    pw.println("Failed writing: " + e);
15848                }
15849            }
15850
15851            if (!checkin
15852                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15853                    && packageName == null) {
15854                pw.println();
15855                int count = mSettings.mPackages.size();
15856                if (count == 0) {
15857                    pw.println("No applications!");
15858                    pw.println();
15859                } else {
15860                    final String prefix = "  ";
15861                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15862                    if (allPackageSettings.size() == 0) {
15863                        pw.println("No domain preferred apps!");
15864                        pw.println();
15865                    } else {
15866                        pw.println("App verification status:");
15867                        pw.println();
15868                        count = 0;
15869                        for (PackageSetting ps : allPackageSettings) {
15870                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15871                            if (ivi == null || ivi.getPackageName() == null) continue;
15872                            pw.println(prefix + "Package: " + ivi.getPackageName());
15873                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15874                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15875                            pw.println();
15876                            count++;
15877                        }
15878                        if (count == 0) {
15879                            pw.println(prefix + "No app verification established.");
15880                            pw.println();
15881                        }
15882                        for (int userId : sUserManager.getUserIds()) {
15883                            pw.println("App linkages for user " + userId + ":");
15884                            pw.println();
15885                            count = 0;
15886                            for (PackageSetting ps : allPackageSettings) {
15887                                final long status = ps.getDomainVerificationStatusForUser(userId);
15888                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15889                                    continue;
15890                                }
15891                                pw.println(prefix + "Package: " + ps.name);
15892                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15893                                String statusStr = IntentFilterVerificationInfo.
15894                                        getStatusStringFromValue(status);
15895                                pw.println(prefix + "Status:  " + statusStr);
15896                                pw.println();
15897                                count++;
15898                            }
15899                            if (count == 0) {
15900                                pw.println(prefix + "No configured app linkages.");
15901                                pw.println();
15902                            }
15903                        }
15904                    }
15905                }
15906            }
15907
15908            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15909                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15910                if (packageName == null && permissionNames == null) {
15911                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15912                        if (iperm == 0) {
15913                            if (dumpState.onTitlePrinted())
15914                                pw.println();
15915                            pw.println("AppOp Permissions:");
15916                        }
15917                        pw.print("  AppOp Permission ");
15918                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15919                        pw.println(":");
15920                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15921                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15922                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15923                        }
15924                    }
15925                }
15926            }
15927
15928            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15929                boolean printedSomething = false;
15930                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15931                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15932                        continue;
15933                    }
15934                    if (!printedSomething) {
15935                        if (dumpState.onTitlePrinted())
15936                            pw.println();
15937                        pw.println("Registered ContentProviders:");
15938                        printedSomething = true;
15939                    }
15940                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15941                    pw.print("    "); pw.println(p.toString());
15942                }
15943                printedSomething = false;
15944                for (Map.Entry<String, PackageParser.Provider> entry :
15945                        mProvidersByAuthority.entrySet()) {
15946                    PackageParser.Provider p = entry.getValue();
15947                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15948                        continue;
15949                    }
15950                    if (!printedSomething) {
15951                        if (dumpState.onTitlePrinted())
15952                            pw.println();
15953                        pw.println("ContentProvider Authorities:");
15954                        printedSomething = true;
15955                    }
15956                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15957                    pw.print("    "); pw.println(p.toString());
15958                    if (p.info != null && p.info.applicationInfo != null) {
15959                        final String appInfo = p.info.applicationInfo.toString();
15960                        pw.print("      applicationInfo="); pw.println(appInfo);
15961                    }
15962                }
15963            }
15964
15965            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15966                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15967            }
15968
15969            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15970                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15971            }
15972
15973            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15974                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15975            }
15976
15977            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15978                // XXX should handle packageName != null by dumping only install data that
15979                // the given package is involved with.
15980                if (dumpState.onTitlePrinted()) pw.println();
15981                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15982            }
15983
15984            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15985                if (dumpState.onTitlePrinted()) pw.println();
15986                mSettings.dumpReadMessagesLPr(pw, dumpState);
15987
15988                pw.println();
15989                pw.println("Package warning messages:");
15990                BufferedReader in = null;
15991                String line = null;
15992                try {
15993                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15994                    while ((line = in.readLine()) != null) {
15995                        if (line.contains("ignored: updated version")) continue;
15996                        pw.println(line);
15997                    }
15998                } catch (IOException ignored) {
15999                } finally {
16000                    IoUtils.closeQuietly(in);
16001                }
16002            }
16003
16004            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16005                BufferedReader in = null;
16006                String line = null;
16007                try {
16008                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16009                    while ((line = in.readLine()) != null) {
16010                        if (line.contains("ignored: updated version")) continue;
16011                        pw.print("msg,");
16012                        pw.println(line);
16013                    }
16014                } catch (IOException ignored) {
16015                } finally {
16016                    IoUtils.closeQuietly(in);
16017                }
16018            }
16019        }
16020    }
16021
16022    private String dumpDomainString(String packageName) {
16023        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16024        List<IntentFilter> filters = getAllIntentFilters(packageName);
16025
16026        ArraySet<String> result = new ArraySet<>();
16027        if (iviList.size() > 0) {
16028            for (IntentFilterVerificationInfo ivi : iviList) {
16029                for (String host : ivi.getDomains()) {
16030                    result.add(host);
16031                }
16032            }
16033        }
16034        if (filters != null && filters.size() > 0) {
16035            for (IntentFilter filter : filters) {
16036                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16037                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16038                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16039                    result.addAll(filter.getHostsList());
16040                }
16041            }
16042        }
16043
16044        StringBuilder sb = new StringBuilder(result.size() * 16);
16045        for (String domain : result) {
16046            if (sb.length() > 0) sb.append(" ");
16047            sb.append(domain);
16048        }
16049        return sb.toString();
16050    }
16051
16052    // ------- apps on sdcard specific code -------
16053    static final boolean DEBUG_SD_INSTALL = false;
16054
16055    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16056
16057    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16058
16059    private boolean mMediaMounted = false;
16060
16061    static String getEncryptKey() {
16062        try {
16063            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16064                    SD_ENCRYPTION_KEYSTORE_NAME);
16065            if (sdEncKey == null) {
16066                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16067                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16068                if (sdEncKey == null) {
16069                    Slog.e(TAG, "Failed to create encryption keys");
16070                    return null;
16071                }
16072            }
16073            return sdEncKey;
16074        } catch (NoSuchAlgorithmException nsae) {
16075            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16076            return null;
16077        } catch (IOException ioe) {
16078            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16079            return null;
16080        }
16081    }
16082
16083    /*
16084     * Update media status on PackageManager.
16085     */
16086    @Override
16087    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16088        int callingUid = Binder.getCallingUid();
16089        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16090            throw new SecurityException("Media status can only be updated by the system");
16091        }
16092        // reader; this apparently protects mMediaMounted, but should probably
16093        // be a different lock in that case.
16094        synchronized (mPackages) {
16095            Log.i(TAG, "Updating external media status from "
16096                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16097                    + (mediaStatus ? "mounted" : "unmounted"));
16098            if (DEBUG_SD_INSTALL)
16099                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16100                        + ", mMediaMounted=" + mMediaMounted);
16101            if (mediaStatus == mMediaMounted) {
16102                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16103                        : 0, -1);
16104                mHandler.sendMessage(msg);
16105                return;
16106            }
16107            mMediaMounted = mediaStatus;
16108        }
16109        // Queue up an async operation since the package installation may take a
16110        // little while.
16111        mHandler.post(new Runnable() {
16112            public void run() {
16113                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16114            }
16115        });
16116    }
16117
16118    /**
16119     * Called by MountService when the initial ASECs to scan are available.
16120     * Should block until all the ASEC containers are finished being scanned.
16121     */
16122    public void scanAvailableAsecs() {
16123        updateExternalMediaStatusInner(true, false, false);
16124        if (mShouldRestoreconData) {
16125            SELinuxMMAC.setRestoreconDone();
16126            mShouldRestoreconData = false;
16127        }
16128    }
16129
16130    /*
16131     * Collect information of applications on external media, map them against
16132     * existing containers and update information based on current mount status.
16133     * Please note that we always have to report status if reportStatus has been
16134     * set to true especially when unloading packages.
16135     */
16136    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16137            boolean externalStorage) {
16138        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16139        int[] uidArr = EmptyArray.INT;
16140
16141        final String[] list = PackageHelper.getSecureContainerList();
16142        if (ArrayUtils.isEmpty(list)) {
16143            Log.i(TAG, "No secure containers found");
16144        } else {
16145            // Process list of secure containers and categorize them
16146            // as active or stale based on their package internal state.
16147
16148            // reader
16149            synchronized (mPackages) {
16150                for (String cid : list) {
16151                    // Leave stages untouched for now; installer service owns them
16152                    if (PackageInstallerService.isStageName(cid)) continue;
16153
16154                    if (DEBUG_SD_INSTALL)
16155                        Log.i(TAG, "Processing container " + cid);
16156                    String pkgName = getAsecPackageName(cid);
16157                    if (pkgName == null) {
16158                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16159                        continue;
16160                    }
16161                    if (DEBUG_SD_INSTALL)
16162                        Log.i(TAG, "Looking for pkg : " + pkgName);
16163
16164                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16165                    if (ps == null) {
16166                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16167                        continue;
16168                    }
16169
16170                    /*
16171                     * Skip packages that are not external if we're unmounting
16172                     * external storage.
16173                     */
16174                    if (externalStorage && !isMounted && !isExternal(ps)) {
16175                        continue;
16176                    }
16177
16178                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16179                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16180                    // The package status is changed only if the code path
16181                    // matches between settings and the container id.
16182                    if (ps.codePathString != null
16183                            && ps.codePathString.startsWith(args.getCodePath())) {
16184                        if (DEBUG_SD_INSTALL) {
16185                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16186                                    + " at code path: " + ps.codePathString);
16187                        }
16188
16189                        // We do have a valid package installed on sdcard
16190                        processCids.put(args, ps.codePathString);
16191                        final int uid = ps.appId;
16192                        if (uid != -1) {
16193                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16194                        }
16195                    } else {
16196                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16197                                + ps.codePathString);
16198                    }
16199                }
16200            }
16201
16202            Arrays.sort(uidArr);
16203        }
16204
16205        // Process packages with valid entries.
16206        if (isMounted) {
16207            if (DEBUG_SD_INSTALL)
16208                Log.i(TAG, "Loading packages");
16209            loadMediaPackages(processCids, uidArr, externalStorage);
16210            startCleaningPackages();
16211            mInstallerService.onSecureContainersAvailable();
16212        } else {
16213            if (DEBUG_SD_INSTALL)
16214                Log.i(TAG, "Unloading packages");
16215            unloadMediaPackages(processCids, uidArr, reportStatus);
16216        }
16217    }
16218
16219    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16220            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16221        final int size = infos.size();
16222        final String[] packageNames = new String[size];
16223        final int[] packageUids = new int[size];
16224        for (int i = 0; i < size; i++) {
16225            final ApplicationInfo info = infos.get(i);
16226            packageNames[i] = info.packageName;
16227            packageUids[i] = info.uid;
16228        }
16229        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16230                finishedReceiver);
16231    }
16232
16233    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16234            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16235        sendResourcesChangedBroadcast(mediaStatus, replacing,
16236                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16237    }
16238
16239    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16240            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16241        int size = pkgList.length;
16242        if (size > 0) {
16243            // Send broadcasts here
16244            Bundle extras = new Bundle();
16245            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16246            if (uidArr != null) {
16247                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16248            }
16249            if (replacing) {
16250                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16251            }
16252            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16253                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16254            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16255        }
16256    }
16257
16258   /*
16259     * Look at potentially valid container ids from processCids If package
16260     * information doesn't match the one on record or package scanning fails,
16261     * the cid is added to list of removeCids. We currently don't delete stale
16262     * containers.
16263     */
16264    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16265            boolean externalStorage) {
16266        ArrayList<String> pkgList = new ArrayList<String>();
16267        Set<AsecInstallArgs> keys = processCids.keySet();
16268
16269        for (AsecInstallArgs args : keys) {
16270            String codePath = processCids.get(args);
16271            if (DEBUG_SD_INSTALL)
16272                Log.i(TAG, "Loading container : " + args.cid);
16273            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16274            try {
16275                // Make sure there are no container errors first.
16276                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16277                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16278                            + " when installing from sdcard");
16279                    continue;
16280                }
16281                // Check code path here.
16282                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16283                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16284                            + " does not match one in settings " + codePath);
16285                    continue;
16286                }
16287                // Parse package
16288                int parseFlags = mDefParseFlags;
16289                if (args.isExternalAsec()) {
16290                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16291                }
16292                if (args.isFwdLocked()) {
16293                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16294                }
16295
16296                synchronized (mInstallLock) {
16297                    PackageParser.Package pkg = null;
16298                    try {
16299                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16300                    } catch (PackageManagerException e) {
16301                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16302                    }
16303                    // Scan the package
16304                    if (pkg != null) {
16305                        /*
16306                         * TODO why is the lock being held? doPostInstall is
16307                         * called in other places without the lock. This needs
16308                         * to be straightened out.
16309                         */
16310                        // writer
16311                        synchronized (mPackages) {
16312                            retCode = PackageManager.INSTALL_SUCCEEDED;
16313                            pkgList.add(pkg.packageName);
16314                            // Post process args
16315                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16316                                    pkg.applicationInfo.uid);
16317                        }
16318                    } else {
16319                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16320                    }
16321                }
16322
16323            } finally {
16324                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16325                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16326                }
16327            }
16328        }
16329        // writer
16330        synchronized (mPackages) {
16331            // If the platform SDK has changed since the last time we booted,
16332            // we need to re-grant app permission to catch any new ones that
16333            // appear. This is really a hack, and means that apps can in some
16334            // cases get permissions that the user didn't initially explicitly
16335            // allow... it would be nice to have some better way to handle
16336            // this situation.
16337            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16338                    : mSettings.getInternalVersion();
16339            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16340                    : StorageManager.UUID_PRIVATE_INTERNAL;
16341
16342            int updateFlags = UPDATE_PERMISSIONS_ALL;
16343            if (ver.sdkVersion != mSdkVersion) {
16344                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16345                        + mSdkVersion + "; regranting permissions for external");
16346                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16347            }
16348            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16349
16350            // Yay, everything is now upgraded
16351            ver.forceCurrent();
16352
16353            // can downgrade to reader
16354            // Persist settings
16355            mSettings.writeLPr();
16356        }
16357        // Send a broadcast to let everyone know we are done processing
16358        if (pkgList.size() > 0) {
16359            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16360        }
16361    }
16362
16363   /*
16364     * Utility method to unload a list of specified containers
16365     */
16366    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16367        // Just unmount all valid containers.
16368        for (AsecInstallArgs arg : cidArgs) {
16369            synchronized (mInstallLock) {
16370                arg.doPostDeleteLI(false);
16371           }
16372       }
16373   }
16374
16375    /*
16376     * Unload packages mounted on external media. This involves deleting package
16377     * data from internal structures, sending broadcasts about diabled packages,
16378     * gc'ing to free up references, unmounting all secure containers
16379     * corresponding to packages on external media, and posting a
16380     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16381     * that we always have to post this message if status has been requested no
16382     * matter what.
16383     */
16384    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16385            final boolean reportStatus) {
16386        if (DEBUG_SD_INSTALL)
16387            Log.i(TAG, "unloading media packages");
16388        ArrayList<String> pkgList = new ArrayList<String>();
16389        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16390        final Set<AsecInstallArgs> keys = processCids.keySet();
16391        for (AsecInstallArgs args : keys) {
16392            String pkgName = args.getPackageName();
16393            if (DEBUG_SD_INSTALL)
16394                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16395            // Delete package internally
16396            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16397            synchronized (mInstallLock) {
16398                boolean res = deletePackageLI(pkgName, null, false, null, null,
16399                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16400                if (res) {
16401                    pkgList.add(pkgName);
16402                } else {
16403                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16404                    failedList.add(args);
16405                }
16406            }
16407        }
16408
16409        // reader
16410        synchronized (mPackages) {
16411            // We didn't update the settings after removing each package;
16412            // write them now for all packages.
16413            mSettings.writeLPr();
16414        }
16415
16416        // We have to absolutely send UPDATED_MEDIA_STATUS only
16417        // after confirming that all the receivers processed the ordered
16418        // broadcast when packages get disabled, force a gc to clean things up.
16419        // and unload all the containers.
16420        if (pkgList.size() > 0) {
16421            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16422                    new IIntentReceiver.Stub() {
16423                public void performReceive(Intent intent, int resultCode, String data,
16424                        Bundle extras, boolean ordered, boolean sticky,
16425                        int sendingUser) throws RemoteException {
16426                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16427                            reportStatus ? 1 : 0, 1, keys);
16428                    mHandler.sendMessage(msg);
16429                }
16430            });
16431        } else {
16432            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16433                    keys);
16434            mHandler.sendMessage(msg);
16435        }
16436    }
16437
16438    private void loadPrivatePackages(final VolumeInfo vol) {
16439        mHandler.post(new Runnable() {
16440            @Override
16441            public void run() {
16442                loadPrivatePackagesInner(vol);
16443            }
16444        });
16445    }
16446
16447    private void loadPrivatePackagesInner(VolumeInfo vol) {
16448        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16449        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16450
16451        final VersionInfo ver;
16452        final List<PackageSetting> packages;
16453        synchronized (mPackages) {
16454            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16455            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16456        }
16457
16458        for (PackageSetting ps : packages) {
16459            synchronized (mInstallLock) {
16460                final PackageParser.Package pkg;
16461                try {
16462                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16463                    loaded.add(pkg.applicationInfo);
16464                } catch (PackageManagerException e) {
16465                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16466                }
16467
16468                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16469                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16470                }
16471            }
16472        }
16473
16474        synchronized (mPackages) {
16475            int updateFlags = UPDATE_PERMISSIONS_ALL;
16476            if (ver.sdkVersion != mSdkVersion) {
16477                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16478                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16479                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16480            }
16481            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16482
16483            // Yay, everything is now upgraded
16484            ver.forceCurrent();
16485
16486            mSettings.writeLPr();
16487        }
16488
16489        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16490        sendResourcesChangedBroadcast(true, false, loaded, null);
16491    }
16492
16493    private void unloadPrivatePackages(final VolumeInfo vol) {
16494        mHandler.post(new Runnable() {
16495            @Override
16496            public void run() {
16497                unloadPrivatePackagesInner(vol);
16498            }
16499        });
16500    }
16501
16502    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16503        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16504        synchronized (mInstallLock) {
16505        synchronized (mPackages) {
16506            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16507            for (PackageSetting ps : packages) {
16508                if (ps.pkg == null) continue;
16509
16510                final ApplicationInfo info = ps.pkg.applicationInfo;
16511                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16512                if (deletePackageLI(ps.name, null, false, null, null,
16513                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16514                    unloaded.add(info);
16515                } else {
16516                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16517                }
16518            }
16519
16520            mSettings.writeLPr();
16521        }
16522        }
16523
16524        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16525        sendResourcesChangedBroadcast(false, false, unloaded, null);
16526    }
16527
16528    /**
16529     * Examine all users present on given mounted volume, and destroy data
16530     * belonging to users that are no longer valid, or whose user ID has been
16531     * recycled.
16532     */
16533    private void reconcileUsers(String volumeUuid) {
16534        final File[] files = FileUtils
16535                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16536        for (File file : files) {
16537            if (!file.isDirectory()) continue;
16538
16539            final int userId;
16540            final UserInfo info;
16541            try {
16542                userId = Integer.parseInt(file.getName());
16543                info = sUserManager.getUserInfo(userId);
16544            } catch (NumberFormatException e) {
16545                Slog.w(TAG, "Invalid user directory " + file);
16546                continue;
16547            }
16548
16549            boolean destroyUser = false;
16550            if (info == null) {
16551                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16552                        + " because no matching user was found");
16553                destroyUser = true;
16554            } else {
16555                try {
16556                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16557                } catch (IOException e) {
16558                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16559                            + " because we failed to enforce serial number: " + e);
16560                    destroyUser = true;
16561                }
16562            }
16563
16564            if (destroyUser) {
16565                synchronized (mInstallLock) {
16566                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16567                }
16568            }
16569        }
16570
16571        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16572        final UserManager um = mContext.getSystemService(UserManager.class);
16573        for (UserInfo user : um.getUsers()) {
16574            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16575            if (userDir.exists()) continue;
16576
16577            try {
16578                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16579                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16580            } catch (IOException e) {
16581                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16582            }
16583        }
16584    }
16585
16586    /**
16587     * Examine all apps present on given mounted volume, and destroy apps that
16588     * aren't expected, either due to uninstallation or reinstallation on
16589     * another volume.
16590     */
16591    private void reconcileApps(String volumeUuid) {
16592        final File[] files = FileUtils
16593                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16594        for (File file : files) {
16595            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16596                    && !PackageInstallerService.isStageName(file.getName());
16597            if (!isPackage) {
16598                // Ignore entries which are not packages
16599                continue;
16600            }
16601
16602            boolean destroyApp = false;
16603            String packageName = null;
16604            try {
16605                final PackageLite pkg = PackageParser.parsePackageLite(file,
16606                        PackageParser.PARSE_MUST_BE_APK);
16607                packageName = pkg.packageName;
16608
16609                synchronized (mPackages) {
16610                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16611                    if (ps == null) {
16612                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16613                                + volumeUuid + " because we found no install record");
16614                        destroyApp = true;
16615                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16616                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16617                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16618                        destroyApp = true;
16619                    }
16620                }
16621
16622            } catch (PackageParserException e) {
16623                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16624                destroyApp = true;
16625            }
16626
16627            if (destroyApp) {
16628                synchronized (mInstallLock) {
16629                    if (packageName != null) {
16630                        removeDataDirsLI(volumeUuid, packageName);
16631                    }
16632                    if (file.isDirectory()) {
16633                        mInstaller.rmPackageDir(file.getAbsolutePath());
16634                    } else {
16635                        file.delete();
16636                    }
16637                }
16638            }
16639        }
16640    }
16641
16642    private void unfreezePackage(String packageName) {
16643        synchronized (mPackages) {
16644            final PackageSetting ps = mSettings.mPackages.get(packageName);
16645            if (ps != null) {
16646                ps.frozen = false;
16647            }
16648        }
16649    }
16650
16651    @Override
16652    public int movePackage(final String packageName, final String volumeUuid) {
16653        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16654
16655        final int moveId = mNextMoveId.getAndIncrement();
16656        mHandler.post(new Runnable() {
16657            @Override
16658            public void run() {
16659                try {
16660                    movePackageInternal(packageName, volumeUuid, moveId);
16661                } catch (PackageManagerException e) {
16662                    Slog.w(TAG, "Failed to move " + packageName, e);
16663                    mMoveCallbacks.notifyStatusChanged(moveId,
16664                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16665                }
16666            }
16667        });
16668        return moveId;
16669    }
16670
16671    private void movePackageInternal(final String packageName, final String volumeUuid,
16672            final int moveId) throws PackageManagerException {
16673        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16674        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16675        final PackageManager pm = mContext.getPackageManager();
16676
16677        final boolean currentAsec;
16678        final String currentVolumeUuid;
16679        final File codeFile;
16680        final String installerPackageName;
16681        final String packageAbiOverride;
16682        final int appId;
16683        final String seinfo;
16684        final String label;
16685
16686        // reader
16687        synchronized (mPackages) {
16688            final PackageParser.Package pkg = mPackages.get(packageName);
16689            final PackageSetting ps = mSettings.mPackages.get(packageName);
16690            if (pkg == null || ps == null) {
16691                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16692            }
16693
16694            if (pkg.applicationInfo.isSystemApp()) {
16695                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16696                        "Cannot move system application");
16697            }
16698
16699            if (pkg.applicationInfo.isExternalAsec()) {
16700                currentAsec = true;
16701                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16702            } else if (pkg.applicationInfo.isForwardLocked()) {
16703                currentAsec = true;
16704                currentVolumeUuid = "forward_locked";
16705            } else {
16706                currentAsec = false;
16707                currentVolumeUuid = ps.volumeUuid;
16708
16709                final File probe = new File(pkg.codePath);
16710                final File probeOat = new File(probe, "oat");
16711                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16712                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16713                            "Move only supported for modern cluster style installs");
16714                }
16715            }
16716
16717            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16718                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16719                        "Package already moved to " + volumeUuid);
16720            }
16721
16722            if (ps.frozen) {
16723                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16724                        "Failed to move already frozen package");
16725            }
16726            ps.frozen = true;
16727
16728            codeFile = new File(pkg.codePath);
16729            installerPackageName = ps.installerPackageName;
16730            packageAbiOverride = ps.cpuAbiOverrideString;
16731            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16732            seinfo = pkg.applicationInfo.seinfo;
16733            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16734        }
16735
16736        // Now that we're guarded by frozen state, kill app during move
16737        final long token = Binder.clearCallingIdentity();
16738        try {
16739            killApplication(packageName, appId, "move pkg");
16740        } finally {
16741            Binder.restoreCallingIdentity(token);
16742        }
16743
16744        final Bundle extras = new Bundle();
16745        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16746        extras.putString(Intent.EXTRA_TITLE, label);
16747        mMoveCallbacks.notifyCreated(moveId, extras);
16748
16749        int installFlags;
16750        final boolean moveCompleteApp;
16751        final File measurePath;
16752
16753        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16754            installFlags = INSTALL_INTERNAL;
16755            moveCompleteApp = !currentAsec;
16756            measurePath = Environment.getDataAppDirectory(volumeUuid);
16757        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16758            installFlags = INSTALL_EXTERNAL;
16759            moveCompleteApp = false;
16760            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16761        } else {
16762            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16763            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16764                    || !volume.isMountedWritable()) {
16765                unfreezePackage(packageName);
16766                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16767                        "Move location not mounted private volume");
16768            }
16769
16770            Preconditions.checkState(!currentAsec);
16771
16772            installFlags = INSTALL_INTERNAL;
16773            moveCompleteApp = true;
16774            measurePath = Environment.getDataAppDirectory(volumeUuid);
16775        }
16776
16777        final PackageStats stats = new PackageStats(null, -1);
16778        synchronized (mInstaller) {
16779            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16780                unfreezePackage(packageName);
16781                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16782                        "Failed to measure package size");
16783            }
16784        }
16785
16786        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16787                + stats.dataSize);
16788
16789        final long startFreeBytes = measurePath.getFreeSpace();
16790        final long sizeBytes;
16791        if (moveCompleteApp) {
16792            sizeBytes = stats.codeSize + stats.dataSize;
16793        } else {
16794            sizeBytes = stats.codeSize;
16795        }
16796
16797        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16798            unfreezePackage(packageName);
16799            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16800                    "Not enough free space to move");
16801        }
16802
16803        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16804
16805        final CountDownLatch installedLatch = new CountDownLatch(1);
16806        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16807            @Override
16808            public void onUserActionRequired(Intent intent) throws RemoteException {
16809                throw new IllegalStateException();
16810            }
16811
16812            @Override
16813            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16814                    Bundle extras) throws RemoteException {
16815                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16816                        + PackageManager.installStatusToString(returnCode, msg));
16817
16818                installedLatch.countDown();
16819
16820                // Regardless of success or failure of the move operation,
16821                // always unfreeze the package
16822                unfreezePackage(packageName);
16823
16824                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16825                switch (status) {
16826                    case PackageInstaller.STATUS_SUCCESS:
16827                        mMoveCallbacks.notifyStatusChanged(moveId,
16828                                PackageManager.MOVE_SUCCEEDED);
16829                        break;
16830                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16831                        mMoveCallbacks.notifyStatusChanged(moveId,
16832                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16833                        break;
16834                    default:
16835                        mMoveCallbacks.notifyStatusChanged(moveId,
16836                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16837                        break;
16838                }
16839            }
16840        };
16841
16842        final MoveInfo move;
16843        if (moveCompleteApp) {
16844            // Kick off a thread to report progress estimates
16845            new Thread() {
16846                @Override
16847                public void run() {
16848                    while (true) {
16849                        try {
16850                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16851                                break;
16852                            }
16853                        } catch (InterruptedException ignored) {
16854                        }
16855
16856                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16857                        final int progress = 10 + (int) MathUtils.constrain(
16858                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16859                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16860                    }
16861                }
16862            }.start();
16863
16864            final String dataAppName = codeFile.getName();
16865            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16866                    dataAppName, appId, seinfo);
16867        } else {
16868            move = null;
16869        }
16870
16871        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16872
16873        final Message msg = mHandler.obtainMessage(INIT_COPY);
16874        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16875        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16876                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16877        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16878        msg.obj = params;
16879
16880        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16881                System.identityHashCode(msg.obj));
16882        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16883                System.identityHashCode(msg.obj));
16884
16885        mHandler.sendMessage(msg);
16886    }
16887
16888    @Override
16889    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16890        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16891
16892        final int realMoveId = mNextMoveId.getAndIncrement();
16893        final Bundle extras = new Bundle();
16894        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16895        mMoveCallbacks.notifyCreated(realMoveId, extras);
16896
16897        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16898            @Override
16899            public void onCreated(int moveId, Bundle extras) {
16900                // Ignored
16901            }
16902
16903            @Override
16904            public void onStatusChanged(int moveId, int status, long estMillis) {
16905                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16906            }
16907        };
16908
16909        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16910        storage.setPrimaryStorageUuid(volumeUuid, callback);
16911        return realMoveId;
16912    }
16913
16914    @Override
16915    public int getMoveStatus(int moveId) {
16916        mContext.enforceCallingOrSelfPermission(
16917                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16918        return mMoveCallbacks.mLastStatus.get(moveId);
16919    }
16920
16921    @Override
16922    public void registerMoveCallback(IPackageMoveObserver callback) {
16923        mContext.enforceCallingOrSelfPermission(
16924                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16925        mMoveCallbacks.register(callback);
16926    }
16927
16928    @Override
16929    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16930        mContext.enforceCallingOrSelfPermission(
16931                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16932        mMoveCallbacks.unregister(callback);
16933    }
16934
16935    @Override
16936    public boolean setInstallLocation(int loc) {
16937        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16938                null);
16939        if (getInstallLocation() == loc) {
16940            return true;
16941        }
16942        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16943                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16944            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16945                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16946            return true;
16947        }
16948        return false;
16949   }
16950
16951    @Override
16952    public int getInstallLocation() {
16953        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16954                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16955                PackageHelper.APP_INSTALL_AUTO);
16956    }
16957
16958    /** Called by UserManagerService */
16959    void cleanUpUser(UserManagerService userManager, int userHandle) {
16960        synchronized (mPackages) {
16961            mDirtyUsers.remove(userHandle);
16962            mUserNeedsBadging.delete(userHandle);
16963            mSettings.removeUserLPw(userHandle);
16964            mPendingBroadcasts.remove(userHandle);
16965            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16966        }
16967        synchronized (mInstallLock) {
16968            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16969            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16970                final String volumeUuid = vol.getFsUuid();
16971                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16972                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16973            }
16974            synchronized (mPackages) {
16975                removeUnusedPackagesLILPw(userManager, userHandle);
16976            }
16977        }
16978    }
16979
16980    /**
16981     * We're removing userHandle and would like to remove any downloaded packages
16982     * that are no longer in use by any other user.
16983     * @param userHandle the user being removed
16984     */
16985    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16986        final boolean DEBUG_CLEAN_APKS = false;
16987        int [] users = userManager.getUserIds();
16988        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16989        while (psit.hasNext()) {
16990            PackageSetting ps = psit.next();
16991            if (ps.pkg == null) {
16992                continue;
16993            }
16994            final String packageName = ps.pkg.packageName;
16995            // Skip over if system app
16996            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16997                continue;
16998            }
16999            if (DEBUG_CLEAN_APKS) {
17000                Slog.i(TAG, "Checking package " + packageName);
17001            }
17002            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17003            if (keep) {
17004                if (DEBUG_CLEAN_APKS) {
17005                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17006                }
17007            } else {
17008                for (int i = 0; i < users.length; i++) {
17009                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17010                        keep = true;
17011                        if (DEBUG_CLEAN_APKS) {
17012                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17013                                    + users[i]);
17014                        }
17015                        break;
17016                    }
17017                }
17018            }
17019            if (!keep) {
17020                if (DEBUG_CLEAN_APKS) {
17021                    Slog.i(TAG, "  Removing package " + packageName);
17022                }
17023                mHandler.post(new Runnable() {
17024                    public void run() {
17025                        deletePackageX(packageName, userHandle, 0);
17026                    } //end run
17027                });
17028            }
17029        }
17030    }
17031
17032    /** Called by UserManagerService */
17033    void createNewUser(int userHandle) {
17034        synchronized (mInstallLock) {
17035            mInstaller.createUserConfig(userHandle);
17036            mSettings.createNewUserLI(this, mInstaller, userHandle);
17037        }
17038        synchronized (mPackages) {
17039            applyFactoryDefaultBrowserLPw(userHandle);
17040            primeDomainVerificationsLPw(userHandle);
17041        }
17042    }
17043
17044    void newUserCreated(final int userHandle) {
17045        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17046        // If permission review for legacy apps is required, we represent
17047        // dagerous permissions for such apps as always granted runtime
17048        // permissions to keep per user flag state whether review is needed.
17049        // Hence, if a new user is added we have to propagate dangerous
17050        // permission grants for these legacy apps.
17051        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17052            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17053                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17054        }
17055    }
17056
17057    @Override
17058    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17059        mContext.enforceCallingOrSelfPermission(
17060                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17061                "Only package verification agents can read the verifier device identity");
17062
17063        synchronized (mPackages) {
17064            return mSettings.getVerifierDeviceIdentityLPw();
17065        }
17066    }
17067
17068    @Override
17069    public void setPermissionEnforced(String permission, boolean enforced) {
17070        // TODO: Now that we no longer change GID for storage, this should to away.
17071        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17072                "setPermissionEnforced");
17073        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17074            synchronized (mPackages) {
17075                if (mSettings.mReadExternalStorageEnforced == null
17076                        || mSettings.mReadExternalStorageEnforced != enforced) {
17077                    mSettings.mReadExternalStorageEnforced = enforced;
17078                    mSettings.writeLPr();
17079                }
17080            }
17081            // kill any non-foreground processes so we restart them and
17082            // grant/revoke the GID.
17083            final IActivityManager am = ActivityManagerNative.getDefault();
17084            if (am != null) {
17085                final long token = Binder.clearCallingIdentity();
17086                try {
17087                    am.killProcessesBelowForeground("setPermissionEnforcement");
17088                } catch (RemoteException e) {
17089                } finally {
17090                    Binder.restoreCallingIdentity(token);
17091                }
17092            }
17093        } else {
17094            throw new IllegalArgumentException("No selective enforcement for " + permission);
17095        }
17096    }
17097
17098    @Override
17099    @Deprecated
17100    public boolean isPermissionEnforced(String permission) {
17101        return true;
17102    }
17103
17104    @Override
17105    public boolean isStorageLow() {
17106        final long token = Binder.clearCallingIdentity();
17107        try {
17108            final DeviceStorageMonitorInternal
17109                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17110            if (dsm != null) {
17111                return dsm.isMemoryLow();
17112            } else {
17113                return false;
17114            }
17115        } finally {
17116            Binder.restoreCallingIdentity(token);
17117        }
17118    }
17119
17120    @Override
17121    public IPackageInstaller getPackageInstaller() {
17122        return mInstallerService;
17123    }
17124
17125    private boolean userNeedsBadging(int userId) {
17126        int index = mUserNeedsBadging.indexOfKey(userId);
17127        if (index < 0) {
17128            final UserInfo userInfo;
17129            final long token = Binder.clearCallingIdentity();
17130            try {
17131                userInfo = sUserManager.getUserInfo(userId);
17132            } finally {
17133                Binder.restoreCallingIdentity(token);
17134            }
17135            final boolean b;
17136            if (userInfo != null && userInfo.isManagedProfile()) {
17137                b = true;
17138            } else {
17139                b = false;
17140            }
17141            mUserNeedsBadging.put(userId, b);
17142            return b;
17143        }
17144        return mUserNeedsBadging.valueAt(index);
17145    }
17146
17147    @Override
17148    public KeySet getKeySetByAlias(String packageName, String alias) {
17149        if (packageName == null || alias == null) {
17150            return null;
17151        }
17152        synchronized(mPackages) {
17153            final PackageParser.Package pkg = mPackages.get(packageName);
17154            if (pkg == null) {
17155                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17156                throw new IllegalArgumentException("Unknown package: " + packageName);
17157            }
17158            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17159            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17160        }
17161    }
17162
17163    @Override
17164    public KeySet getSigningKeySet(String packageName) {
17165        if (packageName == null) {
17166            return null;
17167        }
17168        synchronized(mPackages) {
17169            final PackageParser.Package pkg = mPackages.get(packageName);
17170            if (pkg == null) {
17171                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17172                throw new IllegalArgumentException("Unknown package: " + packageName);
17173            }
17174            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17175                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17176                throw new SecurityException("May not access signing KeySet of other apps.");
17177            }
17178            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17179            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17180        }
17181    }
17182
17183    @Override
17184    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17185        if (packageName == null || ks == null) {
17186            return false;
17187        }
17188        synchronized(mPackages) {
17189            final PackageParser.Package pkg = mPackages.get(packageName);
17190            if (pkg == null) {
17191                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17192                throw new IllegalArgumentException("Unknown package: " + packageName);
17193            }
17194            IBinder ksh = ks.getToken();
17195            if (ksh instanceof KeySetHandle) {
17196                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17197                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17198            }
17199            return false;
17200        }
17201    }
17202
17203    @Override
17204    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17205        if (packageName == null || ks == null) {
17206            return false;
17207        }
17208        synchronized(mPackages) {
17209            final PackageParser.Package pkg = mPackages.get(packageName);
17210            if (pkg == null) {
17211                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
17212                throw new IllegalArgumentException("Unknown package: " + packageName);
17213            }
17214            IBinder ksh = ks.getToken();
17215            if (ksh instanceof KeySetHandle) {
17216                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17217                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17218            }
17219            return false;
17220        }
17221    }
17222
17223    private void deletePackageIfUnusedLPr(final String packageName) {
17224        PackageSetting ps = mSettings.mPackages.get(packageName);
17225        if (ps == null) {
17226            return;
17227        }
17228        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17229            // TODO Implement atomic delete if package is unused
17230            // It is currently possible that the package will be deleted even if it is installed
17231            // after this method returns.
17232            mHandler.post(new Runnable() {
17233                public void run() {
17234                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17235                }
17236            });
17237        }
17238    }
17239
17240    /**
17241     * Check and throw if the given before/after packages would be considered a
17242     * downgrade.
17243     */
17244    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17245            throws PackageManagerException {
17246        if (after.versionCode < before.mVersionCode) {
17247            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17248                    "Update version code " + after.versionCode + " is older than current "
17249                    + before.mVersionCode);
17250        } else if (after.versionCode == before.mVersionCode) {
17251            if (after.baseRevisionCode < before.baseRevisionCode) {
17252                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17253                        "Update base revision code " + after.baseRevisionCode
17254                        + " is older than current " + before.baseRevisionCode);
17255            }
17256
17257            if (!ArrayUtils.isEmpty(after.splitNames)) {
17258                for (int i = 0; i < after.splitNames.length; i++) {
17259                    final String splitName = after.splitNames[i];
17260                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17261                    if (j != -1) {
17262                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17263                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17264                                    "Update split " + splitName + " revision code "
17265                                    + after.splitRevisionCodes[i] + " is older than current "
17266                                    + before.splitRevisionCodes[j]);
17267                        }
17268                    }
17269                }
17270            }
17271        }
17272    }
17273
17274    private static class MoveCallbacks extends Handler {
17275        private static final int MSG_CREATED = 1;
17276        private static final int MSG_STATUS_CHANGED = 2;
17277
17278        private final RemoteCallbackList<IPackageMoveObserver>
17279                mCallbacks = new RemoteCallbackList<>();
17280
17281        private final SparseIntArray mLastStatus = new SparseIntArray();
17282
17283        public MoveCallbacks(Looper looper) {
17284            super(looper);
17285        }
17286
17287        public void register(IPackageMoveObserver callback) {
17288            mCallbacks.register(callback);
17289        }
17290
17291        public void unregister(IPackageMoveObserver callback) {
17292            mCallbacks.unregister(callback);
17293        }
17294
17295        @Override
17296        public void handleMessage(Message msg) {
17297            final SomeArgs args = (SomeArgs) msg.obj;
17298            final int n = mCallbacks.beginBroadcast();
17299            for (int i = 0; i < n; i++) {
17300                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17301                try {
17302                    invokeCallback(callback, msg.what, args);
17303                } catch (RemoteException ignored) {
17304                }
17305            }
17306            mCallbacks.finishBroadcast();
17307            args.recycle();
17308        }
17309
17310        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17311                throws RemoteException {
17312            switch (what) {
17313                case MSG_CREATED: {
17314                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17315                    break;
17316                }
17317                case MSG_STATUS_CHANGED: {
17318                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17319                    break;
17320                }
17321            }
17322        }
17323
17324        private void notifyCreated(int moveId, Bundle extras) {
17325            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17326
17327            final SomeArgs args = SomeArgs.obtain();
17328            args.argi1 = moveId;
17329            args.arg2 = extras;
17330            obtainMessage(MSG_CREATED, args).sendToTarget();
17331        }
17332
17333        private void notifyStatusChanged(int moveId, int status) {
17334            notifyStatusChanged(moveId, status, -1);
17335        }
17336
17337        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17338            Slog.v(TAG, "Move " + moveId + " status " + status);
17339
17340            final SomeArgs args = SomeArgs.obtain();
17341            args.argi1 = moveId;
17342            args.argi2 = status;
17343            args.arg3 = estMillis;
17344            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17345
17346            synchronized (mLastStatus) {
17347                mLastStatus.put(moveId, status);
17348            }
17349        }
17350    }
17351
17352    private final static class OnPermissionChangeListeners extends Handler {
17353        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17354
17355        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17356                new RemoteCallbackList<>();
17357
17358        public OnPermissionChangeListeners(Looper looper) {
17359            super(looper);
17360        }
17361
17362        @Override
17363        public void handleMessage(Message msg) {
17364            switch (msg.what) {
17365                case MSG_ON_PERMISSIONS_CHANGED: {
17366                    final int uid = msg.arg1;
17367                    handleOnPermissionsChanged(uid);
17368                } break;
17369            }
17370        }
17371
17372        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17373            mPermissionListeners.register(listener);
17374
17375        }
17376
17377        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17378            mPermissionListeners.unregister(listener);
17379        }
17380
17381        public void onPermissionsChanged(int uid) {
17382            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17383                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17384            }
17385        }
17386
17387        private void handleOnPermissionsChanged(int uid) {
17388            final int count = mPermissionListeners.beginBroadcast();
17389            try {
17390                for (int i = 0; i < count; i++) {
17391                    IOnPermissionsChangeListener callback = mPermissionListeners
17392                            .getBroadcastItem(i);
17393                    try {
17394                        callback.onPermissionsChanged(uid);
17395                    } catch (RemoteException e) {
17396                        Log.e(TAG, "Permission listener is dead", e);
17397                    }
17398                }
17399            } finally {
17400                mPermissionListeners.finishBroadcast();
17401            }
17402        }
17403    }
17404
17405    private class PackageManagerInternalImpl extends PackageManagerInternal {
17406        @Override
17407        public void setLocationPackagesProvider(PackagesProvider provider) {
17408            synchronized (mPackages) {
17409                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17410            }
17411        }
17412
17413        @Override
17414        public void setImePackagesProvider(PackagesProvider provider) {
17415            synchronized (mPackages) {
17416                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17417            }
17418        }
17419
17420        @Override
17421        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17422            synchronized (mPackages) {
17423                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17424            }
17425        }
17426
17427        @Override
17428        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17429            synchronized (mPackages) {
17430                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17431            }
17432        }
17433
17434        @Override
17435        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17436            synchronized (mPackages) {
17437                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17438            }
17439        }
17440
17441        @Override
17442        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17443            synchronized (mPackages) {
17444                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17445            }
17446        }
17447
17448        @Override
17449        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17450            synchronized (mPackages) {
17451                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17452            }
17453        }
17454
17455        @Override
17456        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17457            synchronized (mPackages) {
17458                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17459                        packageName, userId);
17460            }
17461        }
17462
17463        @Override
17464        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17465            synchronized (mPackages) {
17466                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17467                        packageName, userId);
17468            }
17469        }
17470
17471        @Override
17472        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17473            synchronized (mPackages) {
17474                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17475                        packageName, userId);
17476            }
17477        }
17478
17479        @Override
17480        public void setKeepUninstalledPackages(final List<String> packageList) {
17481            Preconditions.checkNotNull(packageList);
17482            List<String> removedFromList = null;
17483            synchronized (mPackages) {
17484                if (mKeepUninstalledPackages != null) {
17485                    final int packagesCount = mKeepUninstalledPackages.size();
17486                    for (int i = 0; i < packagesCount; i++) {
17487                        String oldPackage = mKeepUninstalledPackages.get(i);
17488                        if (packageList != null && packageList.contains(oldPackage)) {
17489                            continue;
17490                        }
17491                        if (removedFromList == null) {
17492                            removedFromList = new ArrayList<>();
17493                        }
17494                        removedFromList.add(oldPackage);
17495                    }
17496                }
17497                mKeepUninstalledPackages = new ArrayList<>(packageList);
17498                if (removedFromList != null) {
17499                    final int removedCount = removedFromList.size();
17500                    for (int i = 0; i < removedCount; i++) {
17501                        deletePackageIfUnusedLPr(removedFromList.get(i));
17502                    }
17503                }
17504            }
17505        }
17506
17507        @Override
17508        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17509            synchronized (mPackages) {
17510                // If we do not support permission review, done.
17511                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17512                    return false;
17513                }
17514
17515                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17516                if (packageSetting == null) {
17517                    return false;
17518                }
17519
17520                // Permission review applies only to apps not supporting the new permission model.
17521                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17522                    return false;
17523                }
17524
17525                // Legacy apps have the permission and get user consent on launch.
17526                PermissionsState permissionsState = packageSetting.getPermissionsState();
17527                return permissionsState.isPermissionReviewRequired(userId);
17528            }
17529        }
17530    }
17531
17532    @Override
17533    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17534        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17535        synchronized (mPackages) {
17536            final long identity = Binder.clearCallingIdentity();
17537            try {
17538                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17539                        packageNames, userId);
17540            } finally {
17541                Binder.restoreCallingIdentity(identity);
17542            }
17543        }
17544    }
17545
17546    private static void enforceSystemOrPhoneCaller(String tag) {
17547        int callingUid = Binder.getCallingUid();
17548        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17549            throw new SecurityException(
17550                    "Cannot call " + tag + " from UID " + callingUid);
17551        }
17552    }
17553}
17554